From tvssarma.omega9 at gmail.com Sat Jun 1 07:47:42 2013 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Sat, 1 Jun 2013 01:47:42 -0400 Subject: [Tutor] Quick Question on String Compare Message-ID: Hi, I had a quick question on how string compare works. If did '1001' <= '999' I get true. I know how the string compare works but I was wondering why it were so. Why doesn't the string length factor into the comparison? For example, If I compared character-by-character but also found how different the lengths are, I could avoid a wrong logical answer as in the example above. Any thoughts? Thanks -- 0 1 0 0 0 1 1 1 1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Jun 1 09:43:17 2013 From: __peter__ at web.de (Peter Otten) Date: Sat, 01 Jun 2013 09:43:17 +0200 Subject: [Tutor] Quick Question on String Compare References: Message-ID: Sarma Tangirala wrote: > I had a quick question on how string compare works. If did '1001' <= '999' > I get true. I know how the string compare works but I was wondering why it > were so. Why doesn't the string length factor into the comparison? For > example, If I compared character-by-character but also found how different > the lengths are, I could avoid a wrong logical answer as in the example > above. Any thoughts? If you took the string length into acount you would get the "wrong logical answer" for strings that don't look like numbers: >>> number_strings = ["2", "20", "100", "1"] >>> sorted(number_strings, key=lambda x: (len(x), x)) ['1', '2', '20', '100'] >>> names = ["Abe", "Peter", "Pete", "Jim", "Jack"] >>> sorted(names, key=lambda x: (len(x), x)) ['Abe', 'Jim', 'Zoe', 'Jack', 'Pete', 'Peter'] There is no one sort order that fits all use cases, but Python makes it easy to supply a custom key function that fits your needs. From andipersti at gmail.com Sat Jun 1 09:42:22 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Sat, 01 Jun 2013 09:42:22 +0200 Subject: [Tutor] Quick Question on String Compare In-Reply-To: References: Message-ID: <51A9A5DE.1030101@gmail.com> On 01.06.2013 07:47, Sarma Tangirala wrote: > I had a quick question on how string compare works. If did '1001' <= '999' > I get true. I know how the string compare works but I was wondering why it > were so. Why doesn't the string length factor into the comparison? Because usually you are interested in the lexicographical order when you compare strings. You wouldn't expect "pear" listed before "apple" in an ordinary dictionary, would you? > For example, If I compared character-by-character but also found how > different the lengths are, I could avoid a wrong logical answer as in > the example above. Why is it a "wrong logical answer"? Neither '1001' nor '999' are numbers but strings. If you want to compare them like numbers you need to convert them to numbers first. Bye, Andreas From wolfgang.maier at biologie.uni-freiburg.de Sat Jun 1 19:01:52 2013 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Sat, 1 Jun 2013 17:01:52 +0000 (UTC) Subject: [Tutor] Project Euler #8 References: <51A8F1D2.1070302@davea.name> Message-ID: Dave Angel davea.name> writes: > > > str_num = '1234567890' > > n = 5 > > > > strings = [str_num[i:i+5] for i in range(0, len(str_num)) if > > len(str_num[i:i+5])==5] > > If you changed the range() size, you could eliminate the extra if test. > After all, the only ones that'll be short are the last 4. Also, > xrange is better than range, if you ever try this on a really big > dataset. Good habit to get into, and in Python 3.x, the original range > is gone, and xrange is called range. > > strings = [str_num[i:i+5] for i in xrange(0, len(str_num-4)) ] > Of course, if you're really concerned about the size of your dataset, then you should combine xrange (or range in Python 3) with a generator expression instead of a list comprehension to yield substrings only one at a time. This is very easy to do: just replace your square brackets with parentheses: strings = (str_num[i:i+5] for i in xrange(0, len(str_num-4))) Since this is in expression you might find useful again for other tasks, you could encapsulate it in a (very short) function: def slider (s, window): return (s[i:i+window] for i in range(0, len(s)-window+1)) that you can use conveniently in a for loop: for substr in slider(str_num, 5): or in a comprehension, like: products = [product(substr) for substr in slider(str_num, 5)] for your code. Best, Wolfgang From cybervigilante at gmail.com Sun Jun 2 05:58:38 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 1 Jun 2013 20:58:38 -0700 Subject: [Tutor] when is a generator "smart?" Message-ID: It's a little unclear to me where generators are more efficient. Below I'm creating a list of non-even squares. I figured Python would be smart enough to see I only wanted a small slice of a large generated list, but as I increased y, Py got slower and eventually died of a memory error. If I don't make it into a list I get a type error. So where are generators more efficient? Or more specifically, how would i make this efficient and use the generator to only pick out the small 2:10 slice I really want, but leave the capability of the entire list if I wanted to slice and dice it in different ways further on? def uneven_squares(x,y): squarelist = (c**2 for c in range(x,y) if c%2 != 0) return squarelist #returning a generator print(list(uneven_squares(10,10000))[2:10]) #slows as y gets bigger, then dies -- Jim Ornhgvshy vf orggre guna htyl From dyoo at hashcollision.org Sun Jun 2 06:14:58 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 1 Jun 2013 21:14:58 -0700 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: Message-ID: > > > print(list(uneven_squares(10,10000))[2:10]) #slows as y gets bigger, then > dies > > You'll want to stick with sequence operations that do not force the entire generator's output. In this specific case, try itertools.islice. http://docs.python.org/2/library/itertools.html#itertools.islice -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Jun 2 06:20:25 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 02 Jun 2013 14:20:25 +1000 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: Message-ID: <51AAC809.5090406@pearwood.info> On 02/06/13 13:58, Jim Mooney wrote: > It's a little unclear to me where generators are more efficient. When there are a lot of items, and you access the items one at a time, not all at once. If there are only a few items, a list or tuple has less overhead and is easier to use. > Below I'm creating a list of non-even squares. By creating a list, you completely lose any benefit of a generator, since you access all the items in one big list. > I figured Python would be > smart enough to see I only wanted a small slice of a large generated > list, Nope. The standard CPython implementation is deliberately dumb. Advanced optimizing Python implementations like PyPy *may* be smarter. There are good reasons why Python *cannot* be very smart about this: - it cannot tell what list(...) will do until runtime, since "list" is just a name and may be replaced by a different function; - consequently it cannot tell what the slice [2:10] does until it has built the entire list. A smarter compiler, like PyPy, *may* be able to tell at runtime that list is the built-in list, and therefore do something special, but that requires a much more complicated compiler. As the reference implementation, CPython is deliberately simple, and will always remain that way. -- Steven From cybervigilante at gmail.com Sun Jun 2 07:14:16 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 1 Jun 2013 22:14:16 -0700 Subject: [Tutor] when is a generator "smart?" In-Reply-To: <51AAC809.5090406@pearwood.info> References: <51AAC809.5090406@pearwood.info> Message-ID: On 1 June 2013 21:20, Steven D'Aprano wrote: > On 02/06/13 13:58, Jim Mooney wrote: >> >> It's a little unclear to me where generators are more efficient. > > > When there are a lot of items, and you access the items one at a time, not > all at once. If there are only a few items, a list or tuple has less > overhead and is easier to use. So how does one access a generator one element at a time? I thought next would do that so I tried: print(next(uneven_squares(10,1000))) print(next(uneven_squares(10,1000))) print(next(uneven_squares(10,1000))) But I got the same answer every time. I'm just trying to see where a generator is more beneficial in practice and exactly how one accesses one element at a time without building a list. Jim From dyoo at hashcollision.org Sun Jun 2 07:32:41 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 1 Jun 2013 22:32:41 -0700 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AAC809.5090406@pearwood.info> Message-ID: > So how does one access a generator one element at a time? I thought > next would do that so I tried: > > print(next(uneven_squares(10,1000))) > print(next(uneven_squares(10,1000))) > print(next(uneven_squares(10,1000))) Each call to uneven_squares(10, 1000) creates a fresh iterator. You may want to bind it so that you can reuse the same value across multiple uses of next(). ####### us = uneven_squares(10, 1000) print(next(us)) print(next(us)) print(next(us)) ####### From bouncingcats at gmail.com Sun Jun 2 07:33:42 2013 From: bouncingcats at gmail.com (David) Date: Sun, 2 Jun 2013 15:33:42 +1000 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AAC809.5090406@pearwood.info> Message-ID: On 02/06/2013, Jim Mooney wrote: > On 1 June 2013 21:20, Steven D'Aprano wrote: >> On 02/06/13 13:58, Jim Mooney wrote: >>> >>> It's a little unclear to me where generators are more efficient. >> >> >> When there are a lot of items, and you access the items one at a time, >> not >> all at once. If there are only a few items, a list or tuple has less >> overhead and is easier to use. > > So how does one access a generator one element at a time? google: python generator example From dyoo at hashcollision.org Sun Jun 2 07:53:31 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 1 Jun 2013 22:53:31 -0700 Subject: [Tutor] Quick Question on String Compare In-Reply-To: References: Message-ID: The standard sorting in Python depends on a comparison operator. A quick and easy comparison operator that Python uses for strings is lexicographic ordering: http://en.wikipedia.org/wiki/Lexicographical_order The quick and dirty rule is: dictionary order, with each character consistently treated as a character. As you note, this doesn't "look" right when we're comparing strings with numbers. That's a common problem. Since it's not immediately clear from the computer's point of view what to do here, Python has no policy that favors humans. To make comparison work the way you want it to, you need to write it explicitly, as it does not come built-in. See: http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort From steve at pearwood.info Sun Jun 2 08:17:44 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 02 Jun 2013 16:17:44 +1000 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AAC809.5090406@pearwood.info> Message-ID: <51AAE388.6000804@pearwood.info> On 02/06/13 15:14, Jim Mooney wrote: > On 1 June 2013 21:20, Steven D'Aprano wrote: >> On 02/06/13 13:58, Jim Mooney wrote: >>> >>> It's a little unclear to me where generators are more efficient. >> >> >> When there are a lot of items, and you access the items one at a time, not >> all at once. If there are only a few items, a list or tuple has less >> overhead and is easier to use. > > So how does one access a generator one element at a time? I thought > next would do that so I tried: > > print(next(uneven_squares(10,1000))) > print(next(uneven_squares(10,1000))) > print(next(uneven_squares(10,1000))) > > But I got the same answer every time. That's because you create three independent generators, one after another. it = uneven_squares(10,1000) # "it" for "iterator" print(next(it)) print(next(it)) print(next(it)) You can also use the itertools module to slice a generator: list(itertools.islice(it, 5, 10, 2)) This call to islice will grab the 5th, 7th and 9th items from it, *starting at the current position*, and return an iterator. The call to list() converts that iterator to a list, so you can easily inspect the values. Here's an example: py> it = iter("abcdefghijklmnopqrstuvwxyz") py> next(it) 'a' py> next(it) 'b' py> list(itertools.islice(it, 5, 10, 2)) ['h', 'j', 'l'] py> next(it) 'm' -- Steven From davea at davea.name Sun Jun 2 12:39:05 2013 From: davea at davea.name (Dave Angel) Date: Sun, 02 Jun 2013 06:39:05 -0400 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: Message-ID: <51AB20C9.5070300@davea.name> On 06/01/2013 11:58 PM, Jim Mooney wrote: > It's a little unclear to me where generators are more efficient. I'm astounded nobody has asked you what version of Python this is for. in Python 2.x, the range(x,y) function produces the whole list, and then the expression around it converts that to a generator. That alone would make it waste tons of memory (and time) for large y. So I'll ASSUME you're using 3.x, or that you actually are using xrange below. > Below > I'm creating a list of non-even squares. I figured Python would be > smart enough to see I only wanted a small slice of a large generated > list, but as I increased y, Py got slower and eventually died of a > memory error. If I don't make it into a list I get a type error. So > where are generators more efficient? Or more specifically, how would i > make this efficient and use the generator to only pick out the small > 2:10 slice I really want, but leave the capability of the entire list > if I wanted to slice and dice it in different ways further on? > > def uneven_squares(x,y): > squarelist = (c**2 for c in range(x,y) if c%2 != 0) > return squarelist #returning a generator > > print(list(uneven_squares(10,10000))[2:10]) #slows as y gets bigger, then dies > So the real question is how to slice a generator without first converting it to a list. That's what iterator.islice() is for. Try (untested): import iterator def uneven_squares(x,y): .... print( iterator.islice(uneven_squares(10, 10000), 2, 10) ) -- DaveA From steve at pearwood.info Sun Jun 2 17:09:56 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 03 Jun 2013 01:09:56 +1000 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: Message-ID: <51AB6044.4050406@pearwood.info> On 02/06/13 13:58, Jim Mooney wrote: > def uneven_squares(x,y): > squarelist = (c**2 for c in range(x,y) if c%2 != 0) > return squarelist #returning a generator By the way, I should mention that there are better ways to write this. Or at least different :-) To start with, the *generator expression* (n**2 for n in range(start, end) if n%2 != 0) is simple enough that you don't need it to go inside a function. That's the beauty of generator expressions, you can work with them in-place just like a list comprehension. Given: start = 1000 end = 2000 it = (n**2 for n in range(start, end) if n%2 != 0) variable "it" is now a generator. Or you can just iterate straight over the generator expression, without a temporary variable holding it: for n in (n**2 for n in range(start, end) if n%2 != 0): ... By the way, a little bit of maths allows us to be more efficient. Any even number times itself is always even; any odd number times itself is always odd. If you trust me on this, you can skip the next two paragraphs, otherwise we can prove this: ===start maths=== Every even number a is of the form 2*n so a**2 = (2*n)**2 = 4*n**2 = 2*(2*n**2) Let m = 2*n**2 then a**2 = 4*n**2 = 2*m hence every even number squared is even. Every odd number b is of the form 2*n + 1 so b**2 = (2*n + 1)**2 = 4*n**2 + 4*n + 1 = 2*(2*n**2 + 2*n) + 1 Let m = 2*n**2 + 2*n then b**2 = 2*(2*n**2 + 2*n) + 1 = 2*m +1 hence every odd number squared is odd. ===end maths=== So we can simplify the generator expression and make it more efficient by just adjusting the starting value to an odd value, then stepping by two. (n**2 for n in range(start + 1 - start%2, end, 2)) Here's another way to create generators (in fact, this was the original way that generators were added to the language -- this came first, before generator expressions). def odd_squares(start, end): start += 1 - start%2 # force starting value to be odd assert start%2 == 1 for n in range(start, end, 2): yield n**2 it = odd_squares(100, 1000) We call "odd_squares" a generator function, or sometimes just a generator. Except for the use of "yield" instead of "return", it looks like an ordinary function, but it is rather special. When you *call* the generator function odd_squares, instead of executing the code body inside it, Python builds a generator object containing that code, and returns the generator object. So now the variable "it" contains a generator. Being a generator, we can retrieve the next value from "it" by calling the next() built-in, or we can grab them all at once by calling list(). Each time you call next(), the body of the code runs until it reaches a yield, then it returns a single value, and pauses, ready to be resumed from wherever it last got to. Calling a function always starts at the beginning of the function, and continues until it hits a return, then stops. Calling it again starts from the beginning again. When a function hits "return", it does three things: - clear whatever internal state the function has - exit the function - and provide to the caller whatever value has been returned. so each time you call a function, it always starts with a fresh state. Generators are different. When you call next() on a generator, the first time processing starts at the beginning of the code. But when it reaches a "yield", it does these things: - save the internal state of the generator - pause the generator - and provide whatever value has been yielded. Then, when you call next() again, instead of starting at the beginning, it starts from wherever it was when it paused. Whether you use a generator expression (n**2 for n in range(start, end)) or a generator function using yield, the same thing happens. The only difference is that generator expressions are syntactic sugar for a generator function, and so are more convenient but also more limited in what they can do. -- Steven From eryksun at gmail.com Sun Jun 2 17:22:35 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 2 Jun 2013 11:22:35 -0400 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: Message-ID: On Sat, Jun 1, 2013 at 11:58 PM, Jim Mooney wrote: > > def uneven_squares(x,y): > squarelist = (c**2 for c in range(x,y) if c%2 != 0) > return squarelist #returning a generator > > print(list(uneven_squares(10,10000))[2:10]) #slows as y gets bigger, then dies I think you said you switched back to using Python 2.x. If that's still the case, remember to use xrange() for a case like this. 2.x range() is a list factory function: >>> r = range(10, 10000) >>> itr = iter(r) >>> type(r), type(itr) (, ) xrange is a type: >>> xr = xrange(10, 10000) >>> itxr = iter(xr) >>> type(xr), type(itxr) (, ) Instead of using syntactic sugar like a generator expression, use a generator function so you can see what it's doing: def uneven_squares(x, y): for c in xrange(x, y): if c % 2 != 0: yield c ** 2 >>> g = uneven_squares(10, 10000) >>> type(g) The compiler flags the code as a generator. Evaluation of generator code is special-cased. It does all of the normal call setup, creates a frame to run the code, but then instead of evaluating the frame it returns a new generator. The next() method (3.x __next__) evaluates the frame up to a yield: >>> g.next() 121 >>> next(g) # use built-in next() 169 When the frame returns instead of yielding, the generator raises StopIteration. For example: def gen(): yield 1 return yield 2 # never gets here >>> list(gen()) [1] Others have already mentioned using itertools.islice(). This takes an iterable/iterator, plus arguments for (start, stop, step) like built-in slice(). In case you're unfamiliar with the latter, it creates a a slice object for use in subscription. For example: >>> r = range(10) >>> s = slice(5) # [:5] >>> r[s] [0, 1, 2, 3, 4] >>> s = slice(5, None) # [5:] >>> r[s] [5, 6, 7, 8, 9] >>> s = slice(None, 5, 2) # [:5:2] >>> r[s] [0, 2, 4] >>> s = slice(None, None, 3) # [::3] >>> r[s] [0, 3, 6, 9] Since many iterators don't support subscription, let alone slicing, itertools.islice is a convenient alternative: >>> g = uneven_squares(10, 10000) >>> tuple(islice(g, 5)) # start=0,stop=5,step=1 (121, 169, 225, 289, 361) >>> set(islice(g, 3)) set([441, 625, 529]) islice returns an iterator, so it can be used efficiently to build other sequence types, such as tuple() and set(). The second islice starts at 21**2 because the previous islice stopped at 19**2, i.e.t he "start" and "stop" arguments are relative to the current position in the iteration sequence. From cybervigilante at gmail.com Sun Jun 2 18:56:50 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 2 Jun 2013 09:56:50 -0700 Subject: [Tutor] when is a generator "smart?" In-Reply-To: <51AB20C9.5070300@davea.name> References: <51AB20C9.5070300@davea.name> Message-ID: On 2 June 2013 03:39, Dave Angel wrote: > On 06/01/2013 11:58 PM, Jim Mooney wrote: > I'm astounded nobody has asked you what version of Python this is for. in > Python 2.x, the range(x,y) function produces the whole list, and then the > expression around it converts that to a generator. That alone would make it > waste tons of memory (and time) for large y. > > So I'll ASSUME you're using 3.x, or that you actually are using xrange > below. Using Python 2.7 on Windows 7 Good point - subtle difference. I'll have to make that more clear with an autohotkey keyboard macro since I started with 3.3, discovered a lot of stuff is still only for 2.7, and so went back to 2.7, which I'm now using. I still sometimes type input instead of that annoying raw_input and get a weird error. It's a bit confusing since, as a learner, some things have been backported, so there is no simple demarcation and there's already a lot to remember, let alone differences. I'll be glad when this all settles out, but Py 3 has been out awhile and an awful lot seems to only be for 2.7 Thanks to everyone for the useful tips on generators and PyDifferences. They all go into Clipmate ;') Jim From marc.tompkins at gmail.com Mon Jun 3 02:23:38 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 2 Jun 2013 17:23:38 -0700 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On Sun, Jun 2, 2013 at 9:56 AM, Jim Mooney wrote: > I still sometimes type input instead of that annoying raw_input and get a > weird error. Here's a nifty tip to get around that - and to eliminate one more thing you'd have to change later, if you switch back to 3. Put this near the top of your code (before any calls to input()): try: input = raw_input except NameError: pass Now you can just use input(), and it will have the 3.x behavior in either version. I'll be glad when this all settles out, but Py 3 has been out awhile and an > awful lot seems to only be for 2.7 > I suspect it's going to be like this for a while yet. The differences between 2.x and 3 _seem_ superficial, but some of them are pretty fundamental - so packages that do anything non-trivial really need major rewrites, and then they need to be maintained for both versions. It's sort of analogous to writing a native iOS app, and porting it as a native Android app, and maintaining both. It can be done, but it requires a lot of effort and usually more than a one-man dev team. I saw a quote a long time ago; I'd love to attribute it properly, but...: "God created the world in just seven days. But then, He had no installed base." -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Mon Jun 3 04:50:48 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 2 Jun 2013 19:50:48 -0700 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On 2 June 2013 17:23, Marc Tompkins wrote: > > I saw a quote a long time ago; I'd love to attribute it properly, but...: > "God created the world in just seven days. But then, He had no installed > base." Using Python 2.7 on Windows 7 In regard to that, I just tried importing Tkinter, according to a guide I'm using. Except the guide is using tkinter and not Tkinter, but Py27 has Tkinter. Lord knows why they bothered to change one lousy letter - it would be less confusing to have given it an entirely new name like notyourmothersKinter ;') Also, lib-tk didn't have __init__ for some reason so when I changed to Big T for Py27 it still didn't import. I put __init__ in, and still no luck, so I put lib-tk into PYTHONPATH and it worked, but then I got ambitious with PYTHONPATH and caused a bigger problem (below). So far, except for changing tkinter back to Tkinter, all the basic programs I've tried so far work the same, so I'm mystified why they bothered to change only that one letter. At least raw_input and input are obvious changes. I think hit-you-in-the-face changes are better than creeping changes. Even though it was in between major versions, which I didn't like, I decided on Python instead of Ruby since Python does a lot more stuff, and I love enforced parentheses (no style-wars, dizzying nested braces, or tiresome deciding what style to use, which I recall from webmastering.) But at times it gets confusing. I searched the web for differences between 2.7 and 3.3, but instead of a simple listing for beginners, every reference I found went into depth so complex I don't fathom it at this point. Rather like much of the docs, which seem to assume you already know what you're doing, which I don't. What I'm looking for is something basic like this simple memory-jogging list I'm slowly building in Clipmate as I get unconfused ;') Py 2.7, Py 3.3 raw_input, input print, print() int a / int b = integer division, int a / int b = normal division and // is int division 'my %s ate my %' % ('dog','shoes'), 'my {0} ate my {1}'.format('dog','shoes') --backported range makes a list, range makes an iterator (xrange for an iterator in 2.7) sort() sorts in place, sorted() returns a list - actually, I think that's in both recent Pys. Tkinter is now tkinter - Lord knows why they bothered doing that On top of that Py 3.3 just died on me by trying to run 2.7s codec, so I realized PYTHONPATH was just causing trouble and got rid of it: C:\Python33>python Fatal Python error: Py_Initializ File "C:\Python27\Lib\encoding raise CodecRegistryError,\ But it's always fun to see a Fatal Error. It's no doubt conflicting with Windows and its awful registry, so now tkinter/Tkinter works on both Pys and the problems are solved - after a few hours. However, I did find I was wrong to blame PyScripter. Since I don't have Wing Pro, which will do multiple Pys easily, I set up Wing 101 for Py 2.7 and PyScripter for Py 3.3. When PyScripter failed twice I blamed it, but I now realize each time was when I went fiddling with PYTHONPATH, which works much more nicely on Windows now that it's not there at all ;') This may all seem overly complex for beginning, but I'm patient and I figure I'll have to learn the differences sooner or later, since 2.7 is lingering. Besides that, I liked the Lutz books and got both the beginner Learning "Python," to be followed by the climb-the-mountain "Programming Python." Only Programming Python has all examples in 3 and scants 2, while the only "Learning Python" book available is mostly for 2 (I think the new edition of "Learning" comes out this month, but I'm all spent out on books for now.) So I'll be going back and forth at some point anyway. Someday I may get back to learning Python. Still, it's all in good fun. Tracking this stuff down is better than reading a detective novel ;') Jim From eryksun at gmail.com Mon Jun 3 05:33:17 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 2 Jun 2013 23:33:17 -0400 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On Sun, Jun 2, 2013 at 10:50 PM, Jim Mooney wrote: > In regard to that, I just tried importing Tkinter, according to a > guide I'm using. Except the guide is using tkinter and not Tkinter, > but Py27 has Tkinter. Lord knows why they bothered to change one lousy > letter - it would be less confusing to have given it an entirely new > name like notyourmothersKinter ;') Also, lib-tk didn't have __init__ > for some reason so when I changed to Big T for Py27 it still didn't > import. I put __init__ in, and still no luck, so I put lib-tk into > PYTHONPATH and it worked, but then I got ambitious with PYTHONPATH and > caused a bigger problem (below). The base sys.path configured in the registry already has lib-tk: C:\>reg query hklm\software\python\pythoncore\2.7\pythonpath HKEY_LOCAL_MACHINE\software\python\pythoncore\2.7\pythonpath (Default) REG_SZ C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk In 2.x, lib-tk needs to be on sys.path because it isn't a package. In 3.3, it was reorganized into the tkinter package. A lot more changed than simply Tkinter => tkinter. See PEP 3108 for a mapping between the two: http://www.python.org/dev/peps/pep-3108/#tkinter-package From steve at pearwood.info Mon Jun 3 05:35:02 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 03 Jun 2013 13:35:02 +1000 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: <51AC0EE6.20509@pearwood.info> On 03/06/13 12:50, Jim Mooney wrote: > In regard to that, I just tried importing Tkinter, according to a > guide I'm using. Except the guide is using tkinter and not Tkinter, > but Py27 has Tkinter. Lord knows why they bothered to change one lousy > letter - it would be less confusing to have given it an entirely new > name like notyourmothersKinter ;') Consistency with the recommended style guide for Python libraries. Modules should be written in lowercase. For historical reasons, some modules, like tkinter, weren't. Prior to Python 3, that couldn't be changed for backwards compatibility. But Python 3 was allowed to break backwards compatibility for the sake of consistency. For the sake of a little bit of pain during the transition, the end result will be a better product in the future. -- Steven From eryksun at gmail.com Mon Jun 3 05:43:22 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 2 Jun 2013 23:43:22 -0400 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On Sun, Jun 2, 2013 at 11:33 PM, eryksun wrote: > In 3.3, it was reorganized into the tkinter package Sorry, that should have been 3.x. From cybervigilante at gmail.com Mon Jun 3 06:44:14 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 2 Jun 2013 21:44:14 -0700 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On 2 June 2013 20:33, eryksun wrote: > > The base sys.path configured in the registry already has lib-tk: > > C:\>reg query hklm\software\python\pythoncore\2.7\pythonpath > > HKEY_LOCAL_MACHINE\software\python\pythoncore\2.7\pythonpath > (Default) REG_SZ > C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk Using Python 2.7 on Windows 7 pythonpath turned out to not be in pythoncore, so I was baffled at the source of the original problem. Then I searched the registry for pythonpath and it was in an entry for an IDE I had just installed, didn't like, and uninstalled, but it didn't clean up the registry (a lot of programs do that). Only its pythonpath was for 3.3, explaining the trouble, since installing was the Last thing I did. I forgot that the counter to the Law of Unintended Consequences is "What did I do last?" -- Jim Ornhgvshy vf orggre guna htyl From shreyas314159 at gmail.com Mon Jun 3 08:09:36 2013 From: shreyas314159 at gmail.com (Shreyas Prakash) Date: Mon, 3 Jun 2013 11:39:36 +0530 Subject: [Tutor] Problem importing modules. Message-ID: I am using Python 2.7 I tried importing a module named hello.py I got this error message Traceback (most recent call last): File "", line 1, in import hello ImportError: No module named hello I am not sure why, Can you please give me more insight about the proper syntax and the PYTHONPATH directory. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Mon Jun 3 08:56:58 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 3 Jun 2013 02:56:58 -0400 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On Mon, Jun 3, 2013 at 12:44 AM, Jim Mooney wrote: > On 2 June 2013 20:33, eryksun wrote: > >> >> The base sys.path configured in the registry already has lib-tk: >> >> C:\>reg query hklm\software\python\pythoncore\2.7\pythonpath >> >> HKEY_LOCAL_MACHINE\software\python\pythoncore\2.7\pythonpath >> (Default) REG_SZ >> C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk > > Using Python 2.7 on Windows 7 > > pythonpath turned out to not be in pythoncore, so I was baffled at the > source of the original problem. Then I searched the registry for > pythonpath and it was in an entry for an IDE I had just installed, > didn't like, and uninstalled, but it didn't clean up the registry (a > lot of programs do that). Only its pythonpath was for 3.3, explaining > the trouble, since installing was the Last thing I did. I forgot that > the counter to the Law of Unintended Consequences is "What did I do > last?" I looked into PC/getpathp.c. The value of PythonPath shown above is only a fallback for when Python is embedded. Otherwise the interpreter can determine sys.prefix from the exe path, and substitute it for the dots in the following hard-coded path: .\DLLs;.\lib;.\lib\plat-win;.\lib\lib-tk However, if PythonPath has subkeys, it always adds the default value of each subkey to sys.path. I created a subkey to test this, but otherwise I haven't used this feature. As to the problem you describe, I'm mystified. Registry settings (except environment variables) won't bleed over between Python installations or across application settings in the registry. That was probably just a private PYTHONPATH setting of the IDE, used for starting the interpreter as a subprocess. From cybervigilante at gmail.com Mon Jun 3 09:41:58 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 3 Jun 2013 00:41:58 -0700 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On 2 June 2013 23:56, eryksun wrote: > On Mon, Jun 3, 2013 at 12:44 AM, Jim Mooney wrote: >> On 2 June 2013 20:33, eryksun wrote: > > I looked into PC/getpathp.c. The value of PythonPath shown above is > only a fallback for when Python is embedded. Otherwise the interpreter > can determine sys.prefix from the exe path, and substitute it for the > dots in the following hard-coded path: > > .\DLLs;.\lib;.\lib\plat-win;.\lib\lib-tk Using Python 2.7 on Windows 7 Ah, useful. A lot more than is on windows path and PYTHONPATH obviously gets snuck in there. Sure enough, I queried sys.path and there's a Lot more in there. But even that wasn't everything since I saw RLPy and vtk had also set up their own system variables when I checked the environment. But those are special variables. From now on if I'm not sure something is on the path I can just query sys.path and see if it's there. Good to know. If I dump a package (not sure how to do that beyond just deleting it, but I've tried some bad ones, so I'd like to) how do I remove it from sys.path, or do I need to? I know the windows path and the registry have a bad habit of accumulating stuff that is no longer there, and just keeping it. Programs add to the windows path, but when you uninstall them, don't delete from the path, and it grows and grows. -- Jim Ornhgvshy vf orggre guna htyl From alan.gauld at btinternet.com Mon Jun 3 09:56:09 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 03 Jun 2013 08:56:09 +0100 Subject: [Tutor] Problem importing modules. In-Reply-To: References: Message-ID: On 03/06/13 07:09, Shreyas Prakash wrote: > I am using Python 2.7 > > I tried importing a module named hello.py > > I got this error message > > Traceback (most recent call last): File "", line 1, in import hello > ImportError: No module named hello > > I am not sure why, Can you please give me more insight about the proper > syntax and the PYTHONPATH directory. Please use plain text emails otherwise the formatting gets all messed up (as in the error message above) The most likely problem is that the folder containing hello.py is not in your import path. You can fix that by changing your PYTHONPATH environment variable or by modifying sys.path. If you are using Windows then the PYTHONPATH solution is documented in my tutor in the Getting Started topic. It describes how to set PATH but the process for PYTHONPATH is exactly the same. Otherwise tell us which OS you are using and we can help. (Or Google environment variable for your OS, there are lots of web pages that describe the process!) hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Mon Jun 3 11:21:12 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 03 Jun 2013 10:21:12 +0100 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On 03/06/2013 08:41, Jim Mooney wrote: > On 2 June 2013 23:56, eryksun wrote: >> On Mon, Jun 3, 2013 at 12:44 AM, Jim Mooney wrote: >>> On 2 June 2013 20:33, eryksun wrote: > > >> >> I looked into PC/getpathp.c. The value of PythonPath shown above is >> only a fallback for when Python is embedded. Otherwise the interpreter >> can determine sys.prefix from the exe path, and substitute it for the >> dots in the following hard-coded path: >> >> .\DLLs;.\lib;.\lib\plat-win;.\lib\lib-tk > > Using Python 2.7 on Windows 7 > > Ah, useful. A lot more than is on windows path and PYTHONPATH > obviously gets snuck in there. Sure enough, I queried sys.path and > there's a Lot more in there. But even that wasn't everything since I > saw RLPy and vtk had also set up their own system variables when I > checked the environment. But those are special variables. From now on > if I'm not sure something is on the path I can just query sys.path and > see if it's there. Good to know. > > If I dump a package (not sure how to do that beyond just deleting it, > but I've tried some bad ones, so I'd like to) how do I remove it from > sys.path, or do I need to? I know the windows path and the registry > have a bad habit of accumulating stuff that is no longer there, and > just keeping it. Programs add to the windows path, but when you > uninstall them, don't delete from the path, and it grows and grows. > On Windows Vista Control Panel->System->Advanced System Settings->System Properties->Advanced->Environment Variables. The path is displayed as a user setting and a system setting, edit either at your own risk. Programs are available to clear unused settings from the registry. I use them quite happily but if you're unsure of what you're doing I'd just leave things alone, you'll probably sleep better for it :) -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From md123 at nycap.rr.com Mon Jun 3 16:01:14 2013 From: md123 at nycap.rr.com (Matt D) Date: Mon, 03 Jun 2013 10:01:14 -0400 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) Message-ID: <51ACA1AA.6020500@nycap.rr.com> Hello, I am using an open source wxPython GUI that I like very very much. I have ideas about some modifications I need but I cannot be bothering the author too much so I must learn some very specific things about Python in order to make the modification myself. First, I need some help understanding the code behind this GUI. From reading the comments I understand that the part of the program written in C++ sends a Python pickled dictionary to a msg_queue and when Python decodes the pickle the TextCtrl fields (in the wxPython GUI I am using) receive/display the appropriate values. And as new messages are received by Python the GUI fields are cleared to display the new values. For starters I would like the values to be displayed on the GUI in some sort of a scrolling panel as they are cleared from the TextCtrl fields so the user can watch recent activity. I dont know what the best way to do this would be; the wxpython.scrolledPanel widget? I am unclear if this can be put on the same GUI pane as the TextCtrl fields are and I am unclear about if I can take the values from the TextCtrl fields or have to use the pickle or what? I dont see any variables declared (like in Visual Basic) so its not like I can just make a list and a textbox and print it. More importantly I need to save the values from the TextCtrl fields, preferable in a CSV file, for later inspection. From looking at the Logging HOWTO and the Logging Cookbook I see there are alot of loggers available, or ways to log, but they all look like they are orientated towards exception handling and debugging so I am unsure what is the best way to go about this; maybe wxLogTextCtrl ? Utimately I need to log the values from the TextCtrl fields in a row of comma separated values adding a time/date stamp as one of the values. I need this log so the data can easily be worked on in excel or SAS. I need the time/date stamp for time series analysis. I attached the code behind the wxPythoin GUI I am using. Any help will be much appreciated. Thanks in advance -- Matt D ------------ -------------- next part -------------- A non-text attachment was scrubbed... Name: op25_traffic_pane.py Type: text/x-python Size: 4967 bytes Desc: not available URL: From oscar.j.benjamin at gmail.com Mon Jun 3 16:22:50 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 3 Jun 2013 15:22:50 +0100 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On 3 June 2013 03:50, Jim Mooney wrote: > Py 2.7, Py 3.3 > raw_input, input There are good reasons for this change. Marc already suggested a solution for writing code that runs under both versions. > print, print() If you put "from __future__ import print_function" at the top of your module you can use the same print function in Python 2.6/2.7 and 3.x. I recommend doing this rather than bothering with the 2.x print statement. > int a / int b = integer division, int a / int b = normal division and > // is int division "from __future__ import division" makes 2.6/2.7 behave like 3.x here. Note that the floor division operator '//' is available in all versions since 2.2 and always has the same meaning. Again there are good reasons for this change and I certainly approve of it. > 'my %s ate my %' % ('dog','shoes'), 'my {0} ate my > {1}'.format('dog','shoes') --backported Both % and .format work in all versions since 2.6: there is no difference in 3.x. There are no plans to remove % formatting so just use whichever you like. > range makes a list, range makes an iterator (xrange for an iterator in 2.7) Similar to Marc's suggestion earlier: try: range = xrange except NameError: pass The newer range is IMO better and should be preferred over the older one. > sort() sorts in place, sorted() returns a list - actually, I think > that's in both recent Pys. That is the same in every Python since Python 2.4 (when sorted() was introduced). The same thing happens for reverse and reversed: >>> a = [1,2,3] >>> a [1, 2, 3] >>> a.reverse() >>> a [3, 2, 1] >>> reversed([1,2,3]) # reversed returns an iterator >>> list(reversed([1,2,3])) # so we'll turn it into a list [3, 2, 1] > Tkinter is now tkinter - Lord knows why they bothered doing that I think the expectation when planning the 2.x to 3.x transition was that most people writing code for both simultaneously would use automatic code translation. This kind of thing is easily fixed automatically but that's overkill when writing small scripts. The recommendation for someone learning Python was expected to be: just pick a version and only use books/tutorials/documentation for that version. There are other differences between 2.x and 3.x that you have not mentioned. It doesn't really affect my own scientific programming but the biggest difference is in text handling. Python 3.x uses unicode for all text by default and uses type safety to protect users from mixing encoded bytes with unicode text. This is a big change and was, I think, a big driving factor in the decision to introduce a backward incompatible version transition for Python. Once that decision was made it created the opportunity to make lots of other small backward incompatible changes (e.g. Tkinter -> tkinter). Oscar From cybervigilante at gmail.com Mon Jun 3 20:13:54 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 3 Jun 2013 11:13:54 -0700 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On 3 June 2013 07:22, Oscar Benjamin wrote: > If you put "from __future__ import print_function" at the top of your > module you can use the same print function in Python 2.6/2.7 and 3.x. > I recommend doing this rather than bothering with the 2.x print > statement. Using Python 2.7 on Windows 7 That's handy. When I went backward from 3.3 to 2.7, one of the few things I missed at my level was end= and sep= in print() .format() was already backported since I'd learned that. I do like it .format() better unless you get too fancy with those {}s. I dislike the % format for some reason. It just looks ugly to me. And as it says in first sentence of The Zen of Python from this.py: "Ornhgvshy vf orggre guna htyl." As a programming exercise I've been trying to translate Ancient Pythonaic back to English, but I don't follow Tim Peter's obfuscated little program yet. Ancient Pythonaic will probably never rival Klingon ;') Ah, question just came up. Since I have two pys, when a module is ported from 2.7 to 3.2 does it always have a different name? If the names are the same i can see where I can get confused with a pip install. Unless it is true that if I use pip-3.3 it will always install a 3.3 module, and if I use pip-2.7 it will always install a 2.7 module. I'd get rid of Py 3.3 for now to avoid confusion, but at some point, since a lot has not been ported to 3.3 and my second Lutz book uses 3.3 exclusively, I'll probably need them both anyway. Or I'll get around to installing virtual environments. But I've already done too much extraneous fooling around when I should be learning more Py. Enough with setting up my environment and editors, already. I'm sick of it. I'm done with editor tryouts. Wing 101 is just fine but 101 won't do two Pys without constant changing every time. The pro version will and it's on my buy list. I judge a restaurant by it's coffee, and so far of all the editors I tried, Wing is the most intuitive and least annoying for Py, and it's thoughtful even on small things, like needing only one dropdown to comment out a block, while others needed two. That counts if you use commenting-out and print() as the poor man's debugger. I was hot to have a debugger but once I learned it I haven't used it since ;') commenting-out, print(), staring-at, and getting a cup of coffee seem to work best for now. Maybe later, too. I'm beginning to feel that if it's longer than a page and looks like it needs a debugger, it needs breaking up so it doesn't look that way. My brain can only hold so much before becoming fozzled, and I have a terrible memory. Jim From alan.gauld at btinternet.com Mon Jun 3 20:38:27 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 03 Jun 2013 19:38:27 +0100 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51ACA1AA.6020500@nycap.rr.com> References: <51ACA1AA.6020500@nycap.rr.com> Message-ID: On 03/06/13 15:01, Matt D wrote: > I am using an open source wxPython GUI that I like very very much. I > have ideas about some modifications I need but I cannot be bothering the > author too much so I must learn some very specific things about Python OK, we can help on the python bits but not so much on the wxPython library. For that you'd be better off using the wxPython mailing list. > For starters I would like the values to be displayed on the GUI in some > sort of a scrolling panel as they are cleared from the TextCtrl fields Assuming the GUI uses a standard Text control then I think it should be possible to turn that into a scrolled pane and then just stop the delete code from deleting. ie make the new text appear below the existing stuff. Is that what you want? I'm fairly sure you can add scroll bars to the wxPython Text widget... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kwpolska at gmail.com Mon Jun 3 20:47:15 2013 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Mon, 3 Jun 2013 20:47:15 +0200 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On Mon, Jun 3, 2013 at 8:13 PM, Jim Mooney wrote: > > On 3 June 2013 07:22, Oscar Benjamin wrote: > > > If you put "from __future__ import print_function" at the top of your > > module you can use the same print function in Python 2.6/2.7 and 3.x. > > I recommend doing this rather than bothering with the 2.x print > > statement. > > Using Python 2.7 on Windows 7 > > That's handy. When I went backward from 3.3 to 2.7, one of the few > things I missed at my level was end= and sep= in print() .format() > was already backported since I'd learned that. I do like it .format() > better unless you get too fancy with those {}s. I dislike the % format > for some reason. It just looks ugly to me. And as it says in first > sentence of The Zen of Python from this.py: "Ornhgvshy vf orggre guna > htyl." > > As a programming exercise I've been trying to translate Ancient > Pythonaic back to English, but I don't follow Tim Peter's obfuscated > little program yet. Ancient Pythonaic will probably never rival > Klingon ;') It is just rot13. In Python 2, `str.decode('rot13')` would be enough. In Python 3, it doesn?t seem to happen so easily. (If anyone knows how to do it, please share!) > Ah, question just came up. Since I have two pys, when a module is > ported from 2.7 to 3.2 does it always have a different name? It never does. And in case it does, the developers are idiots. > If the names are the same i can see where I can get confused with a pip > install. Unless it is true that if I use pip-3.3 it will always > install a 3.3 module, and if I use pip-2.7 it will always install a > 2.7 module. I'd get rid of Py 3.3 for now to avoid confusion, but at > some point, since a lot has not been ported to 3.3 http://python3wos.appspot.com/ seems to think otherwise. 60.5% of the top 200 packages are ported, and two more are getting close (werkzeug+flask[0]). [0]: http://www.reddit.com/r/Python/comments/1fd69b/werkzeug_and_flask_git_repositories_have_early/ -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From cybervigilante at gmail.com Mon Jun 3 22:36:45 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 3 Jun 2013 13:36:45 -0700 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On 3 June 2013 11:47, Chris ?Kwpolska? Warrick wrote: > >> Ah, question just came up. Since I have two pys, when a module is >> ported from 2.7 to 3.2 does it always have a different name? > > It never does. And in case it does, the developers are idiots. Using Python 2.7 on Windows 7 So to clarify, the module names are the same on 2.7 and 3.3. Does that mean the module writers set the module so it will only install on the proper Py version, failing if it can't find it, so I don't have to think about that? Incidentally, for those nutty enough to run two Pys on Win, with Wing 101, I realized you can get Wing 101 to run either, without having to reconfigure it all the time, by setting up a Guest account in Windows, and configuring the second Wing for Py 3.3, run as Guest, with the primary as 2.7. This is helpful since some online sources I read are for one Py and some are for another. Jim From oscar.j.benjamin at gmail.com Mon Jun 3 23:41:28 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 3 Jun 2013 22:41:28 +0100 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On 3 June 2013 21:36, Jim Mooney wrote: > So to clarify, the module names are the same on 2.7 and 3.3. Does that > mean the module writers set the module so it will only install on the > proper Py version, failing if it can't find it, so I don't have to > think about that? Maybe or maybe not. When you run 'python setup.py install' (this happens implicitly when using pip), Python will try to run the setup.py script. At this point the script can do anything that its author likes. It could check for versions, it could just install and be broken, it could delete random files or damage your system in a malicious way. The author may have written the package at a time when Python 3 didn't exist so they didn't see the need to check for Python version and wrote code that wouldn't work in Python 3. There is progress on improving this situation by formalising the metadata that is supplied with Python packages so that it can be used more effectively by tools such as pip. The current (unaccepted) PEP for this is here (see the environment markers section): http://www.python.org/dev/peps/pep-0426/ > Incidentally, for those nutty enough to run two Pys on Win, with Wing > 101, I realized you can get Wing 101 to run either, without having to > reconfigure it all the time, by setting up a Guest account in Windows, > and configuring the second Wing for Py 3.3, run as Guest, with the > primary as 2.7. This is helpful since some online sources I read are > for one Py and some are for another. If you have py.exe (which you should if you've installed Python 3.3 on Windows) then you can run any installed Python version as 'py -2.7 myscript.py' or 'py -3.3 myscript.py' to choose the version of Python that will run myscript.py. I find it easier and clearer to do that explicitly on the command line when I want to test different versions. Oscar From bgailer at gmail.com Tue Jun 4 01:15:17 2013 From: bgailer at gmail.com (bob gailer) Date: Mon, 03 Jun 2013 19:15:17 -0400 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: Message-ID: <51AD2385.4050907@gmail.com> On 6/1/2013 11:58 PM, Jim Mooney wrote: > squarelist = (c**2 for c in range(x,y) if c%2 != 0) can be simplified to: squarelist = (c**2 for c in range(x,y,2)) as long as x is odd. -- Bob Gailer 919-636-4239 Chapel Hill NC From michaelsparks37 at gmail.com Tue Jun 4 01:32:34 2013 From: michaelsparks37 at gmail.com (Michael Sparks) Date: Mon, 3 Jun 2013 16:32:34 -0700 Subject: [Tutor] I think I found what I'm looking for. Message-ID: speech.py is a Python module that provides a clean interface to Windows's voice recognition and text-to-speech capabilities. But it requires Windows XP or Vista, and Python 2.4 or 2.5. I use Windows 7. another one I found; Dragonfly is a speech recognition framework. It is a Python package which offers a high-level object model and allows its users to easily write scripts, macros, and programs which use speech recognition. I think that I'm satisfied with speech.py but it might not work on Windows 7. I'm very interested in Dragonfly but I don't think that I've ever used a framework or even know what a framework is. before you answer my question. I'm going to sourceforge to see if there is any speech recognition software out there. I'm in a coffee shop right now and I seem to have no internet access at home, the sober/recovery house, and I'm not sure if this computer will allow me to download software onto my pen drive. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Tue Jun 4 02:00:05 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 3 Jun 2013 17:00:05 -0700 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On 3 June 2013 14:41, Oscar Benjamin wrote: > Maybe or maybe not. When you run 'python setup.py install' (this > happens implicitly when using pip), Python will try to run the > setup.py script. At this point the script can do anything that its > author likes. It could check for versions, it could just install and > be broken, it could delete random files or damage your system in a > malicious way. The author may have written the package at a time when > Python 3 didn't exist so they didn't see the need to check for Python > version and wrote code that wouldn't work in Python 3. Using Python 2.7 on Windows 7 That's scary. But are we talking modules from wherever or PyPI modules? I figured the modules on the official PyPI index would be checked to some degree, and be safe. I guess I'll always look into the setup.py to see if it contains any obvious gotchas. Oops - pip downloads and installs automatically - I never see setup.py. Might be best to download, inspect, then run the install. Good trick for running different Py versions from the command line without accidentally confusing them. You never know what you're going to learn here ;') I was qualifying the path to each version but that gets to be a pain. As for Wing, I just meant running as Guest is a windows trick for running two different versions of the same program for two different Pys without reconfiguring the IDE. Wing 101 has only one config since it's the free version and doesn't do projects. So you have to reconfig every time to run different Pys from the IDE unless you do that trick. No doubt there's something similar in Linux. Jim > > There is progress on improving this situation by formalising the > metadata that is supplied with Python packages so that it can be used > more effectively by tools such as pip. The current (unaccepted) PEP > for this is here (see the environment markers section): > http://www.python.org/dev/peps/pep-0426/ > >> Incidentally, for those nutty enough to run two Pys on Win, with Wing >> 101, I realized you can get Wing 101 to run either, without having to >> reconfigure it all the time, by setting up a Guest account in Windows, >> and configuring the second Wing for Py 3.3, run as Guest, with the >> primary as 2.7. This is helpful since some online sources I read are >> for one Py and some are for another. > > If you have py.exe (which you should if you've installed Python 3.3 on > Windows) then you can run any installed Python version as 'py -2.7 > myscript.py' or 'py -3.3 myscript.py' to choose the version of Python > that will run myscript.py. I find it easier and clearer to do that > explicitly on the command line when I want to test different versions. > > > Oscar > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Jim Ornhgvshy vf orggre guna htyl From drobinow at gmail.com Tue Jun 4 02:26:07 2013 From: drobinow at gmail.com (David Robinow) Date: Mon, 3 Jun 2013 20:26:07 -0400 Subject: [Tutor] I think I found what I'm looking for. In-Reply-To: References: Message-ID: On Mon, Jun 3, 2013 at 7:32 PM, Michael Sparks wrote: > speech.py is a Python module that provides a clean interface to Windows's > voice recognition and text-to-speech capabilities. But it requires Windows > XP or Vista, and Python 2.4 or 2.5. I use Windows 7. > ... > I think that I'm satisfied with speech.py but it might not work on Windows > 7. It works fine with Windows 7. It works fine with Python 2.7 I haven't tried Dragonfly. (It should be better) From bfishbein79 at gmail.com Tue Jun 4 03:08:59 2013 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Mon, 3 Jun 2013 20:08:59 -0500 Subject: [Tutor] selenium programs stopped working Message-ID: <5E71A086-12FF-447E-8D40-A13C9CEFC1C7@gmail.com> I'm using selenium webdriver with python 2.7. I have some programs I wrote with it and they've been working properly for some months. But today I tried to write a new program with the selenium module. from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.python.org") # actually I go to other sites, not python.org # now there's more but the program never gets to it The Firefox web browser opens, but it doesn't go to any page. The url doesn't even appear in the box at the top of the webbrowser where urls go. Do you know what is causing this problem? The only thing I can think of is that there's some problem in the settings. I shut down the computer and turned it back on, but the problem remains. Any help would be greatly appreciated. Thanks, Ben From bfishbein79 at gmail.com Tue Jun 4 03:27:26 2013 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Mon, 3 Jun 2013 20:27:26 -0500 Subject: [Tutor] selenium programs stopped working In-Reply-To: <5E71A086-12FF-447E-8D40-A13C9CEFC1C7@gmail.com> References: <5E71A086-12FF-447E-8D40-A13C9CEFC1C7@gmail.com> Message-ID: <3C5A470C-5245-4CB4-9069-251191F74F5E@gmail.com> btw I'm on a Mac running 10.7. And after a couple minutes of not loading any webpage, the program gives me this error: Traceback (most recent call last): File "/Users/bfishbein/Documents/s_buy2.py", line 7, in driver = webdriver.Firefox() File "/Library/Python/2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 58, in __init__ self.binary, timeout), File "/Library/Python/2.7/site-packages/selenium/webdriver/firefox/extension_connection.py", line 47, in __init__ self.binary.launch_browser(self.profile) File "/Library/Python/2.7/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 48, in launch_browser self._wait_until_connectable() File "/Library/Python/2.7/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 95, in _wait_until_connectable self.profile.path, self._get_firefox_output())) WebDriverException: Message: "Can't load the profile. Profile Dir: /var/folders/vm/8th3csp91qb47xbhqhb4gcmh0000gn/T/tmpPeqacA Firefox output: *** LOG addons.xpi: startup\n*** LOG addons.xpi: Skipping unavailable install location app-system-share\n*** LOG addons.xpi: checkForChanges\n*** LOG addons.xpi: No changes found\n" I can't make any sense of this. Ben On Jun 3, 2013, at 8:08 PM, Benjamin Fishbein wrote: > I'm using selenium webdriver with python 2.7. I have some programs I wrote with it and they've been working properly for some months. > But today I tried to write a new program with the selenium module. > > from selenium import webdriver > from selenium.webdriver.common.keys import Keys > > driver = webdriver.Firefox() > driver.get("http://www.python.org") # actually I go to other sites, not python.org > # now there's more but the program never gets to it > > The Firefox web browser opens, but it doesn't go to any page. The url doesn't even appear in the box at the top of the webbrowser where urls go. > Do you know what is causing this problem? The only thing I can think of is that there's some problem in the settings. I shut down the computer and turned it back on, but the problem remains. > Any help would be greatly appreciated. > Thanks, > Ben > From oscar.j.benjamin at gmail.com Tue Jun 4 03:28:00 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 4 Jun 2013 02:28:00 +0100 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On 4 June 2013 01:00, Jim Mooney wrote: >> Maybe or maybe not. When you run 'python setup.py install' (this >> happens implicitly when using pip), Python will try to run the >> setup.py script. At this point the script can do anything that its >> author likes. It could check for versions, it could just install and >> be broken, it could delete random files or damage your system in a >> malicious way. The author may have written the package at a time when >> Python 3 didn't exist so they didn't see the need to check for Python >> version and wrote code that wouldn't work in Python 3. > > Using Python 2.7 on Windows 7 I guess at some point that someone told you to "always state the Python version and OS" but really it's only necessary when it's relevant. Sometimes it might not be obvious if it's relevant or not and if so it's best to mention it. Mainly it will be relevant if you're talking about actual code or the availability of particular modules (for this post it isn't). > That's scary. But are we talking modules from wherever or PyPI > modules? You always should be cautious about downloading code and running it. Even more so if you're going to use admin/root privileges to run it. However I've never actually had a problem with this whether I get packages from PyPI or from sourceforge/github/bitbucket etc. In the case of pip, when you run 'pip install X' what you need to understand is that PyPI can only guarantee that the code there was uploaded by whoever initially registered the name X on PyPI. Anyone can register the name but once they have they will control that name in the PyPI namespace unless PyPI or their PyPI account gets hacked. There are a number of ongoing efforts to improve security around PyPI and one part of that is to abolish the "run setup.py to install" concept. > I figured the modules on the official PyPI index would be > checked to some degree, and be safe. No they are not. You can test this yourself: anyone can register a name and upload any code they want. There are two protections that PyPI currently offers. The first is that once a name is registered no one else can upload code under that name. The second is that if someone does upload malware and it is reported to the PyPI admins then they can remove it but only retrospectively. There is no proactive checking of the code that goes onto PyPI. > I guess I'll always look into the > setup.py to see if it contains any obvious gotchas. Oops - pip > downloads and installs automatically - I never see setup.py. Might be > best to download, inspect, then run the install. I personally rarely do this and would only actually bother if installing a very obscure package. I think that widely used packages can be trusted (in this sense) not to do harm. Oscar From oscar.j.benjamin at gmail.com Tue Jun 4 03:44:13 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 4 Jun 2013 02:44:13 +0100 Subject: [Tutor] selenium programs stopped working In-Reply-To: <3C5A470C-5245-4CB4-9069-251191F74F5E@gmail.com> References: <5E71A086-12FF-447E-8D40-A13C9CEFC1C7@gmail.com> <3C5A470C-5245-4CB4-9069-251191F74F5E@gmail.com> Message-ID: Please don't top-post on this list (and many others). Inline or bottom-posted responses are usually preferred like the way that I've rearranged your message below. On 4 June 2013 02:27, Benjamin Fishbein wrote: > On Jun 3, 2013, at 8:08 PM, Benjamin Fishbein wrote: > >> I'm using selenium webdriver with python 2.7. I have some programs I wrote with it and they've been working properly for some months. >> But today I tried to write a new program with the selenium module. >> >> from selenium import webdriver >> from selenium.webdriver.common.keys import Keys >> >> driver = webdriver.Firefox() >> driver.get("http://www.python.org") # actually I go to other sites, not python.org >> # now there's more but the program never gets to it >> >> The Firefox web browser opens, but it doesn't go to any page. The url doesn't even appear in the box at the top of the webbrowser where urls go. >> Do you know what is causing this problem? The only thing I can think of is that there's some problem in the settings. I shut down the computer and turned it back on, but the problem remains. >> Any help would be greatly appreciated. > > btw I'm on a Mac running 10.7. > And after a couple minutes of not loading any webpage, the program gives me this error: > > Traceback (most recent call last): > File "/Users/bfishbein/Documents/s_buy2.py", line 7, in > driver = webdriver.Firefox() > File "/Library/Python/2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 58, in __init__ > self.binary, timeout), > File "/Library/Python/2.7/site-packages/selenium/webdriver/firefox/extension_connection.py", line 47, in __init__ > self.binary.launch_browser(self.profile) > File "/Library/Python/2.7/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 48, in launch_browser > self._wait_until_connectable() > File "/Library/Python/2.7/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 95, in _wait_until_connectable > self.profile.path, self._get_firefox_output())) > WebDriverException: Message: "Can't load the profile. Profile Dir: /var/folders/vm/8th3csp91qb47xbhqhb4gcmh0000gn/T/tmpPeqacA Firefox output: *** LOG addons.xpi: startup\n*** LOG addons.xpi: Skipping unavailable install location app-system-share\n*** LOG addons.xpi: checkForChanges\n*** LOG addons.xpi: No changes found\n" > > I can't make any sense of this. Unfortunately neither can I as I've never used selenium. Someone may respond with a good answer to this but I also wouldn't be surprised if no one here understood your problem. This list is mainly for people learning the basics of Python and I think that this seems like quite a specialist problem that might be better directed at a mailing-list/forum that is primarily for selenium/firefox (I'm not sure as I don't really understand what you're doing). Sorry, Oscar From eryksun at gmail.com Tue Jun 4 03:49:49 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 3 Jun 2013 21:49:49 -0400 Subject: [Tutor] when is a generator "smart?" In-Reply-To: References: <51AB20C9.5070300@davea.name> Message-ID: On Mon, Jun 3, 2013 at 3:41 AM, Jim Mooney wrote: > Ah, useful. A lot more than is on windows path and PYTHONPATH > obviously gets snuck in there. Sure enough, I queried sys.path and > there's a Lot more in there. The path for the script comes first, followed by the contents of the PYTHONPATH environment variable, if present. Next it adds the optional zip library, additional paths from subkeys of PythonPath in HKCU/HKLM, the core path string (expanded for sys.prefix / PYTHONHOME) that I already mentioned, and also the path of the executable (e.g. python.exe). Next, site.py is imported (if you didn't use the -S option), which adds lib\site-packages and paths from .pth files if they exist. If you've installed a package with --user, it will also add "%AppData%\Python\Python27\site-packages". Finally, it tries to import sitecustomize.py and usercustomize.py. > If I dump a package (not sure how to do that beyond just deleting it, > but I've tried some bad ones, so I'd like to) how do I remove it from > sys.path, or do I need to? An exe/msi installer should clean up after itself when you uninstall. With pip, you can "pip uninstall". With easy_install, use "-mxN PackageName" (that should remove scripts and clear the package from setuptools.pth), and then manually delete the directory. As to any .pth files left behind, the directories listed in them won't be added to sys.path if they no longer exist. So leaving them around only costs a few milliseconds of startup time. If for some reason a package stored paths in a subkey of PythonPath, you'll have to remove the subkey to keep it from being added to sys.path -- but I haven't actually seen a package use this option. .pth files are simpler and cross-platform. From wprins at gmail.com Tue Jun 4 10:27:31 2013 From: wprins at gmail.com (Walter Prins) Date: Tue, 4 Jun 2013 09:27:31 +0100 Subject: [Tutor] selenium programs stopped working In-Reply-To: <3C5A470C-5245-4CB4-9069-251191F74F5E@gmail.com> References: <5E71A086-12FF-447E-8D40-A13C9CEFC1C7@gmail.com> <3C5A470C-5245-4CB4-9069-251191F74F5E@gmail.com> Message-ID: Hi, On 4 June 2013 02:27, Benjamin Fishbein wrote: > WebDriverException: Message: "Can't load the profile. Profile Dir: > /var/folders/vm/8th3csp91qb47xbhqhb4gcmh0000gn/T/tmpPeqacA Firefox output: > *** LOG addons.xpi: startup\n*** LOG addons.xpi: Skipping unavailable > install location app-system-share\n*** LOG addons.xpi: checkForChanges\n*** > LOG addons.xpi: No changes found\n" That there is your problem. There's several instances of this problem on the net if you google e.g. "Can't load the profile. Profile Dir: /var/folders" as a search string. The gist of it seems to me to be usually a firefox/selenium version mismatch of some sort. Has firefox been updated recently? Have you checked if there's any updates available for selenium? See for example: https://groups.google.com/forum/?fromgroups#!topic/splinter-users/MAP8yyVhqic Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Tue Jun 4 18:28:36 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 4 Jun 2013 16:28:36 +0000 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51ACA1AA.6020500@nycap.rr.com> References: <51ACA1AA.6020500@nycap.rr.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> Matt D wrote: > Hello, > > I am using an open source wxPython GUI that I like very very much. I > have ideas about some modifications I need but I cannot be bothering the > author too much so I must learn some very specific things about Python > in order to make the modification myself. First, I need some help > understanding the code behind this GUI. From reading the comments I > understand that the part of the program written in C++ sends a Python > pickled dictionary to a msg_queue and when Python decodes the pickle the > TextCtrl fields (in the wxPython GUI I am using) receive/display the > appropriate values. And as new messages are received by Python the GUI > fields are cleared to display the new values. > > For starters I would like the values to be displayed on the GUI in some > sort of a scrolling panel as they are cleared from the TextCtrl fields > so the user can watch recent activity. I dont know what the best way to > do this would be; the wxpython.scrolledPanel widget? I am unclear if > this can be put on the same GUI pane as the TextCtrl fields are and I am > unclear about if I can take the values from the TextCtrl fields or have > to use the pickle or what? I dont see any variables declared (like in > Visual Basic) so its not like I can just make a list and a textbox and > print it. Scrolled panel is just a graphical container that allows for scrolling inside, but it is the window that scrolls not widgets inside it. This of it like a webpage that scrolls. If you use web email the text widget in the email needs to scroll so you can see your full email context and not just scroll the page. You will probably need to create a TextCtrl with the appropriate style and append your new data. I have given an example below that should automatically scroll with your new data. #in __init__ self.scrolling_widget = wx.TextCtrl( self, wx.ID_ANY, '', size=(-1, 275), style=wx.TE_AUTO_SCROLL|wx.TE_READONLY|wx.TE_PROCESS_ENTER|wx.TE_WORDWRAP|wx.TE_MULTILINE ) You will probably have to edit TrafficPane.update so that it performs the action you want. BTW, the widgets are all stored in self.fields. You will need to look at the init to see how they stored to get the correct field if you want to change existing field behavior. self.fields["dest"] # Destination TextCtrl That being said, for your desired effect I think all you need to do is change: v.SetValue(f) to: old_text = v.GetValue() # You may need to modify or add some context as otherwise it will # just dump the data and may not make sense when looking at it # scroll. self.scrolling_widget.AppendText(old_text) v.SetValue(f) > > More importantly I need to save the values from the TextCtrl fields, > preferable in a CSV file, for later inspection. From looking at the > Logging HOWTO and the Logging Cookbook I see there are alot of loggers > available, or ways to log, but they all look like they are orientated > towards exception handling and debugging so I am unsure what is the best > way to go about this; maybe wxLogTextCtrl ? Utimately I need to log the > values from the TextCtrl fields in a row of comma separated values > adding a time/date stamp as one of the values. I need this log so the > data can easily be worked on in excel or SAS. I need the time/date > stamp for time series analysis. Create a list of lists with your data (think table). Then use the csv module to write that data to file. If you need to append, You should read all the existing data. Close the file, append your new data and then write to a new complete file. Once the write has succeeded, rename/overwrite the existing file. That will help prevent you from losing existing data if a problem occurs on write. # Sort the dictionary keys so you get the same order for each row row = [ field_values[k] for sorted(field_values) ] # Now read csv, append row, write new csv, and then overwrite old file > > I attached the code behind the wxPythoin GUI I am using. > Any help will be much appreciated. > > Thanks in advance > -- > Matt D > ------------ Well that should get you started. Post back if you need specific help with something else. ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From bfishbein79 at gmail.com Tue Jun 4 19:49:08 2013 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Tue, 4 Jun 2013 12:49:08 -0500 Subject: [Tutor] selenium programs stopped working In-Reply-To: References: <5E71A086-12FF-447E-8D40-A13C9CEFC1C7@gmail.com> <3C5A470C-5245-4CB4-9069-251191F74F5E@gmail.com> Message-ID: <69858D14-3916-4CC4-B5E2-DD568664BABA@gmail.com> I think you're right: Firefox may have automatically updated itself. I checked and I was using Selenium 2.29 The most recent is 2.33 So I downloaded the newest one and did pip install -U selenium in terminal but I got this: Installing collected packages: selenium Found existing installation: selenium 2.29.0 Uninstalling selenium: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-1.2.1-py2.7.egg/pip/basecommand.py", line 107, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-1.2.1-py2.7.egg/pip/commands/install.py", line 261, in run requirement_set.install(install_options, global_options) File "/Library/Python/2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py", line 1162, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py", line 495, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py", line 1492, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip-1.2.1-py2.7.egg/pip/util.py", line 273, in renames shutil.move(old, new) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 290, in move File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 249, in rmtree File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 247, in rmtree OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/selenium-2.29.0-py2.7.egg-info/dependency_links.txt' Is it saying that 2.29 isn't letting itself be upgraded? Will I have to completely delete Selenium from my computer and then reinstall it with the updated one? Ben On Jun 4, 2013, at 3:27 AM, Walter Prins wrote: > Hi, > > On 4 June 2013 02:27, Benjamin Fishbein wrote: > WebDriverException: Message: "Can't load the profile. Profile Dir: /var/folders/vm/8th3csp91qb47xbhqhb4gcmh0000gn/T/tmpPeqacA Firefox output: *** LOG addons.xpi: startup\n*** LOG addons.xpi: Skipping unavailable install location app-system-share\n*** LOG addons.xpi: checkForChanges\n*** LOG addons.xpi: No changes found\n" > > That there is your problem. There's several instances of this problem on the net if you google e.g. "Can't load the profile. Profile Dir: /var/folders" as a search string. > > The gist of it seems to me to be usually a firefox/selenium version mismatch of some sort. Has firefox been updated recently? Have you checked if there's any updates available for selenium? > > See for example: > https://groups.google.com/forum/?fromgroups#!topic/splinter-users/MAP8yyVhqic > > > Walter > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dipo.elegbede at dipoelegbede.com Tue Jun 4 20:05:25 2013 From: dipo.elegbede at dipoelegbede.com (Oladipupo Elegbede) Date: Tue, 4 Jun 2013 19:05:25 +0100 Subject: [Tutor] Python Conference/Tutorial in the USA Message-ID: Hello, Kindly let me have details if there are any python conferences/tutorials within the USA. I just came into the USA. Thank you all. Regards. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dfjennings at gmail.com Tue Jun 4 20:09:52 2013 From: dfjennings at gmail.com (Don Jennings) Date: Tue, 4 Jun 2013 14:09:52 -0400 Subject: [Tutor] selenium programs stopped working In-Reply-To: <69858D14-3916-4CC4-B5E2-DD568664BABA@gmail.com> References: <5E71A086-12FF-447E-8D40-A13C9CEFC1C7@gmail.com> <3C5A470C-5245-4CB4-9069-251191F74F5E@gmail.com> <69858D14-3916-4CC4-B5E2-DD568664BABA@gmail.com> Message-ID: On Jun 4, 2013, at 1:49 PM, Benjamin Fishbein wrote: > File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 247, in rmtree > OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/selenium-2.29.0-py2.7.egg-info/dependency_links.txt' > > Is it saying that 2.29 isn't letting itself be upgraded? More likely, the os isn't allowing the program to take whatever action it's trying to complete (I suspect the action is to delete the files since it's in rmtree). Perhaps you should issue the pip command as the superuser: sudo pip install -U selenium Take care, Don From bfishbein79 at gmail.com Tue Jun 4 20:20:27 2013 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Tue, 4 Jun 2013 13:20:27 -0500 Subject: [Tutor] selenium programs stopped working In-Reply-To: References: <5E71A086-12FF-447E-8D40-A13C9CEFC1C7@gmail.com> <3C5A470C-5245-4CB4-9069-251191F74F5E@gmail.com> <69858D14-3916-4CC4-B5E2-DD568664BABA@gmail.com> Message-ID: <7099EF59-4F07-4E83-AB41-C52118F1C4FE@gmail.com> Don, Thank you! It works!!! :) Ben On Jun 4, 2013, at 1:09 PM, Don Jennings wrote: > > On Jun 4, 2013, at 1:49 PM, Benjamin Fishbein wrote: > >> File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 247, in rmtree >> OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/selenium-2.29.0-py2.7.egg-info/dependency_links.txt' >> >> Is it saying that 2.29 isn't letting itself be upgraded? > > More likely, the os isn't allowing the program to take whatever action it's trying to complete (I suspect the action is to delete the files since it's in rmtree). Perhaps you should issue the pip command as the superuser: > > sudo pip install -U selenium > > Take care, > Don > From dfjennings at gmail.com Tue Jun 4 20:16:12 2013 From: dfjennings at gmail.com (Don Jennings) Date: Tue, 4 Jun 2013 14:16:12 -0400 Subject: [Tutor] Python Conference/Tutorial in the USA In-Reply-To: References: Message-ID: <8904A994-EC18-4C28-B194-40ADA62CBBE7@gmail.com> On Jun 4, 2013, at 2:05 PM, Oladipupo Elegbede wrote: > Hello, > > Kindly let me have details if there are any python conferences/tutorials within the USA. The Triangle Python User group [1] has several affordable options for attending in person at various places around the country, but if you are happy to watch videos of past conferences, try http://pyvideo.org/ > > I just came into the USA. Welcome! Take care, Don [1] http://trizpug.org/boot-camp From francois.dion at gmail.com Tue Jun 4 20:51:02 2013 From: francois.dion at gmail.com (Francois Dion) Date: Tue, 4 Jun 2013 14:51:02 -0400 Subject: [Tutor] Python Conference/Tutorial in the USA In-Reply-To: References: Message-ID: Where are you situated? You should join a local Python user group. Don mentionned tripython, which is in North Carolina. There is also PYPTUG [1] and PyCarolinas [2] 2013 should be announced soon. A little to the northwest, PyOhio [3] just concluded RFPs and is scheduled for the end of July. There are similar user groups and conferences around the US. Some hackerspaces also have Python project nights and workshops. If you tell us what city you are in, we can point you in the right direction. Francois [1] http://www.pyptug.org [2] http://www.pycarolinas.org/ [3] http://pyohio.org -- www.pyptug.org - raspberry-python.blogspot.com - @f_dion On Tue, Jun 4, 2013 at 2:05 PM, Oladipupo Elegbede < dipo.elegbede at dipoelegbede.com> wrote: > Hello, > > Kindly let me have details if there are any python conferences/tutorials > within the USA. > I just came into the USA. > > Thank you all. > > Regards. > > _______________________________________________ > 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 dipo.elegbede at dipoelegbede.com Tue Jun 4 20:55:19 2013 From: dipo.elegbede at dipoelegbede.com (Oladipupo Elegbede) Date: Tue, 4 Jun 2013 19:55:19 +0100 Subject: [Tutor] Python Conference/Tutorial in the USA In-Reply-To: References: Message-ID: I am currently in Ellenwood, Atlanta. I would be in Maryland as from Friday morning. I don't have an address yet. Thanks. On 4 Jun 2013 14:51, "Francois Dion" wrote: > Where are you situated? You should join a local Python user group. Don > mentionned tripython, which is in North Carolina. There is also PYPTUG [1] > and PyCarolinas [2] 2013 should be announced soon. A little to the > northwest, PyOhio [3] just concluded RFPs and is scheduled for the end of > July. There are similar user groups and conferences around the US. Some > hackerspaces also have Python project nights and workshops. If you tell us > what city you are in, we can point you in the right direction. > > Francois > > [1] http://www.pyptug.org > [2] http://www.pycarolinas.org/ > [3] http://pyohio.org > > -- > www.pyptug.org - raspberry-python.blogspot.com - @f_dion > > > On Tue, Jun 4, 2013 at 2:05 PM, Oladipupo Elegbede < > dipo.elegbede at dipoelegbede.com> wrote: > >> Hello, >> >> Kindly let me have details if there are any python conferences/tutorials >> within the USA. >> I just came into the USA. >> >> Thank you all. >> >> Regards. >> >> _______________________________________________ >> 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 cfuller084 at thinkingplanet.net Tue Jun 4 21:12:32 2013 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Tue, 4 Jun 2013 14:12:32 -0500 Subject: [Tutor] Python Conference/Tutorial in the USA In-Reply-To: References: Message-ID: <201306041412.32648.cfuller084@thinkingplanet.net> http://www.python.org/community/workshops/ On Tuesday, June 04, 2013, Oladipupo Elegbede wrote: > Hello, > > Kindly let me have details if there are any python conferences/tutorials > within the USA. > I just came into the USA. > > Thank you all. > > Regards. From joel.goldstick at gmail.com Tue Jun 4 21:29:20 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 4 Jun 2013 15:29:20 -0400 Subject: [Tutor] Python Conference/Tutorial in the USA In-Reply-To: <201306041412.32648.cfuller084@thinkingplanet.net> References: <201306041412.32648.cfuller084@thinkingplanet.net> Message-ID: On Tue, Jun 4, 2013 at 3:12 PM, Chris Fuller wrote: > > http://www.python.org/community/workshops/ > > On Tuesday, June 04, 2013, Oladipupo Elegbede wrote: > > Hello, > > > > Kindly let me have details if there are any python conferences/tutorials > > within the USA. > > I just came into the USA. > > > > Thank you all. > > > > Regards. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > checkout meetup.com There may be a python group in your area that meets monthly or so -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Tue Jun 4 22:56:20 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 4 Jun 2013 13:56:20 -0700 Subject: [Tutor] Python Conference/Tutorial in the USA In-Reply-To: <8904A994-EC18-4C28-B194-40ADA62CBBE7@gmail.com> References: <8904A994-EC18-4C28-B194-40ADA62CBBE7@gmail.com> Message-ID: On 4 June 2013 11:16, Don Jennings wrote: > but if you are happy to watch videos of past conferences, try http://pyvideo.org/ Thanks. A very useful link. My eyes fog just reading a book and I need a break. I even found a few videos I could understand, that clarified some items, like packaging. Now I'll go look for importing. I think those two are harder for a newbie to decipher than the language itself. And I even got to see Guido ;') -- Jim The insurance industry is America's largest organized criminal enterprise. From alan.gauld at btinternet.com Tue Jun 4 23:54:46 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 04 Jun 2013 22:54:46 +0100 Subject: [Tutor] Python Conference/Tutorial in the USA In-Reply-To: References: <8904A994-EC18-4C28-B194-40ADA62CBBE7@gmail.com> Message-ID: On 04/06/13 21:56, Jim Mooney wrote: > Thanks. A very useful link. My eyes fog just reading a book Jim, If you like videos check out the showMeDo site they have a lot of python video tuts and some of them are free. Enjoy, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From msg.ufo at gmail.com Wed Jun 5 07:23:01 2013 From: msg.ufo at gmail.com (Mike G) Date: Tue, 4 Jun 2013 22:23:01 -0700 Subject: [Tutor] Python Conference/Tutorial in the USA Message-ID: ...> Jim, ...> If you like videos check out the showMeDo site ...> they have a lot of python video tuts and some of ...> them are free. ...> Enjoy, ...> -- ...> Alan G ...> Author of the Learn to Program web site ...> http://www.alan-g.me.uk/ I liked ShowMeDo early on but it seems to be 'Club' driven mostly, and without a membership you get one or two videos in a series only - the founders do this a lot. I think in business they call it teasing, it's not nice to tease :) From cybervigilante at gmail.com Wed Jun 5 07:53:18 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 4 Jun 2013 22:53:18 -0700 Subject: [Tutor] list comprehensions isolate variables but for loops don't - is there a special usage? Message-ID: I just noticed that a list comprehension doesn't change a same-name variable outside of it, but a for loop does. That is: #Using Python 3.3.2 on Win 7 lst = [1,3,55,44,79,1,6,7,44,231,764,44,3,44] frog = 'jumping' print(frog, end=' ') newlst = [frog**2 for frog in lst] print(newlst, end=' ') print(frog) # printed result is "jumping (the above list squared) jumping" newlst = [] print(frog, end=' ') for frog in lst: newlst.append(frog**2) print(newlst,end=' ') print(frog) # printed result is "jumping (the above list squared) 44" For some reason it bothers me that a for loop can do this. Is there a simple usage that isolates the for loop iteration variable the way a list comprehension does? That is, without a lot of foofooraw. I can isolate it by using a function but that's overkill for something simple. If my new autoheader wasn't noticed, I'm now on Py 3.3 for good. I figure I learned what I should about the basic differences between 2.7 and 3.3, so it was time to move on. By the time I get done with the two Lutz books and have a real use for the major libraries, most will probably be ported. The Python 3 wall of superpowers already has enough green to keep me busy for a long time ( http://python3wos.appspot.com ;') -- Jim The insurance industry is America's largest organized criminal enterprise. From cybervigilante at gmail.com Wed Jun 5 08:06:19 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 4 Jun 2013 23:06:19 -0700 Subject: [Tutor] Python Conference/Tutorial in the USA In-Reply-To: References: Message-ID: On 4 June 2013 22:23, Mike G wrote: > ...> Author of the Learn to Program web site > ...> http://www.alan-g.me.uk/ Your site looks good for a quick runthru tomorrow, to solidify the basics I'm learning in my bad memory. But Under Construction pages are soooo Web 1.0 ;') -- Jim The insurance industry is America's largest organized criminal enterprise. From msg.ufo at gmail.com Wed Jun 5 09:09:33 2013 From: msg.ufo at gmail.com (Mike G) Date: Wed, 5 Jun 2013 00:09:33 -0700 Subject: [Tutor] Python Conference/Tutorial in the USA In-Reply-To: References: Message-ID: On 6/4/13, Jim Mooney wrote: ...> On 4 June 2013 22:23, Mike G wrote: ...> ...>> ...> Author of the Learn to Program web site ...>> ...> http://www.alan-g.me.uk/ ...> ...> Your site looks good for a quick runthru tomorrow, to solidify the ...> basics I'm learning in my bad memory. But Under Construction pages are ...> soooo Web 1.0 ;') ...> ...> -- ...> Jim ...> The insurance industry is America's largest organized criminal enterprise. ...> Hi Jim Just wanted to clarify, seeing this post came to me directly as well the tutor archives. I was commenting to Alan G regarding his comment to you about ShowMeDo, the tutorial you mention is Alan's page, which I recommend you read BTW, regardless if it appears web 1.0. Also, if I accidently sent an email to anyone directly, I'm sorry, I know I've done this in the past. I can't always remember how to respond to a post direcly (and only) to the archive, along with it located time-wise in the proper order with the proper title. I thought you use when 'replying'... To: tutor at python.org Subject: Re: [Tutor] Python Conference/Tutorial in the USA """ my quote (if any) and comments here. """ Somehow I still send people an additional email directly, not sure if this happened here...? From alan.gauld at btinternet.com Wed Jun 5 09:35:44 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 05 Jun 2013 08:35:44 +0100 Subject: [Tutor] list comprehensions isolate variables but for loops don't - is there a special usage? In-Reply-To: References: Message-ID: On 05/06/13 06:53, Jim Mooney wrote: > I just noticed that a list comprehension doesn't change a same-name > variable outside of it, but a for loop does. > > For some reason it bothers me that a for loop can do this. Is there a > simple usage that isolates the for loop iteration variable the way a > list comprehension does? No, and it's unlikely to change since a lot of code relies on the fact that the for loop iteration variable remembers the last value in the loop. This is especially so in loops that have a break exit since its useful to know how far through the sequence it got to. To be honest I didn't realize that comprehensions (and I assume generators in general) created their own local namespace. But thinking about it, it seems logical since they are effectively functions in disguise... Whereas for loops are structures of the language just like if statements or while loops. They live in whichever context they are used. hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mail at timgolden.me.uk Wed Jun 5 09:44:53 2013 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 05 Jun 2013 08:44:53 +0100 Subject: [Tutor] list comprehensions isolate variables but for loops don't - is there a special usage? In-Reply-To: References: Message-ID: <51AEEC75.1080704@timgolden.me.uk> On 05/06/2013 08:35, Alan Gauld wrote: > To be honest I didn't realize that comprehensions (and I assume > generators in general) created their own local namespace. In 2.x list comps "leak" their iteration variables while gen comps don't. In 3.x neither does. It's never bothered me very much either way, but the change in 3.x does at least mean that the list comp [i for i in ...] is now, as you might have expected, equivalent to list(i for i in ...) TJG From wolfgang.maier at biologie.uni-freiburg.de Wed Jun 5 09:47:34 2013 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Wed, 5 Jun 2013 07:47:34 +0000 (UTC) Subject: [Tutor] list comprehensions isolate variables but for loops don't - is there a special usage? References: Message-ID: Alan Gauld btinternet.com> writes: > > To be honest I didn't realize that comprehensions (and I assume > generators in general) created their own local namespace. This is true only for Python 3. In Python 2.x comprehensions and for loops behave the same way. See this post on python-ideas: http://article.gmane.org/gmane.comp.python.ideas/19151 Best, Wolfgang From eryksun at gmail.com Wed Jun 5 09:59:14 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 5 Jun 2013 03:59:14 -0400 Subject: [Tutor] list comprehensions isolate variables but for loops don't - is there a special usage? In-Reply-To: References: Message-ID: On Wed, Jun 5, 2013 at 3:35 AM, Alan Gauld wrote: > > To be honest I didn't realize that comprehensions (and I assume generators > in general) created their own local namespace. But thinking about it, it > seems logical since they are effectively functions in disguise... Whereas > for loops are structures of the language just like if statements or while > loops. They live in whichever context they are used. 3.x compiles comprehensions as functions. 2.x compiles list comprehensions *inline*. But, just to confuse us, 2.7 adds the new set/dict comprehensions compiled as functions (doing it 'right' didn't break backward compatibility). 2.7.3: >>> [x for x in [1]] [1] >>> x 1 >>> {y for y in [1]} set([1]) >>> y Traceback (most recent call last): File "", line 1, in NameError: name 'y' is not defined From __peter__ at web.de Wed Jun 5 10:05:49 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Jun 2013 10:05:49 +0200 Subject: [Tutor] list comprehensions isolate variables but for loops don't - is there a special usage? References: Message-ID: Alan Gauld wrote: > On 05/06/13 06:53, Jim Mooney wrote: >> I just noticed that a list comprehension doesn't change a same-name >> variable outside of it, but a for loop does. >> >> For some reason it bothers me that a for loop can do this. Is there a >> simple usage that isolates the for loop iteration variable the way a >> list comprehension does? > > No, and it's unlikely to change since a lot of code relies on the fact > that the for loop iteration variable remembers the last value in the > loop. This is especially so in loops that have a break exit since its > useful to know how far through the sequence it got to. > > To be honest I didn't realize that comprehensions (and I assume > generators in general) created their own local namespace. But thinking > about it, it seems logical since they are effectively functions in > disguise... Whereas for loops are structures of the language just like > if statements or while loops. They live in whichever context they are > used. Caveat: The behaviour was unified in Python 3. List comprehensions in 2.x did leak the loop variable... >>> def f(): ... [x for x in "abc"] ... print x ... >>> f() c while generator expressions did not leak: >>> def g(): ... list(x for x in "abc") ... print x ... >>> g() Traceback (most recent call last): File "", line 1, in File "", line 3, in g NameError: global name 'x' is not defined Until 2.6 you could even access the underlying iterator under a name like "_[1]", but that has been cleaned up in 2.7 it seems. From oscar.j.benjamin at gmail.com Wed Jun 5 11:29:55 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 5 Jun 2013 10:29:55 +0100 Subject: [Tutor] list comprehensions isolate variables but for loops don't - is there a special usage? In-Reply-To: References: Message-ID: On 5 June 2013 06:53, Jim Mooney wrote: > I just noticed that a list comprehension doesn't change a same-name > variable outside of it, but a for loop does. That is: > > #Using Python 3.3.2 on Win 7 In this case the version is relevant since this behaviour changed in Python 3.x as others have pointed out. I just want to add that the reason for the change is that it's easier to accidentally bind a name when using list comprehensions than with a for loop. With a for loop the name being bound appears prominently at the start of the line e.g.: for x in func1(arg1, arg2, param1=val1, param2=val2): print(func3(stuff, x)) However in a list comprehension you might do something like: x = 2*y z = long_function_name('qwe', param1=func2('foo'), param2=[x for x in func3('bar')], param3='foobar') print(x, z) In this case it's less obvious that you're binding to the name 'x' (in Python 2.x). I've definitely made this mistake before. I don't think it ever went unnoticed in my own code but it could easily lead to a subtle and hard to spot bug. Generally in Python binding names is done very explicitly and it is easy to see from the code when names are bound which is a good thing. There are hacky exceptions to this using e.g. globals() or sys._getframe() and the like but if you stick to normal Python code names do not get bound unexpectedly. If you want to access the loop variable from a list comprehension you could use: values = [x for x in stuff] print(values[-1]) This is not necessarily the same if the list comp has an if clause but otherwise it gives you the same value (and raises an error in the same situations). Oscar From cybervigilante at gmail.com Wed Jun 5 12:38:57 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 5 Jun 2013 03:38:57 -0700 Subject: [Tutor] Python Conference/Tutorial in the USA - email Message-ID: On 5 June 2013 00:09, Mike G wrote: > Somehow I still send people an additional email directly, not sure if > this happened here...? I set gmail to reply-to-all as the default, but that does introduce some redundancy so maybe I'll reset it, if I remember. It's 3:30 am and I have the sitting-at-the-computer-can't-sleep-syndrome ;') Of course, reply-to-all is because I belong to another group whose members sometimes send me a personal note when they meant a group note, so if I just reply no one else sees it. No matter which way I set email I end up having to do a manual fixup ;') I also thought reply-to-all was for the mail program, but I think the problem was it uses the subject line, which gets confused if you change it. Or that's my theory anyway. I'm so used to web-based boards that I've forgotten about mailing lists. Not to mention that every time I send a photo I have to remember to go back to plain text since gmail "obligingly" remembers my last format instead of allowing a default. It's kind of funny I'm learning to automate everything with python but the lousy email still needs manual fixups. I think I'll just Append to the subject and see if my reply stays in the same stream. Jim From cybervigilante at gmail.com Wed Jun 5 13:14:34 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 5 Jun 2013 04:14:34 -0700 Subject: [Tutor] Future Python Message-ID: Here's something interesting. I went to the Tutor archives to see if appending to a title would keep a msg in the stream (it didn't), and found email from 2027. I'll ask Djuro for lottery numbers but I'll have to wait ten years to collect. http://mail.python.org/pipermail/tutor/2027-January/date.html#start 2027-January Archives by Date Messages sorted by: [ thread ] [ subject ] [ author ] More info on this list... Starting: Sat Jan 30 02:20:15 2027 Ending: Sat Jan 30 02:20:15 2027 Messages: 1 [Tutor] Glade djuro m. Last message date: Sat Jan 30 02:20:15 2027 Archived on: Wed Feb 6 09:57:01 2002 =========================== Even more oddly, it was archived in 2002, but with the same format as 2027, or I'd figure I was misunderstanding something (Which is still possible.) Although putting some odd sequence number that looks like a year at the end of a date would be really obtuse. That, or someone else has as much trouble with dates as I do. Or maybe its a time-dilation effect and I can get a sneak peek at Python 7 ;') -- Jim The insurance industry is America's largest organized criminal enterprise - after banking. From steve at pearwood.info Wed Jun 5 13:45:15 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 05 Jun 2013 21:45:15 +1000 Subject: [Tutor] Future Python In-Reply-To: References: Message-ID: <51AF24CB.2010501@pearwood.info> On 05/06/13 21:14, Jim Mooney wrote: > Here's something interesting. I went to the Tutor archives to see if > appending to a title would keep a msg in the stream (it didn't), and > found email from 2027. I'll ask Djuro for lottery numbers but I'll > have to wait ten years to collect. :-) Of course, this has an easy explanation: the poster had the clock on his computer set to the wrong date, so his email also showed the wrong date. -- Steven From breamoreboy at yahoo.co.uk Wed Jun 5 15:35:25 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 05 Jun 2013 14:35:25 +0100 Subject: [Tutor] Future Python In-Reply-To: <51AF24CB.2010501@pearwood.info> References: <51AF24CB.2010501@pearwood.info> Message-ID: On 05/06/2013 12:45, Steven D'Aprano wrote: > On 05/06/13 21:14, Jim Mooney wrote: >> Here's something interesting. I went to the Tutor archives to see if >> appending to a title would keep a msg in the stream (it didn't), and >> found email from 2027. I'll ask Djuro for lottery numbers but I'll >> have to wait ten years to collect. > > :-) > > Of course, this has an easy explanation: the poster had the clock on his > computer set to the wrong date, so his email also showed the wrong date. > Or he borrowed Guido's time machine? :) -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From bjorn.h.madsen at googlemail.com Wed Jun 5 16:45:05 2013 From: bjorn.h.madsen at googlemail.com (Bjorn Madsen) Date: Wed, 5 Jun 2013 15:45:05 +0100 Subject: [Tutor] Python Package Diagram Message-ID: Hello Tutor, On http://docs.oracle.com/javase/7/docs/ a pretty chart gives a more or less misdirecting view of the Java library (I guess the gaps between the boxes are the security holes). *Does something similar exist for Python?* Google images turned out with a stack of, well, not so pretty charts... Kind regards, Bjorn -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Wed Jun 5 17:13:47 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 5 Jun 2013 15:13:47 +0000 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51AF4716.4050208@nycap.rr.com> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> Please always CC the list. It's to your benefit as other people might be able to answer faster or better. Thanks for bottom posting and plain text emails. Matt D wrote: > On 06/04/2013 12:28 PM, Prasad, Ramit wrote: > > Matt D wrote: > >> Hello, > >> > >> I am using an open source wxPython GUI that I like very very much. I > >> have ideas about some modifications I need but I cannot be bothering the > >> author too much so I must learn some very specific things about Python > >> in order to make the modification myself. First, I need some help > >> understanding the code behind this GUI. From reading the comments I > >> understand that the part of the program written in C++ sends a Python > >> pickled dictionary to a msg_queue and when Python decodes the pickle the > >> TextCtrl fields (in the wxPython GUI I am using) receive/display the > >> appropriate values. And as new messages are received by Python the GUI > >> fields are cleared to display the new values. > >> > >> For starters I would like the values to be displayed on the GUI in some > >> sort of a scrolling panel as they are cleared from the TextCtrl fields > >> so the user can watch recent activity. I dont know what the best way to > >> do this would be; the wxpython.scrolledPanel widget? I am unclear if > >> this can be put on the same GUI pane as the TextCtrl fields are and I am > >> unclear about if I can take the values from the TextCtrl fields or have > >> to use the pickle or what? I dont see any variables declared (like in > >> Visual Basic) so its not like I can just make a list and a textbox and > >> print it. > > > > Scrolled panel is just a graphical container that allows for scrolling inside, > > but it is the window that scrolls not widgets inside it. This of it like > > a webpage that scrolls. If you use web email the text widget in the > > email needs to scroll so you can see your full email context and not > > just scroll the page. > > > > You will probably need to create a TextCtrl with the appropriate style > > and append your new data. I have given an example below that should > > automatically scroll with your new data. > > > > #in __init__ > > self.scrolling_widget = wx.TextCtrl( self, wx.ID_ANY, '', size=(-1, 275), > style=wx.TE_AUTO_SCROLL|wx.TE_READONLY|wx.TE_PROCESS_ENTER|wx.TE_WORDWRAP|wx.TE_MULTILINE ) > > > > You will probably have to edit TrafficPane.update so that it performs > > the action you want. BTW, the widgets are all stored in self.fields. > > You will need to look at the init to see how they stored to get the > > correct field if you want to change existing field behavior. > > > > self.fields["dest"] # Destination TextCtrl > > > > That being said, for your desired effect I think all you need to do > > is change: > > > > v.SetValue(f) > > > > to: > > > > old_text = v.GetValue() > > # You may need to modify or add some context as otherwise it will > > # just dump the data and may not make sense when looking at it > > # scroll. > > self.scrolling_widget.AppendText(old_text) > > v.SetValue(f) > > > >> > >> More importantly I need to save the values from the TextCtrl fields, > >> preferable in a CSV file, for later inspection. From looking at the > >> Logging HOWTO and the Logging Cookbook I see there are alot of loggers > >> available, or ways to log, but they all look like they are orientated > >> towards exception handling and debugging so I am unsure what is the best > >> way to go about this; maybe wxLogTextCtrl ? Utimately I need to log the > >> values from the TextCtrl fields in a row of comma separated values > >> adding a time/date stamp as one of the values. I need this log so the > >> data can easily be worked on in excel or SAS. I need the time/date > >> stamp for time series analysis. > > > > Create a list of lists with your data (think table). Then use the > > csv module to write that data to file. If you need to append, > > You should read all the existing data. Close the file, append > > your new data and then write to a new complete file. Once > > the write has succeeded, rename/overwrite the existing file. > > That will help prevent you from losing existing data if a problem > > occurs on write. > > > > # Sort the dictionary keys so you get the same order for each row > > row = [ field_values[k] for sorted(field_values) ] > > # Now read csv, append row, write new csv, and then overwrite old file > > > >> > >> I attached the code behind the wxPythoin GUI I am using. > >> Any help will be much appreciated. > >> > >> Thanks in advance > >> -- > >> Matt D > >> ------------ > > > > Well that should get you started. Post back if you need specific > > help with something else. > > > > > > > > ~Ramit > > > > > > This email is confidential and subject to important disclaimers and > > conditions including on offers for the purchase or sale of > > securities, accuracy and completeness of information, viruses, > > confidentiality, legal privilege, and legal entity disclaimers, > > available at http://www.jpmorgan.com/pages/disclosures/email. > > > > Hello, > > Thank you Ramit for your reply. I haven't had time to yet use the code > you have given me but will soon. But first, I am confused as to how the > code knows what values to display? I understand that the data comes out > of a 'pickle" but I don't understand how or how it is possible for > you/me (or us) to take only what we need out of the pickle without using > variable names (i have only used Visual Basic and C++). > > Also, should I just put the code into the file that is running in my > program? It doesn't need to be compiled right? I have not figured a way > to use an IDE because the code needs that pickle. > > Cheers, > Matt It looks to me like there is a separate thread that pulls data off some queue and then hands it to WX in the form of a DataEvent. WX calls display_data which unpickles the data. Pickle is just a format of storage and can store all Python built-in types. It seems that what is stored is a Python dictionary. In fact, you can probably add (and should add) a print statement to print attrs in display_data to see the data. It's always important to know what your data looks like. If you are only familiar with Visual Basic and C++, you may want to familiarize yourself with Dictionaries (aka Hashmaps). They are basically containers with key-value pairs for unique keys. By knowing the name of the data you want (for example "duid") you can retrieve the value and post it back to the appropriate TextCtrl. From hgfernan at gmail.com Wed Jun 5 20:26:00 2013 From: hgfernan at gmail.com (Hilton Fernandes) Date: Wed, 5 Jun 2013 15:26:00 -0300 Subject: [Tutor] Python Package Diagram In-Reply-To: References: Message-ID: Hi, Bjorm ! It would be cool to have one of these charts for Python. And for every other language, for sure. However, my guess is that for Python it would be much thinner. At least for the common usage. Probably the Qt, Gtk or Django architectures would be that thick. What do the Python gurus think ? All the best, hilton On Wed, Jun 5, 2013 at 11:45 AM, Bjorn Madsen wrote: > Hello Tutor, > On http://docs.oracle.com/javase/7/docs/ a pretty chart gives a more or > less misdirecting view of the Java library (I guess the gaps between the > boxes are the security holes). > > *Does something similar exist for Python?* > > Google images turned out with a stack of, well, not so pretty charts... > > Kind regards, > > Bjorn > > _______________________________________________ > 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 bjorn.h.madsen at googlemail.com Wed Jun 5 21:39:30 2013 From: bjorn.h.madsen at googlemail.com (Bjorn Madsen) Date: Wed, 5 Jun 2013 20:39:30 +0100 Subject: [Tutor] Python Package Diagram In-Reply-To: References: Message-ID: This is the closest I can get to an info-graphic http://goo.gl/RVXFZ (...I don't think I qualify as an artist...) Maybe a competition is required? On 5 June 2013 19:26, Hilton Fernandes wrote: > Hi, Bjorm ! > > It would be cool to have one of these charts for Python. And for every > other language, for sure. > > However, my guess is that for Python it would be much thinner. At least > for the common usage. Probably the Qt, Gtk or Django architectures would > be that thick. > > What do the Python gurus think ? > > All the best, > hilton > > On Wed, Jun 5, 2013 at 11:45 AM, Bjorn Madsen < > bjorn.h.madsen at googlemail.com> wrote: > >> Hello Tutor, >> On http://docs.oracle.com/javase/7/docs/ a pretty chart gives a more or >> less misdirecting view of the Java library (I guess the gaps between the >> boxes are the security holes). >> >> *Does something similar exist for Python?* >> >> Google images turned out with a stack of, well, not so pretty charts... >> >> Kind regards, >> >> Bjorn >> >> _______________________________________________ >> 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 cybervigilante at gmail.com Wed Jun 5 21:58:18 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 5 Jun 2013 12:58:18 -0700 Subject: [Tutor] Future Python In-Reply-To: References: <51AF24CB.2010501@pearwood.info> Message-ID: On 5 June 2013 06:35, Mark Lawrence wrote: > On 05/06/2013 12:45, Steven D'Aprano wrote: >> Of course, this has an easy explanation: the poster had the clock on his >> computer set to the wrong date, so his email also showed the wrong date. >> > > Or he borrowed Guido's time machine? :) > That's a relief. Of course, Guido has seen the future of programming. The majority of our processing is visual, and we Love consistent patterns, which is why everyone leaves the farm for the big city. As a former freelance webmaster (due to dislike of dealing with cheap customers, not incapacity), I recall the tortured line-endings of a nested Jquery chain, that made your eyes spin. The funny thing is, when they didn't work, you'd break them up into different lines, and indent them like, like, Python, so you could figure out what you'd done. This is so much easier on the eyes than jQuery. But Guido says "..no Python for browsers," alas. Hopefully, he's not too prescient. Why not javascript And Python for browsers? There just has to be enough of a clamor for it. Jim "Would you use Internet Explorer if someone put a gun to your head?" "How big is the gun?" From wprins at gmail.com Wed Jun 5 22:38:28 2013 From: wprins at gmail.com (Walter Prins) Date: Wed, 5 Jun 2013 21:38:28 +0100 Subject: [Tutor] Future Python In-Reply-To: References: <51AF24CB.2010501@pearwood.info> Message-ID: Jim, On 5 June 2013 20:58, Jim Mooney wrote: > But Guido says > "..no Python for browsers," alas. Hopefully, he's not too prescient. > Why not javascript And Python for browsers? There just has to be > enough of a clamor for it. > You might be interested to know there's several incarnations of Python for browser already available. PyJS and PyJaco are Python to Javascript compilers, and Brython is basically a Python subset that allows you to write Python and use it as a scripting language in client side web pages instead of Javascript: http://code.google.com/p/brython/ http://www.brython.info/ I'll leave you to google the other 2 yourself if you're interested. ;) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Thu Jun 6 01:28:00 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 5 Jun 2013 16:28:00 -0700 Subject: [Tutor] Future Python In-Reply-To: References: <51AF24CB.2010501@pearwood.info> Message-ID: On 5 June 2013 13:38, Walter Prins wrote: > Jim, > > You might be interested to know there's several incarnations of Python for > browser already available. PyJS and PyJaco are Python to Javascript > compilers, and Brython is basically a Python subset that allows you to > write Python and use it as a scripting language in client side web pages > instead of Javascript: > http://code.google.com/p/brython/ > http://www.brython.info/ > Brython looks interesting. After the joy of learning it I have to find a use for Python, and it appears even Django uses JS as the scripter. Probably so folks can use jQuery, which was a great idea, but is now being polluted by endless jQuery popups that have replaced the HTML popups I block. You will never get away from all popups unless you use Lynx ;') -- Jim "Would you use Internet Explorer if someone put a gun to your head?" "How big is the gun?" -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jun 6 01:28:42 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Jun 2013 00:28:42 +0100 Subject: [Tutor] Future Python In-Reply-To: References: <51AF24CB.2010501@pearwood.info> Message-ID: On 05/06/13 21:38, Walter Prins wrote: > Jim, > > On 5 June 2013 20:58, Jim Mooney > wrote: > > But Guido says > "..no Python for browsers," alas. > > You might be interested to know there's several incarnations of Python > for browser already available. And at one time there was a browser written in pure Python called Grail. Sadly it died through lack of support. But you can still run Python in IE using WindowsScriptHost and as Walter mentioned there are more exotic ways of doing it too. Guido didn't veto Python for browsers it's just hard to get the browser writers to support it so you need to resort to devious methods and technology. And JQuery can look perfectly fine if its formatted correctly. The problem is people often use compressors to remove extaneous characters from html and that tends to mangle the JScript code to the point of unreadability. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cybervigilante at gmail.com Thu Jun 6 02:10:49 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 5 Jun 2013 17:10:49 -0700 Subject: [Tutor] Future Python In-Reply-To: References: <51AF24CB.2010501@pearwood.info> Message-ID: On 5 June 2013 16:28, Alan Gauld wrote: > > > And JQuery can look perfectly fine if its formatted correctly. > The problem is people often use compressors to remove extaneous characters from html and that tends to mangle the JScript code > to the point of unreadability. There's a real temptation to go on and on with chaining in one line, since it's so cool to do so much with one line. What's good about Python is it Forces you to not be lazy. -- Jim "Would you use Internet Explorer if someone put a gun to your head?" "How big is the gun?" From francois.dion at gmail.com Thu Jun 6 02:22:12 2013 From: francois.dion at gmail.com (Francois Dion) Date: Wed, 5 Jun 2013 20:22:12 -0400 Subject: [Tutor] Future Python In-Reply-To: References: <51AF24CB.2010501@pearwood.info> Message-ID: You can combine django (or any other framework) with brython, just like you would with javascript. For example, just this past week, this example was posted to the brython list: https://github.com/mrjmad/django_socketio_test Francois -- www.pyptug.org - raspberry-python.blogspot.com - @f_dion On Wed, Jun 5, 2013 at 7:28 PM, Jim Mooney wrote: > On 5 June 2013 13:38, Walter Prins wrote: > >> Jim, >> >> >> You might be interested to know there's several incarnations of Python >> for browser already available. PyJS and PyJaco are Python to Javascript >> compilers, and Brython is basically a Python subset that allows you to >> write Python and use it as a scripting language in client side web pages >> instead of Javascript: >> http://code.google.com/p/brython/ >> http://www.brython.info/ >> > > Brython looks interesting. After the joy of learning it I have to find a > use for Python, and it appears even Django uses JS as the scripter. > Probably so folks can use jQuery, which was a great idea, but is now being > polluted by endless jQuery popups that have replaced the HTML popups I > block. You will never get away from all popups unless you use Lynx ;') > > -- > Jim > "Would you use Internet Explorer if someone put a gun to your head?" > "How big is the gun?" > > _______________________________________________ > 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 jacklittlemc at yahoo.com Thu Jun 6 03:57:04 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Wed, 5 Jun 2013 18:57:04 -0700 (PDT) Subject: [Tutor] Py2Exe Problems Message-ID: <1370483824.43115.YahooMailNeo@web124506.mail.ne1.yahoo.com> I have written a setup.py file to compile a script to a standalone exe. My error is here: Traceback (most recent call last): ? File "C:\Users\Jack\Desktop\compiler\setup.py", line 4, in ? ? setup(console=["te.py"]) ? File "C:\Python27\lib\distutils\core.py", line 140, in setup ? ? raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg SystemExit: usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] ? ?or: setup.py --help [cmd1 cmd2 ...] ? ?or: setup.py --help-commands ? ?or: setup.py cmd --help error: no commands supplied My code is here: from distutils.core import * import py2exe setup(console=["te.py"]) Get back to me asap.. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jun 6 08:29:33 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Jun 2013 07:29:33 +0100 Subject: [Tutor] Py2Exe Problems In-Reply-To: <1370483824.43115.YahooMailNeo@web124506.mail.ne1.yahoo.com> References: <1370483824.43115.YahooMailNeo@web124506.mail.ne1.yahoo.com> Message-ID: On 06/06/13 02:57, Jack Little wrote: > I have written a setup.py file to compile a script to a standalone exe. > My error is here: > Traceback (most recent call last): > File "C:\Users\Jack\Desktop\compiler\setup.py", line 4, in > setup(console=["te.py"]) > File "C:\Python27\lib\distutils\core.py", line 140, in setup > raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg > SystemExit: usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 > [cmd2_opts] ...] > or: setup.py --help [cmd1 cmd2 ...] > or: setup.py --help-commands > or: setup.py cmd --help > > error: no commands supplied So did you supply any commands? If so what? How did you call it? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From msg.ufo at gmail.com Thu Jun 6 10:28:04 2013 From: msg.ufo at gmail.com (Mike G) Date: Thu, 6 Jun 2013 01:28:04 -0700 Subject: [Tutor] Py2Exe Problems Message-ID: Hi Jack ...> From: Jack Little ...> Date: Wed, 5 Jun 2013 18:57:04 -0700 (PDT) ...> ...> I have written a setup.py file to compile a script to a standalone exe. ...> My code is here: ...> from distutils.core import * ...> import py2exe ...> setup(console=["te.py"]) Did you try importing 'setup' """ from distutils.core import setup import py2exe setup(console=['te.py']) """ Mike From cybervigilante at gmail.com Thu Jun 6 11:30:17 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Thu, 6 Jun 2013 02:30:17 -0700 Subject: [Tutor] import * not allowed at function level - wassup? Message-ID: In the program below, which now works, I tried to use "from tkinter.constants import *" to throw up an error message with tkinter, and got the error "import * only allowed at module level." So I instead imported tkinter.constants, but then I had to prepend every constant with tkinter.constants, which is annoying. Is there a way around that prohibition (and what's it for, anyway?) So I kludged the problem a bit by letting K = tkinter.constants, but I'd still just like to use the constants without any qualifiers, which I can do without a function. Except the error routine doesn't belong in the main program, IMHO, since it fuddles the main logic of getting a Fibonacci sequence. I want it out of the way and callable. (The message box appeared behind my editor, and was not visible, which drove me nuts, but it works fine at the dos prompt ;') #Using Python 3.3.2 on Win 7 - standard project, standard test file """Print a user-chosen Fibonacci sequence""" x = 0 fib = [0,1] attempts = 0 def die_on_errors(): """Throw up a message box and quit if too many bad entries are made""" import tkinter import tkinter.constants K = tkinter.constants tk = tkinter.Tk() frame = tkinter.Frame(tk, relief=K.GROOVE, borderwidth=5) frame.pack(fill=K.BOTH,expand=1) label = tkinter.Label(frame, text="\n Too many errors, quitting \n ") label.pack(fill=K.X, expand=1) tk.mainloop() user_prompt = "How long do you want your Fibonacci sequence?" user_error = "That's not an integer, please enter the desired integer length\ of your Fibonacci series again." while True: try: fiblong = int(input(user_prompt)) break except ValueError: attempts += 1 if attempts > 6: die_on_errors() exit('bye, bye') user_prompt = user_error for cnt in range(0,fiblong - 2): fib.append(fib[x] + fib[x+1]) x += 1 print(fib) -- Jim "Would you use Internet Explorer if someone put a gun to your head?" "How big is the gun?" From davea at davea.name Thu Jun 6 12:22:38 2013 From: davea at davea.name (Dave Angel) Date: Thu, 06 Jun 2013 06:22:38 -0400 Subject: [Tutor] import * not allowed at function level - wassup? In-Reply-To: References: Message-ID: <51B062EE.1010201@davea.name> On 06/06/2013 05:30 AM, Jim Mooney wrote: > In the program below, which now works, I tried to use "from > tkinter.constants import *" to throw up an error message with tkinter, > and got the error "import * only allowed at module level." So I > instead imported tkinter.constants, but then I had to prepend every > constant with tkinter.constants, which is annoying. Is there a way > around that prohibition (and what's it for, anyway?) from xx import * is generally discouraged, for a reason known as "namespace pollution." Once you've done that in a module, you no longer can tell from the source file where a particular symbol comes from. Further, if you do it from more than one module, then the latter module hides symbols from the earlier one, invisibly. If the modules change over time, then features you don't even use might stop features that you do from working properly. Instead, try to use: from xx import CONST1, CONST2, func3, func4, Class5 Here we can tell which constants, functions, and classes we're getting from the module, and can readily tell if there are any conflicts. Further, we can use the "as" notation to rename those that do create conflicts. As for using the first form inside a function, it's probably useful to point out that locals inside functions are treated specially, and this special treatment leads not only to smaller compiled code, but faster (frequently much faster) code. The compiler decides what all the local variables are for a given function, and gives each a number. The number of slots is known when the function is entered, so a fixed structure can be used. And each value is looked up at runtime by index (or slot number), and not by name. You may have already seen the other effect of this, which is that you can't usefully add new entries to locals() inside a function. So inside the function, use the same syntax shown above. I don't use tkinter, so I may mess it up some. But something like: def die_on_errors(): from tkinter.constants import BOTH, X #now BOTH and X are directly accessible, as local (constant) variables. Without qualifiers. Although X is a terrible name, perhaps it has some useful mnemonic in tkinter-speak. Another comment, since you're referring to constants. No reason that the function cannot refer to global constants, since it won't be doing any assignments to them, and therefore they don't need slots. However, I hesitate to point that out, since it permits you to not only use the dreaded 'from xx import *' but it also separates reference to these arbitrary, undeclared names from their point of import. > > So I kludged the problem a bit by letting K = tkinter.constants, but > I'd still just like to use the constants without any qualifiers, which > I can do without a function. Except the error routine doesn't belong > in the main program, I hope you're not implying that you have a non-trivial "program" as top-level code ?? !! Looking further, it appears you are. Please learn to use if __name__ == "__main__": doit() or equivalent. Doesn't matter for toy projects, but sooner or later you're going to write some code you want to modify later, or reuse as a module. At that point you'll wish it were already in functions. Good rule of thumb is to include only the following kinds of things at top-level: 1) imports 2) the above if name==main thingie 3) calls to argv parsing 4) some help, in case argv stuff isn't right 5) calls to main(), whatever it's named > IMHO, since it fuddles the main logic of getting > a Fibonacci sequence. I want it out of the way and callable. > > (The message box appeared behind my editor, and was not visible, which > drove me nuts, but it works fine at the dos prompt ;') > > #Using Python 3.3.2 on Win 7 - standard project, standard test file > """Print a user-chosen Fibonacci sequence""" > x = 0 > fib = [0,1] > attempts = 0 > > def die_on_errors(): > """Throw up a message box and quit if too many bad entries are made""" > import tkinter > import tkinter.constants > K = tkinter.constants > tk = tkinter.Tk() > frame = tkinter.Frame(tk, relief=K.GROOVE, borderwidth=5) > frame.pack(fill=K.BOTH,expand=1) > label = tkinter.Label(frame, text="\n Too many errors, quitting \n ") > label.pack(fill=K.X, expand=1) > tk.mainloop() > > user_prompt = "How long do you want your Fibonacci sequence?" > user_error = "That's not an integer, please enter the desired integer length\ > of your Fibonacci series again." > > while True: > try: > fiblong = int(input(user_prompt)) > break > except ValueError: > attempts += 1 > if attempts > 6: > die_on_errors() > exit('bye, bye') > user_prompt = user_error > > for cnt in range(0,fiblong - 2): > fib.append(fib[x] + fib[x+1]) > x += 1 > Why have 'x' here, when cnt is precisely the same thing, and is defined right here in the loop? > print(fib) > > -- DaveA From alan.gauld at btinternet.com Thu Jun 6 14:56:59 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 06 Jun 2013 13:56:59 +0100 Subject: [Tutor] import * not allowed at function level - wassup? In-Reply-To: References: Message-ID: On 06/06/13 10:30, Jim Mooney wrote: > In the program below, which now works, I tried to use "from > tkinter.constants import *" to throw up an error message with tkinter, > and got the error "import * only allowed at module level." So I > instead imported tkinter.constants, but then I had to prepend every > constant with tkinter.constants, which is annoying. Is there a way > around that prohibition (and what's it for, anyway?) Not the prohibition - although in general imports are done at module level. You don't really want to try to import every time you call a function.... But you can rename an import: import foo as f or you can import explicitly from tkinter.constants import foo,bar,baz... importing * is generally a bad idea in real code. hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bicofino at gmail.com Thu Jun 6 15:08:37 2013 From: bicofino at gmail.com (Danilo Chilene) Date: Thu, 6 Jun 2013 10:08:37 -0300 Subject: [Tutor] Argparse functions with N parameters In-Reply-To: References: Message-ID: Hello, It's ok to revive a old thread? :) I finished my script (https://github.com/bicofino/Pyora) using argparse. But I have a question, today I'm connecting to the database outside the class Check, what's the best way to connect passing the arguments using argparse and run a function. Today it work like this: # Check Oracle version 0: python pyora.py version Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi I was thinking that is better pass the database arguments(username,password,address,database) it would run like this: python pyora.py username,password,address,database version Any thoughts? Best Regards, Danilo On Wed, May 8, 2013 at 10:31 AM, Danilo Chilene wrote: > > > That solves my issue. > > Thanks Peter. > > To unsubscribe or change subscription options: > >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cbc at unc.edu Thu Jun 6 21:11:48 2013 From: cbc at unc.edu (Calloway, Chris) Date: Thu, 6 Jun 2013 19:11:48 +0000 Subject: [Tutor] Python Community Training Events Message-ID: Here are some upcoming Python community training events organized by the Triangle Python Users Group: PyOhio PyCamp 2013 offered July 22-26, 2013 at Ohio State University in conjunction with the PyOhio 2013 regional Python conference: http://trizpug.org/boot-camp/pyohio13/ Python Network and Web Programming Workshop offered August 5-9, 2013 at the University of North Carolina: http://trizpug.org/boot-camp/pywebpw13/ Toronto PyCamp 2013 offered August 12-16, 2013 at the University of Toronto in conjunction with the PyCon Canada 2013 national Python conference: http://trizpug.org/boot-camp/torpy13/ Seattle PyCamp 2013 offered September 9-13, 2013 at the University of Washington's Paul G. Allen Center for Computer Science and Engineering: http://trizpug.org/boot-camp/seapy13/ -- Sincerely, Chris Calloway UNC-CH Department of Marine Sciences 3313 Venable Hall CB 3300 Chapel Hill, NC 27599-3300 (919) 599-3530 From __peter__ at web.de Fri Jun 7 09:58:39 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Jun 2013 09:58:39 +0200 Subject: [Tutor] Argparse functions with N parameters References: Message-ID: Danilo Chilene wrote: > Hello, > > It's ok to revive a old thread? :) > > I finished my script (https://github.com/bicofino/Pyora) using argparse. > > But I have a question, today I'm connecting to the database outside the > class Check, what's the best way to connect passing the arguments using > argparse and run a function. > > Today it work like this: > > # Check Oracle version > 0: python pyora.py version > Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi > > > I was thinking that is better pass the database > arguments(username,password,address,database) > > it would run like this: > python pyora.py username,password,address,database version > > Any thoughts? Untested: > class Main(Checks): > def __init__(self): > parser = argparse.ArgumentParser() parser.add_argument("username") parser.add_argument("--password") parser.add_argument("address") ... > subparsers = parser.add_subparsers() > > for name in dir(self): > if not name.startswith("_"): > p = subparsers.add_parser(name) > method = getattr(self, name) > argnames = inspect.getargspec(method).args[1:] > for argname in argnames: > p.add_argument(argname) > p.set_defaults(func=method, argnames=argnames) > self.args = parser.parse_args() def db_connect(self): a = self.args username = a.username password = a.password if password is None: password = getpass.getpass() ... self.db = cx_oracle.connect(...) self.cur = self.db.cursor() def db_close(self): self.db.close() > def __call__(self): > a = self.args > callargs = [getattr(a, name) for name in a.argnames] self.db_connect() try: return self.args.func(*callargs) finally: self.db_close() Of course you have to modify your methods to use self.cur instead of a global cur. From chigga101 at gmail.com Fri Jun 7 17:25:08 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Fri, 7 Jun 2013 16:25:08 +0100 Subject: [Tutor] web software applictions Message-ID: Hi all. Im alright with using GUI toolkits and i always thought the difference between desktop apps and web apps was that one was an application in a browser that had similar widgets to a desktop app. Now ive realised this is wrong. A web app is simply a web page, their is no program or UI. I wanted to learn how to make some actual applications on the web similar to gui toolkits, for instance a graphical web calculator with ui specific widgets like buttons etc. something like this: http://web2.0calc.com/ can the usual python web frameworks design this? if not, is there a tool in Python i can use that comes with GUI widgets etc that can create these graphical web applications. Thanks From timomlists at gmail.com Fri Jun 7 20:32:38 2013 From: timomlists at gmail.com (Timo) Date: Fri, 07 Jun 2013 20:32:38 +0200 Subject: [Tutor] web software applictions In-Reply-To: References: Message-ID: <51B22746.8080902@gmail.com> Op 07-06-13 17:25, Matthew Ngaha schreef: > Hi all. Im alright with using GUI toolkits and i always thought the > difference between desktop apps and web apps was that one was an > application in a browser that had similar widgets to a desktop app. > Now ive realised this is wrong. A web app is simply a web page, their > is no program or UI. I wanted to learn how to make some actual > applications on the web similar to gui toolkits, for instance a > graphical web calculator with ui specific widgets like buttons etc. > > something like this: http://web2.0calc.com/ > > can the usual python web frameworks design this? if not, is there a > tool in Python i can use that comes with GUI widgets etc that can > create these graphical web applications. Most webpages are just HTML with CSS, this calculator is no exception. Have a look at the page source and you'll see this (for button "7"): 7 See the stylesheets for the corresponding CSS. I also notice they are using Twitter Bootstrap, which handles a lot of things already for you: http://twitter.github.io/bootstrap/ Timo > > Thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Fri Jun 7 20:48:12 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 07 Jun 2013 19:48:12 +0100 Subject: [Tutor] web software applictions In-Reply-To: References: Message-ID: On 07/06/13 16:25, Matthew Ngaha wrote: > ... A web app is simply a web page, their is no program or UI. That's not true. The program is there but its running on the web server not on the user's PC. The UI is defined using HTML which is generated by the web program as its output. This is one reason that traditional web apps are inherently slow and clunky compared to desktop apps - they have to send both the data and the UI in every transaction payload whereas a desktop app only needs the data. Modern web technologies address that issue with tools like Ajax, JSON and JQuery which allow the UI code to be sent once and then other action on a page to just send data and the browser updates the UI with the changes. > applications on the web similar to gui toolkits, for instance a > graphical web calculator with ui specific widgets like buttons etc. You can actually write a calculator program in pure HTML/Javascript and it will work without a web server. But... > can the usual python web frameworks design this? The usual web frameworks can indeed deliver a calculator or any other kind of web app. All web apps consist of a web page presenting the UI and a set of response functions/methods that react to user input. Each function returns either a new web page or an update to the existing one. > tool in Python i can use that comes with GUI widgets etc that can > create these graphical web applications. It depends how sophisticated you want the widgets to be. The basic form widgets - text boxes, radio buttons, scroll bars, list boxes, buttons etc are all just HTML. If you want fancier widgets then you have to design the look yourself and present them as images and then manually code up the event handling which is equivalent to creating your own GUI widget on the desktop - but there are fewer widgets to start with in HTML. For things like drag n drop you need to use Javascript/Jquery type code. Finally you can create Java applets and embed them in your HTML page but for several reasons this has gone out of favour. And with HTML5 bringing lots more features for building apps there is even less need for Java in the browser. (Unfortunately HTML5 is not completely supported in the popular browsers yet) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From md123 at nycap.rr.com Fri Jun 7 21:44:49 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 07 Jun 2013 15:44:49 -0400 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> Message-ID: <51B23831.1020202@nycap.rr.com> > It looks to me like there is a separate thread that pulls data off some queue > and then hands it to WX in the form of a DataEvent. WX calls display_data > which unpickles the data. Pickle is just a format of storage and can store > all Python built-in types. It seems that what is stored is a Python > dictionary. In fact, you can probably add (and should add) a print statement > to print attrs in display_data to see the data. It's always important to know > what your data looks like. If you are only familiar with Visual Basic and C++, > you may want to familiarize yourself with Dictionaries (aka Hashmaps). They > are basically containers with key-value pairs for unique keys. By knowing the > name of the data you want (for example "duid") you can retrieve the value and > post it back to the appropriate TextCtrl. > Hey, So is the separate thread is this??: import gnuradio.gr.gr_threading as _threading This is how the pickled data is brought into the wxPython UI? I have been unable to find any explanation on the web about the wxDATA_EVENT? The 'class traffic_watcher_thread(_threading.Thread):' is this what waits on the message queue for another frame of pickled data to come in? One of the main problems I have with understanding the Python code I have shared is that the pickle comes from C++ code. The program uses C++ for what is computational intense and it uses Python for the UI and for sending the data stream between the C++ blocks. I have never tried modifying code in a program that uses two languages before. >From python.org/2/library/pickle: "Perhaps the most obvious thing to do with these byte streams is to write them onto a file" and sense "the pickle data format uses a printable ASCII representation" . . . "it is possible for a human to read the pickled file with a standard text editor." I would love to have this wxPython code write the pickled data to file just to see exactly what is in it. Do you know of some sort of code I can put in to make the pickle write to a file? I think this is the best starting point instead of playing with the UI. Thank you very much for your attention. Cheers, Matt From cybervigilante at gmail.com Fri Jun 7 23:07:07 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 7 Jun 2013 14:07:07 -0700 Subject: [Tutor] startups for programmers Message-ID: This might be interesting to some here. Only requires basic programming skill as a prerequisite, but surveys most web programming. Teaches how to create a web or tech startup company, and avoid the usual errors. Free course: http://online.stanford.edu/course/startup-engineering Learn the engineering skills needed to build a technology startup from the ground up. -- Jim "Would you use Internet Explorer if someone put a gun to your head?" "How big is the gun?" From md123 at nycap.rr.com Sat Jun 8 03:22:33 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 07 Jun 2013 21:22:33 -0400 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> Message-ID: <51B28759.60201@nycap.rr.com> >>> Scrolled panel is just a graphical container that allows for scrolling inside, >>> but it is the window that scrolls not widgets inside it. This of it like >>> a webpage that scrolls. If you use web email the text widget in the >>> email needs to scroll so you can see your full email context and not >>> just scroll the page. >>> >>> You will probably need to create a TextCtrl with the appropriate style >>> and append your new data. I have given an example below that should >>> automatically scroll with your new data. >>> >>> #in __init__ >>> self.scrolling_widget = wx.TextCtrl( self, wx.ID_ANY, '', size=(-1, 275), >> style=wx.TE_AUTO_SCROLL|wx.TE_READONLY|wx.TE_PROCESS_ENTER|wx.TE_WORDWRAP|wx.TE_MULTILINE ) >>> Hey, I added this the above 3 lines of code to my file and ran it. the box shows up on the far left, mostly of the pane, to the left of the current text feilds. I am having trouble positioning this textbox under where the current text fields are. I am not sure but maybe this sets up the grid on the pane: sizer = wx.GridBagSizer(hgap=10, vgap=10) self.fields = {} all the current TextCtrl fields are positioned at (1,1) through (5,5). I tried adding: sizer.Add(field, pos=(1,6)) but it did not move the box to the position? THanks, Matt From cybervigilante at gmail.com Sat Jun 8 05:11:16 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 7 Jun 2013 20:11:16 -0700 Subject: [Tutor] three numbers for one Message-ID: I'm puzzling out the difference between isdigit, isdecimal, and isnumeric. But at this point, for simple practice programs, which is the best to use for plain old 0123456589 , without special characters? -- Jim "Would you use Internet Explorer if someone put a gun to your head?" "How big is the gun?" From steve at pearwood.info Sat Jun 8 07:25:48 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 08 Jun 2013 15:25:48 +1000 Subject: [Tutor] three numbers for one In-Reply-To: References: Message-ID: <51B2C05C.1040401@pearwood.info> On 08/06/13 13:11, Jim Mooney wrote: > I'm puzzling out the difference between isdigit, isdecimal, and > isnumeric. But at this point, for simple practice programs, which is > the best to use for plain old 0123456589 , without special characters? Context? Are you talking about the string methods, isdigit, isdecimal and isnumeric in Python 3? You should say so rather than have us guess. Assuming this is what you mean, the short answer is, use isdecimal. Or better still, don't use any of them -- as the saying goes, it is better to ask forgiveness than permission. Instead of: if s.isdecimal(): n = int(s) else: print("not a number") it is usually better to just call int(s) and catch the exception. But occasionally it is handy or useful to "Look Before You Leap" and find out whether a string is numeric first, and for that Python 3 provides three methods. The Unicode standard defines three categories of "numeric character": === Decimal Digit, or category 'Nd' === This includes the familiar "Arabic numerals" we use in English and most European languages: 0123456789 plus actual Arabic numerals: ?????????? (which ironically are called "Indian numerals" in the parts of the Arab world that use them), and various others, such as Tamil, Bengali, Thai, and many others. Here is a full list: http://www.fileformat.info/info/unicode/category/Nd/list.htm (Note: if the above Arabic-Indic digits looks like garbage or mojibake, tell your email client to use the UTF-8 encoding. Most good email programs will automatically do so, but if it doesn't, there is usually a way to set the encoding by hand. If they look like square boxes, try changing the font you are using for display.) The str.isdecimal() method returns True if the string contains only characters in the 'Nd' Unicode category. isdecimal() is the most specific of the three methods. Python's int() and float() functions will happily convert strings made of such characters into numbers: py> s = '\N{TIBETAN DIGIT THREE}\N{TIBETAN DIGIT SEVEN}' py> int(s) 37 === Other Number, or category 'No' === These are characters which represents numerals, but in some context other than "ordinary" numbers. For example, they include fractions, special currency numerals, superscripts and subscripts. The full list is here: http://www.fileformat.info/info/unicode/category/No/list.htm The str.isdigit() returns True for anything that str.isdecimal() returns True, plus *some* characters in the 'No' category. To be precise, it returns True for those characters whose Unicode property includes Numeric_Type=Digit or Numeric_Type=Decimal. For example, superscript digits count as a digit, but fractions do not. py> '?'.isdigit() True py> '?'.isdigit() False int() and float() do *not* convert such characters to numbers. If you want to support them, you have to manually convert them yourself, or you can use the unicodedata.numeric() function. === Letter Number, or category 'Nl' === This includes characters which are technically letters, but are used as numbers. Examples include Ancient Roman, Ancient Greek, Cuneiform and Hangzhou numerals. The full list is here: http://www.fileformat.info/info/unicode/category/Nl/list.htm Like 'No', int() and float() do not convert such characters. The str.isnumeric() method is the least specific of the three methods. It returns True if the string contains only characters in any of the three numeric categories, 'Nd', 'No' and 'Nl'. -- Steven From eryksun at gmail.com Sat Jun 8 07:49:03 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 8 Jun 2013 01:49:03 -0400 Subject: [Tutor] three numbers for one In-Reply-To: References: Message-ID: On Fri, Jun 7, 2013 at 11:11 PM, Jim Mooney wrote: > I'm puzzling out the difference between isdigit, isdecimal, and > isnumeric. But at this point, for simple practice programs, which is > the best to use for plain old 0123456589 , without special characters? The isnumeric, isdigit, and isdecimal predicates use Unicode character properties that are defined in UnicodeData.txt: http://www.unicode.org/Public/6.1.0/ucd The most restrictive of the 3 is isdecimal. If a string isdecimal(), you can convert it with int() -- even if you're mixing scripts: >>> unicodedata.name('\u06f0') 'EXTENDED ARABIC-INDIC DIGIT ZERO' >>> unicodedata.decimal('\u06f0') 0 >>> '1234\u06f0'.isdecimal() True >>> int('1234\u06f0') 12340 The relevant fields in the database are described in Unicode Standard Annex #44: http://www.unicode.org/reports/tr44/tr44-6.html#UnicodeData.txt (6) If the character has the property value Numeric_Type=Decimal, then the Numeric_Value of that digit is represented with an integer value (limited to the range 0..9) in fields 6, 7, and 8. Characters with the property value Numeric_Type=Decimal are restricted to digits which can be used in a decimal radix positional numeral system and which are encoded in the standard in a contiguous ascending range 0..9. See the discussion of decimal digits in Chapter 4, Character Properties in [Unicode]. (7) If the character has the property value Numeric_Type=Digit, then the Numeric_Value of that digit is represented with an integer value (limited to the range 0..9) in fields 7 and 8, and field 6 is null. This covers digits that need special handling, such as the compatibility superscript digits. (8) If the character has the property value Numeric_Type=Numeric, then the Numeric_Value of that character is represented with a positive or negative integer or rational number in this field, and fields 6 and 7 are null. This includes fractions such as, for example, "1/5" for U+2155 VULGAR FRACTION ONE FIFTH. Some characters have these properties based on values from the Unihan data files. See Numeric_Type, Han. Here are the records for ASCII 0-9: 0030;DIGIT ZERO;Nd;0;EN;;0;0;0;N;;;;; 0031;DIGIT ONE;Nd;0;EN;;1;1;1;N;;;;; 0032;DIGIT TWO;Nd;0;EN;;2;2;2;N;;;;; 0033;DIGIT THREE;Nd;0;EN;;3;3;3;N;;;;; 0034;DIGIT FOUR;Nd;0;EN;;4;4;4;N;;;;; 0035;DIGIT FIVE;Nd;0;EN;;5;5;5;N;;;;; 0036;DIGIT SIX;Nd;0;EN;;6;6;6;N;;;;; 0037;DIGIT SEVEN;Nd;0;EN;;7;7;7;N;;;;; 0038;DIGIT EIGHT;Nd;0;EN;;8;8;8;N;;;;; 0039;DIGIT NINE;Nd;0;EN;;9;9;9;N;;;;; Notice the decimal value is repeated for fields 6-8. The category is 'Nd' (decimal number). Here's the record for superscript two (U+00B2): 00B2;SUPERSCRIPT TWO;No;0;EN; 0032;;2;2;N; SUPERSCRIPT DIGIT TWO;;;; Notice in this case that field 6 is null (empty), so this is not a decimal number. The category is 'No' (other number). int('\xb2') raises a ValueError, but you can use unicodedata.digit() to get the value: >>> '\xb2' '?' >>> unicodedata.digit('\xb2') 2 unicodedata.numeric() returns the value as a float: >>> unicodedata.numeric('\xb2') 2.0 Finally, here's the record for the character "1/5" (U+2155): 2155;VULGAR FRACTION ONE FIFTH;No;0;ON; 0031 2044 0035;;;1/5;N; FRACTION ONE FIFTH;;;; In this case both field 6 and field 7 are null. The category is 'No', which is the same as superscript two, but this character is *not* flagged as a digit. That's why the predicate functions don't use the General_Category, but instead use the more specific information provided by the Numeric_Type. Recall that unicodedata.numeric() outputs a float: >>> '\u2155' '?' >>> unicodedata.numeric('\u2155') 0.2 ==== The following are just some random observations that you can feel free to ignore: The award for the biggest numeric value of all goes to CJK ideograph 5146: >>> '\u5146' '?' >>> unicodedata.numeric('?') 1000000000000.0 The following Bengali/Oriya/North Indic characters tie for the smallest magnitude (1/16): >>> '\u09f4', '\u0b75', '\ua833' ('?', '?', '?') >>> unicodedata.name('?') 'BENGALI CURRENCY NUMERATOR ONE' >>> unicodedata.name('?') 'ORIYA FRACTION ONE SIXTEENTH' >>> unicodedata.name('\ua833') 'NORTH INDIC FRACTION ONE SIXTEENTH' >>> unicodedata.numeric('?') 0.0625 Tibet wins an award for having the only character with a negative value: >>> '\u0f33' '?' >>> unicodedata.name('?') 'TIBETAN DIGIT HALF ZERO' >>> unicodedata.numeric('?') -0.5 From cybervigilante at gmail.com Sat Jun 8 09:01:51 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 8 Jun 2013 00:01:51 -0700 Subject: [Tutor] three numbers for one In-Reply-To: References: Message-ID: On 7 June 2013 22:49, eryksun wrote: > 0.0625 > > Tibet wins an award for having the only character with a negative value: > > >>> '\u0f33' > '?' > >>> unicodedata.name('?') > 'TIBETAN DIGIT HALF ZERO' > >>> unicodedata.numeric('?') > -0.5 There are programmers in Tibet? That certainly changes my picture of the place. Jim -- Jim "Would you use Internet Explorer if someone put a gun to your head?" "How big is the gun?" From eryksun at gmail.com Sat Jun 8 09:40:41 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 8 Jun 2013 03:40:41 -0400 Subject: [Tutor] three numbers for one In-Reply-To: <51B2C05C.1040401@pearwood.info> References: <51B2C05C.1040401@pearwood.info> Message-ID: On Sat, Jun 8, 2013 at 1:25 AM, Steven D'Aprano wrote: > > The str.isnumeric() method is the least specific of the three methods. It > returns True if the string contains only characters in any of the three > numeric categories, 'Nd', 'No' and 'Nl'. It's strictly more accurate to say isnumeric is based on the numeric type instead of the general category. This agrees with the result in Python even if there are quirks in the database. For example, Python 3.3 uses Unicode 6.1, which has 4 'Nl' characters (out of 224) that have no defined numeric value (i.e. field 8 is null): 12432;CUNEIFORM NUMERIC SIGN SHAR2 TIMES GAL PLUS DISH; Nl;0;L;;;;;N;;;;; 12433;CUNEIFORM NUMERIC SIGN SHAR2 TIMES GAL PLUS MIN; Nl;0;L;;;;;N;;;;; 12456;CUNEIFORM NUMERIC SIGN NIGIDAMIN; Nl;0;L;;;;;N;;;;; 12457;CUNEIFORM NUMERIC SIGN NIGIDAESH; Nl;0;L;;;;;N;;;;; So Python 3.3 happily declares these characters to be 'Nl' and yet non-numeric: >>> unicodedata.category('\U00012432') 'Nl' >>> '\U00012432'.isnumeric() False >>> unicodedata.numeric('\U00012432') Traceback (most recent call last): File "", line 1, in ValueError: not a numeric character Unicode 6.2 fixes this: 12432;CUNEIFORM NUMERIC SIGN SHAR2 TIMES GAL PLUS DISH; Nl;0;L;;;;216000;N;;;;; 12433;CUNEIFORM NUMERIC SIGN SHAR2 TIMES GAL PLUS MIN; Nl;0;L;;;;432000;N;;;;; 12456;CUNEIFORM NUMERIC SIGN NIGIDAMIN; Nl;0;L;;;;-1;N;;;;; 12457;CUNEIFORM NUMERIC SIGN NIGIDAESH; Nl;0;L;;;;-1;N;;;;; Unicode 6.3 fixes it again: 12456;CUNEIFORM NUMERIC SIGN NIGIDAMIN; Nl;0;L;;;;2;N;;;;; 12457;CUNEIFORM NUMERIC SIGN NIGIDAESH; Nl;0;L;;;;3;N;;;;; 3rd time's a charm, right? From eryksun at gmail.com Sat Jun 8 09:48:18 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 8 Jun 2013 03:48:18 -0400 Subject: [Tutor] three numbers for one In-Reply-To: References: Message-ID: On Sat, Jun 8, 2013 at 3:01 AM, Jim Mooney wrote: > On 7 June 2013 22:49, eryksun wrote: > >> 0.0625 >> >> Tibet wins an award for having the only character with a negative value: >> >> >>> '\u0f33' >> '?' >> >>> unicodedata.name('?') >> 'TIBETAN DIGIT HALF ZERO' >> >>> unicodedata.numeric('?') >> -0.5 > > There are programmers in Tibet? That certainly changes my picture of the place. The half digits are controversial anyway: http://babelstone.blogspot.com/2007/04/numbers-that-dont-add-up-tibetan-half.html The problem with these characters is that it is very hard to get hold of any examples of their usage, and even respected Tibetan experts (and most Tibetans) are not familiar with them other than from the Unicode character charts. Tibetan reference books are universally silent on these characters, and as no other Indic scripts have similar half digits it is not immediately evident what they are meant to represent. From alan.gauld at btinternet.com Sat Jun 8 09:51:11 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 08 Jun 2013 08:51:11 +0100 Subject: [Tutor] three numbers for one In-Reply-To: References: Message-ID: On 08/06/13 08:01, Jim Mooney wrote: >> >>> unicodedata.name('?') >> 'TIBETAN DIGIT HALF ZERO' >> >>> unicodedata.numeric('?') >> -0.5 > > There are programmers in Tibet? That certainly changes my picture of the place. Even if there aren't programmers (and I'm pretty sure there will be) there are definitely writers. And Unicode is primarily for writers' benefit not programmers - we'd probably prefer to make everyone use ASCII! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cybervigilante at gmail.com Sat Jun 8 17:09:08 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 8 Jun 2013 08:09:08 -0700 Subject: [Tutor] three numbers for one In-Reply-To: <51B2C05C.1040401@pearwood.info> References: <51B2C05C.1040401@pearwood.info> Message-ID: Steven D'Aprano > Are you talking about the string methods, isdigit, isdecimal and isnumeric > in Python 3? You should say so rather than have us guess. If it's not the header in a program fragment, assume PY3 for the next year, at least. I don't plan on changing again - even if they come out with Py4 ;') > it is usually better to just call int(s) and catch the exception. Actually, I like that better than other tests Putting try..except in a while True loop and breaking out when the try succeeds seems the most natural way to do input, to me. Jim From davea at davea.name Sat Jun 8 17:26:54 2013 From: davea at davea.name (Dave Angel) Date: Sat, 08 Jun 2013 11:26:54 -0400 Subject: [Tutor] three numbers for one In-Reply-To: References: <51B2C05C.1040401@pearwood.info> Message-ID: <51B34D3E.9020205@davea.name> On 06/08/2013 11:09 AM, Jim Mooney wrote: > Steven D'Aprano > >> in Python 3? You should say so rather than have us guess. > > If it's not the header in a program fragment, assume PY3 for the next > year, at least. Unless we each started a notebook where we keep such information, only those with an extraordinary memory would be able to track such details for thousands of posters. Do you remember that Scurvy Scott uses Mingus ? Me neither. -- DaveA From michaelsparks37 at gmail.com Sat Jun 8 17:58:16 2013 From: michaelsparks37 at gmail.com (Michael Sparks) Date: Sat, 8 Jun 2013 08:58:16 -0700 Subject: [Tutor] How does formatted printing work? Message-ID: You can explain it yourself or just drop me a link (or both). Right now I'm learning Python 2.x but I plan on learning Python 3.x as well. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Jun 8 18:35:13 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 08 Jun 2013 17:35:13 +0100 Subject: [Tutor] How does formatted printing work? In-Reply-To: References: Message-ID: On 08/06/2013 16:58, Michael Sparks wrote: > You can explain it yourself or just drop me a link (or both). > Right now I'm learning Python 2.x but I plan on learning Python 3.x as well. > Try http://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting or http://docs.python.org/3/library/string.html#formatstrings for starters. -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From steve at pearwood.info Sat Jun 8 20:03:54 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 09 Jun 2013 04:03:54 +1000 Subject: [Tutor] How does formatted printing work? In-Reply-To: References: Message-ID: <51B3720A.5010607@pearwood.info> On 09/06/13 01:58, Michael Sparks wrote: > You can explain it yourself or just drop me a link (or both). > Right now I'm learning Python 2.x but I plan on learning Python 3.x as well. Formatted printing? First you format something, then you print it. Other than that, you will need to explain your question in more detail. I can't read your mind, so I don't know if you're having trouble understanding "formatting" (which formatting? there are at least four things which might be described as "formatting") or "printing" (which printing? there are at least three things which might be described as "printing"). So please don't assume that just because a question is clear and obvious in your mind, it is necessarily clear and obvious to everyone else. And for the record: 1) format() built-in function; 2) str.format() method; 3) % string interpolation; 4) string templates; and 1) printing to an actual printer; 2) print statement; 3) the pprint ("pretty printing") module. -- Steven From cybervigilante at gmail.com Sat Jun 8 23:46:56 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 8 Jun 2013 14:46:56 -0700 Subject: [Tutor] recursion surprise Message-ID: I was trying out simple recursion as below, with the printout I expected, but it then also prints out "None" nine times. How does that work? Jim #Using Python 3.3.2 on Win 7 - standard project, standard test file def addone(num): if num > 10: return num num = addone(num + 1) print(addone(1)) Result: 11 None None None None None None None None None -- Jim "Would you use Internet Explorer if someone put a gun to your head?" "How big is the gun?" From breamoreboy at yahoo.co.uk Sun Jun 9 00:02:24 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 08 Jun 2013 23:02:24 +0100 Subject: [Tutor] recursion surprise In-Reply-To: References: Message-ID: On 08/06/2013 22:46, Jim Mooney wrote: > I was trying out simple recursion as below, with the printout I > expected, but it then also prints out "None" nine times. How does that > work? > > Jim > > #Using Python 3.3.2 on Win 7 - standard project, standard test file > > def addone(num): > if num > 10: > return num > num = addone(num + 1) return None #Python puts the default return here as you don't specify it. > > print(addone(1)) > > Result: > 11 > None > None > None > None > None > None > None > None > None > > -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From thomasmurphymusic at gmail.com Sun Jun 9 00:05:12 2013 From: thomasmurphymusic at gmail.com (Thomas Murphy) Date: Sat, 8 Jun 2013 18:05:12 -0400 Subject: [Tutor] recursion surprise In-Reply-To: References: Message-ID: Hi Jim, First off, I'm a beginner, so I offer this with humility, but are you sure you wanted a > then sign? It looks to me like you want to loop through and print each number while num is less than 10 right? I went with this, using while loop instead: def addOne(num): while num < 10: print num num = num + 1 addOne(1) On Sat, Jun 8, 2013 at 5:46 PM, Jim Mooney wrote: > I was trying out simple recursion as below, with the printout I > expected, but it then also prints out "None" nine times. How does that > work? > > Jim > > #Using Python 3.3.2 on Win 7 - standard project, standard test file > > def addone(num): > if num > 10: > return num > num = addone(num + 1) > > print(addone(1)) > > Result: > 11 > None > None > None > None > None > None > None > None > None > > > -- > Jim > "Would you use Internet Explorer if someone put a gun to your head?" > "How big is the gun?" > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Sincerely, Thomas Murphy Code Ninja 646.957.6115 From michaelsparks37 at gmail.com Sun Jun 9 00:10:49 2013 From: michaelsparks37 at gmail.com (Michael Sparks) Date: Sat, 8 Jun 2013 15:10:49 -0700 Subject: [Tutor] How does formatted printing work? In-Reply-To: <51B3720A.5010607@pearwood.info> References: <51B3720A.5010607@pearwood.info> Message-ID: I believe it's % string interpolation where % formats strings I'm reading Practical Programming and I'm stuck on page 35, question 6. b) where: "___" % 34.5 => "3.45e+01" On Sat, Jun 8, 2013 at 11:03 AM, Steven D'Aprano wrote: > On 09/06/13 01:58, Michael Sparks wrote: > >> You can explain it yourself or just drop me a link (or both). >> Right now I'm learning Python 2.x but I plan on learning Python 3.x as >> well. >> > > > Formatted printing? First you format something, then you print it. > > Other than that, you will need to explain your question in more detail. I > can't read your mind, so I don't know if you're having trouble > understanding "formatting" (which formatting? there are at least four > things which might be described as "formatting") or "printing" (which > printing? there are at least three things which might be described as > "printing"). > > So please don't assume that just because a question is clear and obvious > in your mind, it is necessarily clear and obvious to everyone else. > > > And for the record: > > 1) format() built-in function; > 2) str.format() method; > 3) % string interpolation; > 4) string templates; > > and > > 1) printing to an actual printer; > 2) print statement; > 3) the pprint ("pretty printing") module. > > > > -- > Steven > > ______________________________**_________________ > 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 cybervigilante at gmail.com Sun Jun 9 00:31:40 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 8 Jun 2013 15:31:40 -0700 Subject: [Tutor] recursion surprise In-Reply-To: References: Message-ID: On 8 June 2013 15:02, Mark Lawrence wrote: > return None #Python puts the default return here as you don't specify > it. I wasn't quite sure where to put that 'return None' since it wasn't aligned, so I tried a few different ways, did the below and it worked. Is that what you meant or am I still confused ;') #Using Python 3.3.2 on Win 7 - standard project, standard test file def addone(num): if num > 10: return num num = addone(num + 1) if num != None: print(num) addone(1) result: 11 From cybervigilante at gmail.com Sun Jun 9 00:38:18 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 8 Jun 2013 15:38:18 -0700 Subject: [Tutor] recursion surprise In-Reply-To: References: Message-ID: On 8 June 2013 15:05, Thomas Murphy wrote: > Hi Jim, > > First off, I'm a beginner, so I offer this with humility, but are you > sure you wanted a > then sign? Thanks. I'm a beginner myself, but yes, I meant to do that. I get bored with my Lutz book, which is very long and detailed, so now and then I look ahead and try out things I don't quite fathom, if they interest me ;') But that is what I thought I meant to do, not a loop. Jim -- From davea at davea.name Sun Jun 9 00:43:03 2013 From: davea at davea.name (Dave Angel) Date: Sat, 08 Jun 2013 18:43:03 -0400 Subject: [Tutor] recursion surprise In-Reply-To: References: Message-ID: <51B3B377.4000602@davea.name> On 06/08/2013 05:46 PM, Jim Mooney wrote: > I was trying out simple recursion as below, with the printout I > expected, but it then also prints out "None" nine times. How does that > work? > > Jim > > #Using Python 3.3.2 on Win 7 - standard project, standard test file > > def addone(num): > if num > 10: > return num > num = addone(num + 1) > > print(addone(1)) > > Result: > 11 > None > None > None > None > None > None > None > None > None > > Post the same code that you ran, to get that output. Otherwise you're wasting our time. Your function is missing a return statement, presumably you meant to return num, and presumably that would be directly after you assign to num. Since you don't have a return statement, when the function falls off the end, it returns None. So this is how your function currently looks (before you fix it) def addone(num): if num > 10: return num num = addone(num + 1) return None -- DaveA From breamoreboy at yahoo.co.uk Sun Jun 9 00:46:40 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 08 Jun 2013 23:46:40 +0100 Subject: [Tutor] recursion surprise In-Reply-To: References: Message-ID: On 08/06/2013 23:31, Jim Mooney wrote: > On 8 June 2013 15:02, Mark Lawrence wrote: > >> return None #Python puts the default return here as you don't specify >> it. > > I wasn't quite sure where to put that 'return None' since it wasn't > aligned, so I tried a few different ways, did the below and it worked. > Is that what you meant or am I still confused ;') > There's only one place it can go, it should have been aligned directly under "num = addone(num + 1)". Shift it to the left or right gives you a syntax error. -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From davea at davea.name Sun Jun 9 00:47:35 2013 From: davea at davea.name (Dave Angel) Date: Sat, 08 Jun 2013 18:47:35 -0400 Subject: [Tutor] recursion surprise In-Reply-To: References: Message-ID: <51B3B487.9010407@davea.name> On 06/08/2013 06:38 PM, Jim Mooney wrote: > On 8 June 2013 15:05, Thomas Murphy wrote: >> Hi Jim, >> >> First off, I'm a beginner, so I offer this with humility, but are you >> sure you wanted a > then sign? > > Thanks. I'm a beginner myself, but yes, I meant to do that. Your description mentions recursion, while Thomas's code has no such thing. So if that's what you intended, you were way off target. > I get > bored with my Lutz book, which is very long and detailed, so now and > then I look ahead and try out things I don't quite fathom, if they > interest me ;') But that is what I thought I meant to do, not a loop. And yet Thomas version uses a loop, while yours uses recursion, not a loop. -- DaveA From davea at davea.name Sun Jun 9 01:02:27 2013 From: davea at davea.name (Dave Angel) Date: Sat, 08 Jun 2013 19:02:27 -0400 Subject: [Tutor] How does formatted printing work? In-Reply-To: References: <51B3720A.5010607@pearwood.info> Message-ID: <51B3B803.9090904@davea.name> On 06/08/2013 06:10 PM, Michael Sparks wrote: > I believe it's % string interpolation where % formats strings > I'm reading Practical Programming and I'm stuck on page 35, question 6. b) > where: > "___" % 34.5 => "3.45e+01" > > By top-posting, you ruined all context. For Python 2.x, here's the documentation link for string interpolation using the "%" operator. http://docs.python.org/2/library/stdtypes.html#string-formatting-operations -- DaveA From cybervigilante at gmail.com Sun Jun 9 01:12:33 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 8 Jun 2013 16:12:33 -0700 Subject: [Tutor] recursion surprise In-Reply-To: <51B3B377.4000602@davea.name> References: <51B3B377.4000602@davea.name> Message-ID: On 8 June 2013 15:43, Dave Angel wrote: > On 06/08/2013 05:46 PM, Jim Mooney wrote: > Post the same code that you ran, to get that output. Otherwise you're > wasting our time. Okay, here it is not working a different way, copied exactly, but it looks like I do have a return statement, and that it should be returning 11, not None. I must be missing something in my understanding: def addone(num): if num > 10: return num num = addone(num + 1) print(addone(1)) result: >>> None >>> From mnickey at gmail.com Sun Jun 9 01:44:29 2013 From: mnickey at gmail.com (Mike Nickey) Date: Sat, 8 Jun 2013 16:44:29 -0700 Subject: [Tutor] Splitting on punctuation Message-ID: Hey guys, I'm working on a web-project simply to bruh up on skills and build new ones. One of the tasks is to split on punctuation passed yet I'm having a bit more trouble then I expected. Give the input of "which isn't that surprising I guess.",",'.") where the first part passed is the string and the second part is the punctuation to split on, I'm having difficulty converting the punctuation to a split parameter. As you'll see I have tried various attempts at replace, strip and split but I can't seem to get it just right. Currently I have the following: import string def tokenize_query(query, punctuation): # informational and to be removed print 'Query passed: ', query print 'Punctuation passed:' , punctuation print '-----------------------' punc = punctuation query = query.replace(punc," ") words = query.split() for item in words: item = item.replace(punc,' ') # item = item.rstrip(punctuation) # item = item.replace(punctuation,"") print item tokenize_query("Dynamic programming string processing algorithms","") print tokenize_query("The quick! bro'wn fox! runs slowly$",",$'") print tokenize_query("which isn't that surprising I guess.",",'.") The output I get is: Query passed: which isn't that surprising I guess. Punctuation passed: ,'. ----------------------- which isn't that surprising I guess. What I should have is: Query passed: which isn't that surprising I guess. Punctuation passed: ,'. ----------------------- which isn t that surprising I guess Any suggestions? and thanks in advance. -- ~MEN -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Sun Jun 9 01:46:38 2013 From: davea at davea.name (Dave Angel) Date: Sat, 08 Jun 2013 19:46:38 -0400 Subject: [Tutor] recursion surprise In-Reply-To: References: <51B3B377.4000602@davea.name> Message-ID: <51B3C25E.30800@davea.name> On 06/08/2013 07:12 PM, Jim Mooney wrote: > On 8 June 2013 15:43, Dave Angel wrote: >> On 06/08/2013 05:46 PM, Jim Mooney wrote: > >> Post the same code that you ran, to get that output. Otherwise you're >> wasting our time. > > Okay, here it is not working a different way, copied exactly, but it > looks like I do have a return statement, and that it should be > returning 11, not None. I must be missing something in my > understanding: > > def addone(num): > if num > 10: > return num > num = addone(num + 1) > > print(addone(1)) > > result: >>>> > None >>>> > > Did you even read my message? Or Mark's? Or look at the code I posted? You are missing a return statement at the end of the function, so after the assignment num=addone(num+1) it will return None, by definition. -- DaveA From cybervigilante at gmail.com Sun Jun 9 01:52:18 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 8 Jun 2013 16:52:18 -0700 Subject: [Tutor] recursion surprise In-Reply-To: <51B3C25E.30800@davea.name> References: <51B3B377.4000602@davea.name> <51B3C25E.30800@davea.name> Message-ID: On 8 June 2013 16:46, Dave Angel wrote: > On 06/08/2013 07:12 PM, Jim Mooney wrote: >> >> On 8 June 2013 15:43, Dave Angel wrote: > Did you even read my message? Or Mark's? Or look at the code I posted? > You are missing a return statement at the end of the function, so after the > assignment num=addone(num+1) it will return None, by definition. Well, I thought if num > 10: return num Was a return statement. Num does become > 10. You mean I need more than one? Jim From marc.tompkins at gmail.com Sun Jun 9 02:15:17 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 8 Jun 2013 17:15:17 -0700 Subject: [Tutor] recursion surprise In-Reply-To: References: <51B3B377.4000602@davea.name> <51B3C25E.30800@davea.name> Message-ID: On Sat, Jun 8, 2013 at 4:52 PM, Jim Mooney wrote: > Well, I thought > > if num > 10: > return num > > Was a return statement. Num does become > 10. You mean I need more than > one? > It is, and you actually have more than one. All functions return None, unless you explicitly specify a return value (via a return statement). Whenever your execution path does NOT go through your return statement - in other words, if num is NOT greater than 10 - execution falls off the end and the function returns None. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dfjennings at gmail.com Sun Jun 9 02:10:24 2013 From: dfjennings at gmail.com (Don Jennings) Date: Sat, 8 Jun 2013 20:10:24 -0400 Subject: [Tutor] recursion surprise In-Reply-To: References: <51B3B377.4000602@davea.name> <51B3C25E.30800@davea.name> Message-ID: On Jun 8, 2013, at 7:52 PM, Jim Mooney wrote: > On 8 June 2013 16:46, Dave Angel wrote: >> On 06/08/2013 07:12 PM, Jim Mooney wrote: >>> >>> On 8 June 2013 15:43, Dave Angel wrote: >> Did you even read my message? Or Mark's? Or look at the code I posted? >> You are missing a return statement at the end of the function, so after the >> assignment num=addone(num+1) it will return None, by definition. > > Well, I thought > > if num > 10: > return num > > Was a return statement. Num does become > 10. You mean I need more than one? Yes, you do need more than one. Let's walk through your code so you understand what's happening. However, I'll take the liberty of changing the if test so we go through only one level of recursion. def addone(num): if num > 1: return num num = addone(num + 1) print(addone(1)) So, what happens on the first call? addone(num) # num is the name for the value 1 if num > 1: # num is not greater than one; there's no loop, so this check never happens again return num # skip this line num = addone(num + 1) # recursive call --> | addone(num) # num is now 2, right? | if num > 1: # why, yes it is | return num # passes back 2 As Dave pointed out, the function ends, and implicitly returns None since you didn't tell it to return anything else. Does that help? Take care, Don From davea at davea.name Sun Jun 9 02:21:55 2013 From: davea at davea.name (Dave Angel) Date: Sat, 08 Jun 2013 20:21:55 -0400 Subject: [Tutor] Splitting on punctuation In-Reply-To: References: Message-ID: <51B3CAA3.40708@davea.name> On 06/08/2013 07:44 PM, Mike Nickey wrote: > Hey guys, > > I'm working on a web-project simply to bruh up on skills and build new > ones. > One of the tasks is to split on punctuation passed yet I'm having a bit > more trouble then I expected. > > Give the input of "which isn't that surprising I guess.",",'.") where the > first part passed is the string and the second part is the punctuation to > split on, I'm having difficulty converting the punctuation to a split > parameter. > > As you'll see I have tried various attempts at replace, strip and split but > I can't seem to get it just right. > There's a lot here that's irrelevant to the problem you're describing. > Currently I have the following: > import string Why? You don't use it. > def tokenize_query(query, punctuation): > # informational and to be removed > print 'Query passed: ', query > print 'Punctuation passed:' , punctuation > print '-----------------------' > punc = punctuation > query = query.replace(punc," ") That's enough. Just print it and be done. Try just reading about the replace method itself. http://docs.python.org/2/library/string.html#deprecated-string-functions "Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced." You're trying to use a string as though it were a list of characters, while replace is using it as a substring. Try it with something simple in Python 2.7: >>> print "abc cba".replace("ca", "*") abc cba >>> print "abc cba".replace("cb", "*") abc *a >>> Probably the simplest way to do it is to write a for loop over all the punctuation characters, replacing each of them in turn with a space. -- DaveA From cybervigilante at gmail.com Sun Jun 9 02:25:41 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 8 Jun 2013 17:25:41 -0700 Subject: [Tutor] recursion surprise In-Reply-To: References: <51B3B377.4000602@davea.name> <51B3C25E.30800@davea.name> Message-ID: On 8 June 2013 17:10, Don Jennings wrote: As Dave pointed out, the function ends, and implicitly returns None since you didn't tell it to return anything else. Does that help? > > Take care, > Don > Yes, I see it now. My return num just returned to the previous function call, but I need a final return to return to print. I was probably misremembering something from javascript when I was just hacking it in as needed, when I was webmastering. -- Jim From davea at davea.name Sun Jun 9 02:28:17 2013 From: davea at davea.name (Dave Angel) Date: Sat, 08 Jun 2013 20:28:17 -0400 Subject: [Tutor] recursion surprise In-Reply-To: References: <51B3B377.4000602@davea.name> <51B3C25E.30800@davea.name> Message-ID: <51B3CC21.9030307@davea.name> On 06/08/2013 07:52 PM, Jim Mooney wrote: > On 8 June 2013 16:46, Dave Angel wrote: >> On 06/08/2013 07:12 PM, Jim Mooney wrote: >>> >>> On 8 June 2013 15:43, Dave Angel wrote: >> Did you even read my message? Or Mark's? Or look at the code I posted? >> You are missing a return statement at the end of the function, so after the >> assignment num=addone(num+1) it will return None, by definition. > > Well, I thought > > if num > 10: > return num > > Was a return statement. Num does become > 10. You mean I need more than one? > > Jim > > Since your function has more than one return point, you need more than one return statement, or you'll wind up with the default one, which is None. Try a simpler function, and see if you can get it straight. def newfunc(x): if x > 5: return x+20 else: pass # return x+100 What would you expect it to return for x <= 5. Without the extra return statement, it's going to return None. Test it for yourself: print newfunc(7) print newfunc(3) By the way, the empty return statement also returns None. -- DaveA From davea at davea.name Sun Jun 9 02:30:27 2013 From: davea at davea.name (Dave Angel) Date: Sat, 08 Jun 2013 20:30:27 -0400 Subject: [Tutor] recursion surprise In-Reply-To: References: <51B3B377.4000602@davea.name> <51B3C25E.30800@davea.name> Message-ID: <51B3CCA3.4060906@davea.name> On 06/08/2013 07:52 PM, Jim Mooney wrote: > On 8 June 2013 16:46, Dave Angel wrote: >> On 06/08/2013 07:12 PM, Jim Mooney wrote: >>> >>> On 8 June 2013 15:43, Dave Angel wrote: >> Did you even read my message? Or Mark's? Or look at the code I posted? >> You are missing a return statement at the end of the function, so after the >> assignment num=addone(num+1) it will return None, by definition. > > Well, I thought > > if num > 10: > return num > > Was a return statement. Num does become > 10. You mean I need more than one? > > Jim > > Since your function has more than one return point, you need more than one return statement, or you'll wind up with the default one, which is None. Try a simpler function, and see if you can get it straight. def newfunc(x): if x > 5: return x+20 else: pass # return x+100 What would you expect it to return for x <= 5. Without the extra return statement, it's going to return None. Test it for yourself: print newfunc(7) print newfunc(3) By the way, an empty return statement also returns None. -- DaveA From steve at pearwood.info Sun Jun 9 03:08:00 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 09 Jun 2013 11:08:00 +1000 Subject: [Tutor] recursion surprise In-Reply-To: References: <51B3B377.4000602@davea.name> Message-ID: <51B3D570.2010909@pearwood.info> On 09/06/13 09:12, Jim Mooney wrote: > Okay, here it is not working a different way, copied exactly, but it > looks like I do have a return statement, and that it should be > returning 11, not None. I must be missing something in my > understanding: > > def addone(num): > if num > 10: > return num > num = addone(num + 1) Follow the code in your head. Suppose you pass 20 as the argument: 1st call to addone: num = 20 "if num > 10" is true, so: "return num" returns 20 And we are done. There's no more code to run, because "return" exits the function and there are no more function calls queued up. So far so good. Now, try again, this time with 10 as the argument: 1st call to addone: num = 10 "if num > 10" is false, so the return line is skipped num = addone(num + 1) At this point, the function pauses, and waits for a result from "addone(num + 1)". So we make a recursive call to find out what the result of addone(11) is: => 2nd call to addone: num = 10+1 = 11 "if num > 10" is false, so: "return num" returns 11 => back to the paused 1st call to addone num = addone(num + 1) receives the result 11, so: num = 11 At this point, we hit the end of the function. There's no more code to run, and no return statement, so Python automatically returns None. And we're done. addone(10) returns None, not 11 as you hoped. This might be easier to understand if you drop the recursion, and just use some other calculation: def simple_addone(num): if num > 10: return num num = num + 1 If you look at simple_addone, it hopefully will be obvious that there are two cases, e.g.: * simple_addone(20) will return 20 * simple_addone(10) will calculate num = 11, but not do anything with it, and then return None when execution "drops out the bottom" of the function code. Here's another example: let's make a second function to perform the addition: def add(a, b): print("adding numbers like a Boss") return a+b def simple_addone(num): if num > 10: return num num = add(num, 1) The situation is exactly the same. If num starts off > 10, the return statement is reached, and num is returned. But if num starts off <= 10, the return statement is skipped, num is recalculated, but nothing is done with the new result, and None is returned. Nothing significant changes when you replace the expression num+1 with a call to a function add(num, 1), and likewise nothing significant happens when you replace the call to add() with a recursive call to addone(n+1). The return statement is skipped, you drop out the bottom of the outermost call to addone, and None is returned. Is this enough information for you to fix it? -- Steven From cybervigilante at gmail.com Sun Jun 9 03:18:37 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 8 Jun 2013 18:18:37 -0700 Subject: [Tutor] recursion surprise In-Reply-To: <51B3D570.2010909@pearwood.info> References: <51B3B377.4000602@davea.name> <51B3D570.2010909@pearwood.info> Message-ID: On 8 June 2013 18:08, Steven D'Aprano wrote: > Is this enough information for you to fix it? Yes, I was tripping over myself. Once I simplified it, it became clear: def addone(n): if n > 5: return n return addone(n + 1) result: 6 -- Jim From steve at pearwood.info Sun Jun 9 03:45:32 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 09 Jun 2013 11:45:32 +1000 Subject: [Tutor] recursion surprise In-Reply-To: References: <51B3B377.4000602@davea.name> <51B3D570.2010909@pearwood.info> Message-ID: <51B3DE3C.7060803@pearwood.info> On 09/06/13 11:18, Jim Mooney wrote: > On 8 June 2013 18:08, Steven D'Aprano wrote: > >> Is this enough information for you to fix it? > > Yes, I was tripping over myself. Once I simplified it, it became clear: > > def addone(n): > if n > 5: > return n > return addone(n + 1) > > result: 6 By George, I think you've got it! :-) Recursion is one of the more difficult computer science concepts for people to grasp. I don't remember the reference, but I think I read somewhere that something like 50% of professional programmers never understand recursion. Admittedly, most of them are VB or PHP code monkeys, where the standards for "professionalism" can be quite low, but still. -- Steven From cybervigilante at gmail.com Sun Jun 9 03:56:12 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 8 Jun 2013 18:56:12 -0700 Subject: [Tutor] recursion surprise In-Reply-To: <51B3DE3C.7060803@pearwood.info> References: <51B3B377.4000602@davea.name> <51B3D570.2010909@pearwood.info> <51B3DE3C.7060803@pearwood.info> Message-ID: On 8 June 2013 18:45, Steven D'Aprano wrote: > By George, I think you've got it! Well, for simple stuff. I'm now trying more complicated stuff and getting "maximum recursion depth exceeded" but that will give me fun running progs and figuring it out all night, now that I see the basics. I have to do something with my time. I don't intend to: Be Retired >> Watch TV >> Play Shuffleboard >> Complain a lot >> Brain rots. Actually, I threw my TV out the window (literally) a number of years ago. Jim From jacklittlemc at yahoo.com Sun Jun 9 04:08:11 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Sat, 8 Jun 2013 19:08:11 -0700 (PDT) Subject: [Tutor] Compilation Error Message-ID: <1370743691.31787.YahooMailNeo@web124501.mail.ne1.yahoo.com> 1. I compiled a script withpy2exe.I have the .exe ,but when I run it,the window just closes itself.Inthe cmd window fromwhich I compiled the script from,Itsays some dlls are needed.Whatdoes this this have to dowithit,andmore importantly,isthere any solution? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Jun 9 06:37:34 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 09 Jun 2013 14:37:34 +1000 Subject: [Tutor] Compilation Error In-Reply-To: <1370743691.31787.YahooMailNeo@web124501.mail.ne1.yahoo.com> References: <1370743691.31787.YahooMailNeo@web124501.mail.ne1.yahoo.com> Message-ID: <51B4068E.5090200@pearwood.info> On 09/06/13 12:08, Jack Little wrote: > 1. I compiled a script withpy2exe.I have the .exe ,but when I run it,the window just closes itself.Inthe cmd window fromwhich I compiled the script from,Itsays some dlls are needed.Whatdoes this this have to dowithit,andmore importantly,isthere any solution? Is the spacebar broken on your computer? You should get a new keyboard. Also, guessing games are lots of fun when you're five, but not so much as an adult. At the moment, we have to guess what error message you are getting, what DLLs are missing, and therefore what you need to do to fix this. Please don't make us guess, show us the EXACT error message, copied and pasted from the cmd window. Don't retype it from memory, summarize it, simplify it, or paraphrase it. Copy and paste the exact wording. I would expect that, yes, of course there is a solution. You need to provide the DLLs that py2exe just told you it needs. As for why, DLLs are software libraries. Think of them as being equivalent to Python modules, except written in some other language like C. If your script says: import math print math.sin(1.25) then your script will not work without the math module. The same applies to py2exe: somewhere in it's code, it relies on one or more DLLs, and if those DLLs cannot be found, it wouldn't work. -- Steven From steve at pearwood.info Sun Jun 9 06:54:03 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 09 Jun 2013 14:54:03 +1000 Subject: [Tutor] How does formatted printing work? In-Reply-To: References: <51B3720A.5010607@pearwood.info> Message-ID: <51B40A6B.7080806@pearwood.info> On 09/06/13 08:10, Michael Sparks wrote: > I believe it's % string interpolation where % formats strings > I'm reading Practical Programming and I'm stuck on page 35, question 6. b) > where: > "___" % 34.5 => "3.45e+01" Okay, this has nothing to do with printing. % string interpolation is independent of printing. It just creates a new string, which you can store in a variable: new_str = old_str % 34.5 Of course, you can print the string if you want to, but you don't have to. % string interpolation is based very closely on the same thing from the C programming language. It is based on "%" being a "magic character" -- when you call some_string % one_or_more_arguments Python will search some_string for codes starting with % and replace them with values from the given arguments. The simplest code is %s which just inserts the value converted to a string: py> print( "value = [%s]" % 22.5 ) value = [22.5] Anything outside of the % codes remains unchanged. There's not a lot to see there. %s formatting is pretty trivial. But we can start to see more of the power when you provide extra fields, like width: py> print( "value = [%8s]" % 22.5 ) value = [ 22.5] There are other codes. As well as %s that simply turns any value into a string, there are also: %d value must be an integer %x integer displayed as hexadecimal, using lowercase a...f %X integer displayed as hexadecimal, using uppercase A...F %f value is displayed as a floating point number %g like %f, but with slightly different display %G like %f and %g, but with yet another display and others. You can read all about it here: http://docs.python.org/2/library/stdtypes.html#string-formatting-operations Does that help? If you have any further concrete questions, please ask. -- Steven From msg.ufo at gmail.com Sun Jun 9 07:18:04 2013 From: msg.ufo at gmail.com (Mike G) Date: Sat, 8 Jun 2013 22:18:04 -0700 Subject: [Tutor] Compilation Error Message-ID: ...> Jack Little jacklittlemc at yahoo.com ...> Sun Jun 9 04:08:11 CEST 2013 ...> 1. I compiled a script with py2exe. I have the .exe, but when I run it, the window just closes ...> itself. In the cmd window from which I compiled the script from, It says some dlls are ...> needed. What does this this have to do with it, and more importantly, is there any solution? You likely are missing the needed runtime, read here. ... http://www.py2exe.org/index.cgi/Tutorial The flashing screen could be the code, console app versus gui, not sure, can't read invisible ink, sorry. From alan.gauld at btinternet.com Sun Jun 9 07:44:32 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 09 Jun 2013 06:44:32 +0100 Subject: [Tutor] recursion surprise In-Reply-To: References: <51B3B377.4000602@davea.name> <51B3D570.2010909@pearwood.info> <51B3DE3C.7060803@pearwood.info> Message-ID: On 09/06/13 02:56, Jim Mooney wrote: > Well, for simple stuff. I'm now trying more complicated stuff and > getting "maximum recursion depth exceeded" but that will give me fun One of the snags with recursion in Python (and several other languages) is that there is an arbitrary limit on how often you can recurse. This is one (of several) reasons why recursion should be used in moderation in real-world problems. The good news is that 1) recursion can lead to simple and elegant solutions 2) recursion can always be unwrapped into traditional loops This means you can use recursion to discover the pure solution then unwrap the recursion to get an industrial strength (but ugly) solution that works. Finally note that some languages (notably Lisp dialects) are designed to use recursion and have specific mechanisms to get round the limitations found in Python etc. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Jun 9 07:48:13 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 09 Jun 2013 06:48:13 +0100 Subject: [Tutor] Splitting on punctuation In-Reply-To: References: Message-ID: On 09/06/13 00:44, Mike Nickey wrote: > One of the tasks is to split on punctuation passed yet I'm having a bit > more trouble then I expected. You do realize that split() can do that for you? Its not limited to splitting on whitespace? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jacklittlemc at yahoo.com Sun Jun 9 13:20:35 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Sun, 9 Jun 2013 04:20:35 -0700 (PDT) Subject: [Tutor] PyInstaller Message-ID: <1370776835.62111.YahooMailNeo@web124502.mail.ne1.yahoo.com> I am using PyInstaller now for building, but I still have a problem! My error is as follows: Traceback (most recent call last): File C:/Users/Jack/Desktop/pyinstaller-pyinstaller-61571d6/PyInstaller/Build.py ?from PyInstaller.loader import pyi_archive, pyi_carchive ImportError: cannot import name pyi_archive Please help! I am very frustrated with no way to compile my scripts! -------------- next part -------------- An HTML attachment was scrubbed... URL: From andipersti at gmail.com Sun Jun 9 14:55:45 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Sun, 09 Jun 2013 14:55:45 +0200 Subject: [Tutor] PyInstaller In-Reply-To: <1370776835.62111.YahooMailNeo@web124502.mail.ne1.yahoo.com> References: <1370776835.62111.YahooMailNeo@web124502.mail.ne1.yahoo.com> Message-ID: <51B47B51.1050704@gmail.com> On 09.06.2013 13:20, Jack Little wrote: > I am using PyInstaller now for building, but I still have a problem! My error is as follows: > > Traceback (most recent call last): > File C:/Users/Jack/Desktop/pyinstaller-pyinstaller-61571d6/PyInstaller/Build.py > from PyInstaller.loader import pyi_archive, pyi_carchive > ImportError: cannot import name pyi_archive It looks like PyInstaller has an active mailing-list: http://www.pyinstaller.org/#MailingList You should ask your questions there. Bye, Andreas From oscar.j.benjamin at gmail.com Sun Jun 9 16:26:32 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 9 Jun 2013 15:26:32 +0100 Subject: [Tutor] three numbers for one In-Reply-To: References: Message-ID: On 8 June 2013 06:49, eryksun wrote: > On Fri, Jun 7, 2013 at 11:11 PM, Jim Mooney wrote: >> I'm puzzling out the difference between isdigit, isdecimal, and >> isnumeric. But at this point, for simple practice programs, which is >> the best to use for plain old 0123456589 , without special characters? > > The isnumeric, isdigit, and isdecimal predicates use Unicode character > properties that are defined in UnicodeData.txt: > > http://www.unicode.org/Public/6.1.0/ucd > > The most restrictive of the 3 is isdecimal. If a string isdecimal(), > you can convert it with int() -- even if you're mixing scripts: > > >>> unicodedata.name('\u06f0') > 'EXTENDED ARABIC-INDIC DIGIT ZERO' > >>> unicodedata.decimal('\u06f0') > 0 > >>> '1234\u06f0'.isdecimal() > True > >>> int('1234\u06f0') > 12340 I didn't know about this. In the time since this thread started a parallel thread has emerged on python-ideas and it seems that Guido was unaware of these changes in Python 3: http://mail.python.org/pipermail/python-ideas/2013-June/021216.html I don't think I like this behaviour: I don't mind the isdigit, isdecimal and isnumeric methods but I don't want int() to accept non-ascii characters. This is a reasonable addition to the unicodedata module but should not happen when simply calling int(). To answer Jim's original question, there doesn't seem to be a function to check for only plain old 0-9 but you can make your own easily enough: >>> def is_ascii_digit(string): ... return not (set(string) - set('0123456789')) ... >>> is_ascii_digit('qwe') False >>> is_ascii_digit('0123') True >>> is_ascii_digit('0123f') False An alternative method depending on where your strings are actually coming from would be to use byte-strings or the ascii codec. I may consider doing this in future; in my own applications if I pass a non-ascii digit to int() then I definitely have data corruption. Then again it's unlikely that the corruption would manifest itself in precisely this way since only a small proportion of non-ascii unicode characters would be accepted by int(). Oscar From steve at pearwood.info Sun Jun 9 17:22:43 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Jun 2013 01:22:43 +1000 Subject: [Tutor] three numbers for one In-Reply-To: References: Message-ID: <51B49DC3.1090003@pearwood.info> On 10/06/13 00:26, Oscar Benjamin wrote: > On 8 June 2013 06:49, eryksun wrote: >> On Fri, Jun 7, 2013 at 11:11 PM, Jim Mooney wrote: >>> I'm puzzling out the difference between isdigit, isdecimal, and >>> isnumeric. But at this point, for simple practice programs, which is >>> the best to use for plain old 0123456589 , without special characters? >> >> The isnumeric, isdigit, and isdecimal predicates use Unicode character >> properties that are defined in UnicodeData.txt: >> >> http://www.unicode.org/Public/6.1.0/ucd >> >> The most restrictive of the 3 is isdecimal. If a string isdecimal(), >> you can convert it with int() -- even if you're mixing scripts: >> >> >>> unicodedata.name('\u06f0') >> 'EXTENDED ARABIC-INDIC DIGIT ZERO' >> >>> unicodedata.decimal('\u06f0') >> 0 >> >>> '1234\u06f0'.isdecimal() >> True >> >>> int('1234\u06f0') >> 12340 > > I didn't know about this. In the time since this thread started a > parallel thread has emerged on python-ideas and it seems that Guido > was unaware of these changes in Python 3: Python is a pretty big language (although not as big as, say, Java). Nobody knows every last feature in the language and standard library, and by Guido's own admission, he's pretty much stuck in the ASCII-only world. > http://mail.python.org/pipermail/python-ideas/2013-June/021216.html > > I don't think I like this behaviour: I don't mind the isdigit, > isdecimal and isnumeric methods but I don't want int() to accept > non-ascii characters. This is a reasonable addition to the unicodedata > module but should not happen when simply calling int(). Why not? What problem do you see? Decimal digits are perfectly well defined. There is no ambiguity in what counts as a decimal digit and what doesn't. > To answer Jim's original question, there doesn't seem to be a function > to check for only plain old 0-9 Why would you want to? For no extra effort, you can handle numbers written in just about any language. You get this for free. Why would you want to work *harder* in order to be *less useful*? > but you can make your own easily enough: > >>>> def is_ascii_digit(string): > ... return not (set(string) - set('0123456789')) That's buggy, because it claims that '' is an ascii digit. This is likely to be quicker, if not for small strings at least for large strings: def is_ascii_digit(string): return string and all(c in set('0123456789') for c in string) > An alternative method depending on where your strings are actually > coming from would be to use byte-strings or the ascii codec. I may > consider doing this in future; in my own applications if I pass a > non-ascii digit to int() then I definitely have data corruption. It's not up to built-ins like int() to protect you from data corruption. Would you consider it reasonable for me to say "in my own applications, if I pass a number bigger than 100, I definitely have data corruption, therefore int() should not support numbers bigger than 100"? > Then > again it's unlikely that the corruption would manifest itself in > precisely this way since only a small proportion of non-ascii unicode > characters would be accepted by int(). Indeed :-) -- Steven From colincclayton at gmail.com Sun Jun 9 20:56:29 2013 From: colincclayton at gmail.com (Colin Clayton) Date: Sun, 9 Jun 2013 11:56:29 -0700 Subject: [Tutor] Question regarding the 'chr' function Message-ID: Hi everyone, I am fairly new to the Python language and have come from a background of Google's App Inventor Block Language. I'm having trouble understanding what the 'chr' function does? I have yet to find a tutorial or information online relating to the 'chr' function that really clicks with me. If I want to make an AsciiChart function that returns a string that is an AsciiChart using the 'chr' function how would I do this? I don't expect or need code as an answer, I'm really just looking for an explanation of the possible logic. Please let me know if you have any ideas. Thanks! -Colin -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jun 9 21:21:01 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 09 Jun 2013 20:21:01 +0100 Subject: [Tutor] Question regarding the 'chr' function In-Reply-To: References: Message-ID: On 09/06/13 19:56, Colin Clayton wrote: > really clicks with me. If I want to make an AsciiChart function that > returns a string that is an AsciiChart using the 'chr' function how Since you are obviously aware that character symbols are stored on the computer as numeric codes then the explanation of chr() is that given a numeric code it returns the character symbol. So to generate an ASCII table you print the list of codes and their corresponding symbol. You get the symbol by applying chr() to the codes. You can go the other way by using ord() which takes a symbol and returns the code. Try: >>> print( chr(65) ) >>> print( ord('A') ) and other samples to see it in effect. In Python chr()/ord() works with the chosen character set not just simple ASCII... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cybervigilante at gmail.com Mon Jun 10 02:57:56 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 9 Jun 2013 17:57:56 -0700 Subject: [Tutor] Am I missing something on module pyversions? Message-ID: I look at modules online and sometimes it's clear if they're for Py 2.7 or Py3.3, usually in Requirements. Or if not, it's literally on the download package, which will actually have 2.7 or 3.3 in the zip or tar name. But on some sites it's totally unclear. They don't say it at all up-front. I'll hunt around and still can't find it. Is there some standard I'm just overlooking that definitively says which Py version a module is for? Or something in the module package itself? I'm surprised this isn't a real up-front item. Or do I have to search, guess, and download to find out? -- Jim Today is the day that would have been tomorrow if yesterday was today From cybervigilante at gmail.com Mon Jun 10 04:51:34 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 9 Jun 2013 19:51:34 -0700 Subject: [Tutor] three numbers for one In-Reply-To: <51B49DC3.1090003@pearwood.info> References: <51B49DC3.1090003@pearwood.info> Message-ID: On 9 June 2013 08:22, Steven D'Aprano wrote: > On 10/06/13 00:26, Oscar Benjamin wrote: >> >> On 8 June 2013 06:49, eryksun wrote: >>>>> def is_ascii_digit(string): >> >> ... return not (set(string) - set('0123456789')) Darn, here I thought sets were kind of useless, and some sources hint as much so I filed them away as forgettable, but I see now that they can be a real time saver. I wrote a seven line module that tested raw numbers or strings as simple ints, but using sets cuts it to two for both numbers and numeric strings, and also checking False on the empty string. I'll have to keep sets in mind. def isdig(inp): #py33 inp = str(inp) return False if inp == '' else not (set(inp) - set('0123456789')) -- Jim Today is the day that would have been tomorrow if yesterday was today From eryksun at gmail.com Mon Jun 10 05:40:53 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 9 Jun 2013 23:40:53 -0400 Subject: [Tutor] three numbers for one In-Reply-To: <51B49DC3.1090003@pearwood.info> References: <51B49DC3.1090003@pearwood.info> Message-ID: On Sun, Jun 9, 2013 at 11:22 AM, Steven D'Aprano wrote: > On 10/06/13 00:26, Oscar Benjamin wrote: > >>>>> def is_ascii_digit(string): >> >> ... return not (set(string) - set('0123456789')) > > That's buggy, because it claims that '' is an ascii digit. > > This is likely to be quicker, if not for small strings at least for large > strings: > > def is_ascii_digit(string): > return string and all(c in set('0123456789') for c in string) Or use a regex with the category \d and the re.ASCII flag: http://docs.python.org/3/library/re#re.A Its match() method should be several times faster than iterating the string with a generator expression. CPython implementation (lookup table, bit fields): http://hg.python.org/cpython/file/3.3/Modules/_sre.c#l108 If you have a bytes/bytearray object, use isdigit(): >>> '1234\u06f0'.isdecimal() # Unicode decimal True >>> '1234\u06f0'.encode().isdigit() # ASCII digits False CPython 3 (and 2.x bytearray) uses a lookup table for this, defined in pyctype.h: http://hg.python.org/cpython/file/3.3/Python/pyctype.c From mnickey at gmail.com Mon Jun 10 07:49:35 2013 From: mnickey at gmail.com (Mike Nickey) Date: Sun, 9 Jun 2013 22:49:35 -0700 Subject: [Tutor] Tutor Digest, Vol 112, Issue 29 In-Reply-To: References: Message-ID: Thank you Alan, I appreciate your help. The issue that I'm having is that split() doesn't seem to meet the need. The words such as "isn't" comes back as "isn't" rather then "isn" and "t". On Sun, Jun 9, 2013 at 3:00 AM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Splitting on punctuation (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sun, 09 Jun 2013 06:48:13 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Splitting on punctuation > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 09/06/13 00:44, Mike Nickey wrote: > > > One of the tasks is to split on punctuation passed yet I'm having a bit > > more trouble then I expected. > > You do realize that split() can do that for you? > Its not limited to splitting on whitespace? > > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 112, Issue 29 > ************************************** > -- ~MEN -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 10 09:50:24 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Jun 2013 08:50:24 +0100 Subject: [Tutor] Tutor Digest, Vol 112, Issue 29 In-Reply-To: References: Message-ID: On 10/06/13 06:49, Mike Nickey wrote: > Thank you Alan, > I appreciate your help. > > The issue that I'm having is that split() doesn't seem to meet the need. > The words such as "isn't" comes back as "isn't" rather then "isn" and "t". How are you using split? This works for me: >>> "isn't".split("'") ['isn', 't'] -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Mon Jun 10 09:52:13 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Jun 2013 17:52:13 +1000 Subject: [Tutor] Am I missing something on module pyversions? In-Reply-To: References: Message-ID: <51B585AD.5070102@pearwood.info> On 10/06/13 10:57, Jim Mooney wrote: > I look at modules online and sometimes it's clear if they're for Py > 2.7 or Py3.3, usually in Requirements. Or if not, it's literally on > the download package, which will actually have 2.7 or 3.3 in the zip > or tar name. But on some sites it's totally unclear. They don't say it > at all up-front. I'll hunt around and still can't find it. > > Is there some standard I'm just overlooking that definitively says > which Py version a module is for? Or something in the module package > itself? I'm surprised this isn't a real up-front item. Or do I have to > search, guess, and download to find out? The standard is that it should be documented on the PyPI page, if they are on PyPI, or otherwise documented as a requirement, or mentioned on the project home page or FAQ page. But not all projects document, either due to laziness, incompetence, forgetfulness, or hope that it will work for any version of Python under the sun. Documenting the version as part of the file name is definitely *not* a standard. Most modules will work for a whole series of Python versions. What do you do? mymodule-2.4-2.5-2.6-2.7.zip which is ugly and silly, or: mymodule-2.4.zip which looks like it hasn't been updated in six years, or: mymodule-2.7.zip which looks like it doesn't support 2.4 through 2.6. The exception is, if you actually do have a separate version of your package for each Python release. Then it is wise to mirror the Python version in your version. -- Steven From steve at pearwood.info Mon Jun 10 09:57:31 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Jun 2013 17:57:31 +1000 Subject: [Tutor] Splitting on punctuation [was Tutor Digest, Vol 112, Issue 29] In-Reply-To: References: Message-ID: <51B586EB.4090405@pearwood.info> On 10/06/13 15:49, Mike Nickey wrote: > Thank you Alan, > I appreciate your help. > > The issue that I'm having is that split() doesn't seem to meet the need. > The words such as "isn't" comes back as "isn't" rather then "isn" and "t". Works for me. py> "isn't".split("'") ['isn', 't'] P.S. please remember to change the subject line when replying to a digest. As the digest itself says: >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Tutor digest..." Also please trim your quoting. We don't need to see a copy of a 400 line digest when you are replying to a five line comment. -- Steven From andipersti at gmail.com Mon Jun 10 10:21:04 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Mon, 10 Jun 2013 10:21:04 +0200 Subject: [Tutor] Splitting on punctuation In-Reply-To: References: Message-ID: <51B58C70.1000809@gmail.com> On 09.06.2013 01:44, Mike Nickey wrote: > Give the input of "which isn't that surprising I guess.",",'.") where the > first part passed is the string and the second part is the punctuation to > split on, I'm having difficulty converting the punctuation to a split > parameter. Read about the "translate" method to map every punctuation character to whitespace and the just use "split" on the translated string: http://docs.python.org/3/library/stdtypes.html#str.translate Bye, Andreas From fomcl at yahoo.com Mon Jun 10 10:27:23 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 10 Jun 2013 01:27:23 -0700 (PDT) Subject: [Tutor] Splitting on punctuation In-Reply-To: References: Message-ID: <1370852843.6017.YahooMailNeo@web163802.mail.gq1.yahoo.com> _______________________________ > From: Alan Gauld >To: tutor at python.org >Sent: Sunday, June 9, 2013 7:48 AM >Subject: Re: [Tutor] Splitting on punctuation > > >On 09/06/13 00:44, Mike Nickey wrote: > >> One of the tasks is to split on punctuation passed yet I'm having a bit >> more trouble then I expected. > >You do realize that split() can do that for you? >Its not limited to splitting on whitespace? Or use re.split: >>> import re, string >>> string.punctuation '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' >>> re.split("[" + string.punctuation + "]+", "yes, but no. But: yes, no") ['yes', ' but no', ' But', ' yes', ' no'] >>> From eryksun at gmail.com Mon Jun 10 12:12:18 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 10 Jun 2013 06:12:18 -0400 Subject: [Tutor] Splitting on punctuation In-Reply-To: <1370852843.6017.YahooMailNeo@web163802.mail.gq1.yahoo.com> References: <1370852843.6017.YahooMailNeo@web163802.mail.gq1.yahoo.com> Message-ID: On Mon, Jun 10, 2013 at 4:27 AM, Albert-Jan Roskam wrote: > >>>> string.punctuation > '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' >>>> re.split("[" + string.punctuation + "]+", "yes, but no. But: yes, no") > ['yes', ' but no', ' But', ' yes', ' no'] Even though you didn't use re.escape(), that almost works, except for backslash. Since the string doesn't start with ^ or end with ], neither is treated specially. Also, because string.punctuation is sorted, the range ,-. is valid, and even correct: >>> pat = re.compile('[,-.]', re.DEBUG) in range (44, 46) >>> map(ord, ',-.') [44, 45, 46] However, the otherwise harmless escape \] does consume the backslash. So remember to use re.escape. Without re.escape: >>> pat1 = re.compile('[%s]+' % string.punctuation) >>> pat1.split(r'yes, but no... But: yes\no') ['yes', ' but no', ' But', ' yes\\no'] With re.escape: >>> pat2 = re.compile('[%s]+' % re.escape(string.punctuation)) >>> pat2.split(r'yes, but no... But: yes\no') ['yes', ' but no', ' But', ' yes', 'no'] From oscar.j.benjamin at gmail.com Mon Jun 10 14:55:18 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 10 Jun 2013 13:55:18 +0100 Subject: [Tutor] three numbers for one In-Reply-To: <51B49DC3.1090003@pearwood.info> References: <51B49DC3.1090003@pearwood.info> Message-ID: On 9 June 2013 16:22, Steven D'Aprano wrote: > On 10/06/13 00:26, Oscar Benjamin wrote: >> >> I don't think I like this behaviour: I don't mind the isdigit, >> isdecimal and isnumeric methods but I don't want int() to accept >> non-ascii characters. This is a reasonable addition to the unicodedata >> module but should not happen when simply calling int(). > > Why not? What problem do you see? I don't know. I guess I just thought I understood what it was doing but now realise that I didn't. > Decimal digits are perfectly well defined. There is no ambiguity in what > counts as a decimal digit and what doesn't. Yes, but I thought it was using a different unambiguous and easier (for me) to understand definition of decimal digits. I guess that I'm just coming to realise exactly what Python 3's unicode support really means and in many cases it means that the interpreter is doing things that I don't want or need. For example I very often pipe streams of ascii numeric text from one program to another. In some cases the cost of converting to/from decimal is actually significant and Python 3 will add to this both with a more complex conversion and with its encoding/decoding part of the io stack. I'm wondering whether I should really just be using binary mode for this kind of thing in Python 3 since this at least removes an unnecessary part of the stack. In a previous thread where I moaned about the behaviour of the int() function Eryksun suggested that it would be better if int() wan't used for parsing strings at all. Since then I've thought about that and I agree. There should be separate functions for each kind of string to number conversion with one just for ascii decimal only. >> To answer Jim's original question, there doesn't seem to be a function >> to check for only plain old 0-9 > > Why would you want to? For no extra effort, you can handle numbers written > in just about any language. I can see how this would be useful if numbers are typed in interactively or perhaps given at the command line. There are many other cases where this is not needed or desired though. > You get this for free. Why would you want to > work *harder* in order to be *less useful*? > >> but you can make your own easily enough: >> >>>>> def is_ascii_digit(string): >> >> ... return not (set(string) - set('0123456789')) > > That's buggy, because it claims that '' is an ascii digit. > > This is likely to be quicker, if not for small strings at least for large > strings: > > def is_ascii_digit(string): > return string and all(c in set('0123456789') for c in string) I wasn't really worried about speed but in that case I might try: is_ascii_digit = frozenset('0123456789').__contains__ def is_ascii_digits(string): return string and all(map(is_ascii_digit, string)) Although Eryksun's regex is probably faster. >> An alternative method depending on where your strings are actually >> coming from would be to use byte-strings or the ascii codec. I may >> consider doing this in future; in my own applications if I pass a >> non-ascii digit to int() then I definitely have data corruption. > > It's not up to built-ins like int() to protect you from data corruption. > Would you consider it reasonable for me to say "in my own applications, if I > pass a number bigger than 100, I definitely have data corruption, therefore > int() should not support numbers bigger than 100"? I expect the int() function to reject invalid input. I thought that its definition of invalid matched up with my own. Oscar From ramit.prasad at jpmorgan.com Mon Jun 10 17:53:06 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 10 Jun 2013 15:53:06 +0000 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B23831.1020202@nycap.rr.com> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B23831.1020202@nycap.rr.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF47418478ADF@SCACMX008.exchad.jpmchase.net> Adding attribution back (I wrote the original quoted bit). Please leave the attribution as I have done below otherwise it is unclear who said what. Matt D wrote: > [Ramit Prasad wrote:] > > It looks to me like there is a separate thread that pulls data off some queue > > and then hands it to WX in the form of a DataEvent. WX calls display_data > > which unpickles the data. Pickle is just a format of storage and can store > > all Python built-in types. It seems that what is stored is a Python > > dictionary. In fact, you can probably add (and should add) a print statement > > to print attrs in display_data to see the data. It's always important to know > > what your data looks like. If you are only familiar with Visual Basic and C++, > > you may want to familiarize yourself with Dictionaries (aka Hashmaps). They > > are basically containers with key-value pairs for unique keys. By knowing the > > name of the data you want (for example "duid") you can retrieve the value and > > post it back to the appropriate TextCtrl. > > > > Hey, > So is the separate thread is this??: > > import gnuradio.gr.gr_threading as _threading Well that is the threading base class. traffic_watcher_thread is the class that actually which does the threading. > > This is how the pickled data is brought into the wxPython UI? I have > been unable to find any explanation on the web about the wxDATA_EVENT? > > The 'class traffic_watcher_thread(_threading.Thread):' is this what > waits on the message queue for another frame of pickled data to come in? Yes that class is what does the waiting for data / threading bit. > > One of the main problems I have with understanding the Python code I > have shared is that the pickle comes from C++ code. The program uses > C++ for what is computational intense and it uses Python for the UI and > for sending the data stream between the C++ blocks. I have never tried > modifying code in a program that uses two languages before. Unless you have an academic curiosity, you really don't need to bother with what the C++ does. Knowing the data it returns is a good idea. > > From python.org/2/library/pickle: > "Perhaps the most obvious thing to do with these byte streams is to > write them onto a file" and sense "the pickle data format uses a > printable ASCII representation" . . . "it is possible for a human to > read the pickled file with a standard text editor." I would love to > have this wxPython code write the pickled data to file just to see > exactly what is in it. Do you know of some sort of code I can put in to > make the pickle write to a file? I think this is the best starting > point instead of playing with the UI. Why not just print field_values from TrafficPane.update? I wouldn't get caught up too much in the pickle data format. What you care about is what it returns. So print the returned data (after it is already unpickled). Writing to file is also a reasonable endeavor, the below sample will write to file, but it will overwrite the file each time you get new data. You can change 'w' to 'a' (I think) for append mode which will then append to the bottom of the file. Not sure how fast your data will grow so you may want to watch the file size. You may also want to look at the pprint std library instead of str. It helps to format objects when being logged/printed to make them easier to see. For this example you would replace `str` with `pprint.pformat` (and appropriate arguments). # using open as a context manager will open and close file automatically with open( r'c:\unpickled_data.txt', 'w' ) as f: f.write( str(field_values) ) > > Thank you very much for your attention. > Cheers, > Matt > This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Mon Jun 10 18:23:35 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 10 Jun 2013 16:23:35 +0000 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B28759.60201@nycap.rr.com> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B28759.60201@nycap.rr.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> Matt D wrote: > Ramit Prasad wrote: > >>> Scrolled panel is just a graphical container that allows for scrolling inside, > >>> but it is the window that scrolls not widgets inside it. This of it like > >>> a webpage that scrolls. If you use web email the text widget in the > >>> email needs to scroll so you can see your full email context and not > >>> just scroll the page. > >>> > >>> You will probably need to create a TextCtrl with the appropriate style > >>> and append your new data. I have given an example below that should > >>> automatically scroll with your new data. > >>> > >>> #in __init__ > >>> self.scrolling_widget = wx.TextCtrl( self, wx.ID_ANY, '', size=(-1, 275), > >> style=wx.TE_AUTO_SCROLL|wx.TE_READONLY|wx.TE_PROCESS_ENTER|wx.TE_WORDWRAP|wx.TE_MULTILINE ) > >>> > Hey, > I added this the above 3 lines of code to my file and ran it. the box > shows up on the far left, mostly of the pane, to the left of the current > text feilds. I am having trouble positioning this textbox under where > the current text fields are. > I am not sure but maybe this sets up the grid on the pane: > sizer = wx.GridBagSizer(hgap=10, vgap=10) > self.fields = {} > all the current TextCtrl fields are positioned at (1,1) through (5,5). > I tried adding: > sizer.Add(field, pos=(1,6)) > but it did not move the box to the position? Just to make sure, you did call it field and not self.scrolling_widget (which was in my example)? Odd that they don't start at (0,0) when adding to the bag. This is more a wxpython question and their mailing list might prove more useful. I could figure it out, but I cannot run the app. Trial and error here will probably help you the most. You can also try looking at a different sizer (like BoxSizer and GridSizer). Personally, I think BoxSizer is the most intuitive as it matches my thought process. You just set an orientation (vertical/horizontal) and add widgets to it. To get something in the other direction, you create another box sizer with the opposite orientation, add widgets to that sizer, and then add the new sizer to the original sizer. Not nearly as pretty as grid/grid bag though (by default), but super simple. BoxSizer API http://wxpython.org/docs/api/wx.BoxSizer-class.html Some other sizers are listed here: http://wxpython.org/docs/api/wx.Sizer-class.html > > THanks, > Matt ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From michaelsparks37 at gmail.com Mon Jun 10 19:48:07 2013 From: michaelsparks37 at gmail.com (Michael Sparks) Date: Mon, 10 Jun 2013 10:48:07 -0700 Subject: [Tutor] Trying to get mp3play-0.1.15 module to work on Windows 7 Message-ID: I read Practical Programming, chapter 4 and I know how to write and use my own modules on IDLE for Python 3.2 but now I switched to version 2.7 and I don't know how to use a downloaded module such as mp3play-0.1.15 written by Michael Gundlach. I got Python 2.5, 2.7 and 3.2 on my computer at home and I prefer 2.7 for it's modern use (esp. with Csound). I'm using this computer in a coffee shop for internet. I can make small downloads onto my pen drive and transfer them to my laptop at home (well "so-called" home; It's a sober house and I've been sober for a month except for nicoteen, coffee and meds. All I need is one more month in Port Hardy, I believe.). The zip archive contains py files example.py and setup.py in the root directory of the zip including another folder called mp3play containing __init__.py and windows.py including matching pyc files for __init__ and windows. I could e-mail Gundlach himself but I thought I'd ask at least one of you first. Couldn't figure it out even with the documentation yesterday so please teach me as if I know nothing about it. I just want to see If I can play an mp3 in Python. even though I know the/some basics of IDLE, I still have a fair guessing time with the Wing 101 IDE (lite/light version). -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jun 10 20:26:51 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Jun 2013 19:26:51 +0100 Subject: [Tutor] Trying to get mp3play-0.1.15 module to work on Windows 7 In-Reply-To: References: Message-ID: On 10/06/13 18:48, Michael Sparks wrote: > I read Practical Programming, chapter 4 and I know how to write and use > my own modules on IDLE for Python 3.2 but now I switched to version 2.7 > and I don't know how to use a downloaded module such as mp3play-0.1.15 > written by Michael Gundlach. OK, let's see if we can boil this question down to its basics. IDLE should be irrelevant: it is just a development tool that has little or no bearing on whether Python can use your module. The fact you used to use 3.2 is also of little relevance since you are only interested in 2.7 at the moment, correct? > The zip archive contains py files example.py and setup.py in the root > directory of the zip including another folder called mp3play containing > __init__.py and windows.py including matching pyc files for __init__ and > windows. I could e-mail Gundlach himself but I thought I'd ask at least > one of you first. I'm guessing that this module is in a standard package format so have you tried following the usual installation process for third party packages? Do you know what that is? Assuming the answers to all 3 questions above is yes then you are probably best talking to the author. If not then tell us exactly what you did to install the package, what happened and post any error messages in full. > I just want to see If I can play an mp3 in Python. I suspect there are easier ways using the standard library or more well known packages (PyGame maybe?). But for now let's focus on your package problem... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Mon Jun 10 21:01:03 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 10 Jun 2013 20:01:03 +0100 Subject: [Tutor] Trying to get mp3play-0.1.15 module to work on Windows 7 In-Reply-To: References: Message-ID: On 10/06/2013 18:48, Michael Sparks wrote: > I read Practical Programming, chapter 4 and I know how to write and use > my own modules on IDLE for Python 3.2 but now I switched to version 2.7 > and I don't know how to use a downloaded module such as mp3play-0.1.15 > written by Michael Gundlach. I got Python 2.5, 2.7 and 3.2 on my > computer at home and I prefer 2.7 for it's modern use (esp. with > Csound). I'm using this computer in a coffee shop for internet. I can > make small downloads onto my pen drive and transfer them to my laptop at > home (well "so-called" home; It's a sober house and I've been sober for > a month except for nicoteen, coffee and meds. All I need is one more > month in Port Hardy, I believe.). > The zip archive contains py files example.py and setup.py in the root > directory of the zip including another folder called mp3play containing > __init__.py and windows.py including matching pyc files for __init__ and > windows. I could e-mail Gundlach himself but I thought I'd ask at least > one of you first. > Couldn't figure it out even with the documentation yesterday so please > teach me as if I know nothing about it. > I just want to see If I can play an mp3 in Python. > even though I know the/some basics of IDLE, I still have a fair guessing > time with the Wing 101 IDE (lite/light version). > What doesn't work about the installation instructions here http://code.google.com/p/mp3play/ ? -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From bjames at Jamesgang.dyndns.org Mon Jun 10 22:03:59 2013 From: bjames at Jamesgang.dyndns.org (bjames at Jamesgang.dyndns.org) Date: Mon, 10 Jun 2013 15:03:59 -0500 Subject: [Tutor] First program after PyCamp Message-ID: <7eea23564907a4a049d861fe3b278c66.squirrel@jamesgang.dyndns.org> Hello I just took a 3 day PyCamp and am working on my first program from start to finish at the moment and running into a problem. Not sure how it's supposed to be on this list so I'm going to first describe what my program is supposed to do and where I'm having the problems, then post the actual code. Please don't simply come back with a working version of the code since I want to know what each step does, but also explain where I went wrong and why the new version is better, or even better suggest where I should look to fix it without actually fixing it for me. The program is supposed to be given a directory and then look through that directory and all sub-directories and find duplicate files and output the list of duplicates to a text file. This is accomplished by generating a MD5 hash for the files then comparing that hash to a list of previous hashes that have been generated. My problem is the text file that is output seems to contain EVERY file that the program went through rather than just the duplicates. I've tried to mentally step through and figure out where/why it's listing all of them rather than just duplicates and I seem to be failing to spot it. here's the code: ---begin code paste--- import os, hashlib #rootdir = 'c:\Python Test' hashlist = {} # content signature -> list of filenames dups = [] def get_hash(rootdir): # """goes through directory tree, compares md5 hash of all files, # combines files with same hash value into list in hashmap directory""" for path, dirs, files in os.walk(rootdir): #this section goes through the given directory, and all subdirectories/files below #as part of a loop reading them in for filename in files: #steps through each file and starts the process of getting the MD5 hashes for the file #comparing that hash to known hashes that have already been calculated and either merges it #with the known hash (which indicates duplicates) or adds it so that it can be compared to future #files fullname = os.path.join(path, filename) with open(fullname) as f: #does the actual hashing md5 = hashlib.md5() while True: d = f.read(4096) if not d: break md5.update(d) h = md5.hexdigest() filelist = hashlist.setdefault(h, []) filelist.append(fullname) for x in hashlist: currenthash = hashlist[x] #goes through and if has has more than one file listed with it #considers it a duplicate and adds it to the output list if len(currenthash) > 1: dups.append(currenthash) output = open('duplicates.txt','w') output.write(str(dups)) output.close() ---end code paste--- Thank you for taking the time to help me Bryan From wprins at gmail.com Mon Jun 10 23:06:29 2013 From: wprins at gmail.com (Walter Prins) Date: Mon, 10 Jun 2013 22:06:29 +0100 Subject: [Tutor] First program after PyCamp In-Reply-To: <7eea23564907a4a049d861fe3b278c66.squirrel@jamesgang.dyndns.org> References: <7eea23564907a4a049d861fe3b278c66.squirrel@jamesgang.dyndns.org> Message-ID: Hi Bryan, On 10 June 2013 21:03, wrote: > My problem is the text file that is output seems to contain EVERY file > that the program went through rather than just the duplicates. > "Seems" does not sound very certain... have you double checked whether your suspicion is in fact correct? E.g. have you tested your program with, say, a small test folder with a known number of test duplicates and non duplicates to and gotten incorrect results? (It appears to work for me... Maybe you just have many duplicates? ) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Jun 11 00:13:26 2013 From: davea at davea.name (Dave Angel) Date: Mon, 10 Jun 2013 18:13:26 -0400 Subject: [Tutor] First program after PyCamp In-Reply-To: <7eea23564907a4a049d861fe3b278c66.squirrel@jamesgang.dyndns.org> References: <7eea23564907a4a049d861fe3b278c66.squirrel@jamesgang.dyndns.org> Message-ID: <51B64F86.1000505@davea.name> On 06/10/2013 04:03 PM, bjames at Jamesgang.dyndns.org wrote: > Hello I just took a 3 day PyCamp and am working on my first program from > start to finish at the moment and running into a problem. > > Not sure how it's supposed to be on this list Please start by defining your version of Python. I'm going to assume Python 2.7, as in Python 3, you'd have gotten an error from the hashing, logic, after opening that file in text mode. so I'm going to first > describe what my program is supposed to do and where I'm having the > problems, then post the actual code. Please don't simply come back with a > working version of the code since I want to know what each step does, but > also explain where I went wrong and why the new version is better, or even > better suggest where I should look to fix it without actually fixing it > for me. > > The program is supposed to be given a directory and then look through that > directory and all sub-directories and find duplicate files and output the > list of duplicates to a text file. This is accomplished by generating a > MD5 hash for the files then comparing that hash to a list of previous > hashes that have been generated. > > My problem is the text file that is output seems to contain EVERY file > that the program went through rather than just the duplicates. I've tried > to mentally step through and figure out where/why it's listing all of them > rather than just duplicates and I seem to be failing to spot it. First some general comments. Please don't use so many columns for your source file. That may work for you on your own screen, but it's problematic when someone else has to deal with the code. In my case, several of those comments wrapped in the email, and I had to re-edit them before trying things. Next, try to factor your code into reasonable pieces. You have a single function that does at least 3 things; make it three functions. One reason is that then you can frequently figure out which ones of them are correct, and which ones need work. Another reason is you can reuse the logic you spent time building and testing. First function gathers filenames that meet a particular criteria. In this case, it's simply all files in a subtree of a starting place. After you get the hang of things, you'll realize this could better be a generator, but no hurry yet. At present, it should generate a list, and RETURN that list. Not just tuck things into some global. Second function generates md5 checksums of all those file, uses that checksum as a key, and groups the files having the same key together. It should return the dict, rather than modifying some global one. Third function analyzes the dict created by the second one, and prepares a report (to file, or to print). > > here's the code: > ---begin code paste--- > import os, hashlib > #rootdir = 'c:\Python Test' I know this is commented out, but notice that the backslash is a big risk here. If a directory happened to start with t, for example, the filename would have a tab in it. Either use forward slashes (which do work in Windows), or use a raw literal. Or escape it with doubling the backslashes. > hashlist = {} # content signature -> list of filenames > dups = [] > > def get_hash(rootdir): > # """goes through directory tree, compares md5 hash of all files, > # combines files with same hash value into list in hashmap directory""" > for path, dirs, files in os.walk(rootdir): > #this section goes through the given directory, and all > subdirectories/files below > #as part of a loop reading them in > for filename in files: > #steps through each file and starts the process of getting the > MD5 hashes for the file > #comparing that hash to known hashes that have already been > calculated and either merges it > #with the known hash (which indicates duplicates) or adds it > so that it can be compared to future > #files > fullname = os.path.join(path, filename) > with open(fullname) as f: You're defaulting to text files, so the checksum will not in general match the standard md5sum which should get the exact same value. And in Python 3, this would try to decode the file as text, using some default encoding, and even if it didn't fail, would then get an error down below, since the hexdigest() stuff doesn't work on characters, but on bytes. with open(fullname, "rb") as f: > #does the actual hashing > md5 = hashlib.md5() > while True: > d = f.read(4096) > if not d: > break > md5.update(d) > h = md5.hexdigest() > filelist = hashlist.setdefault(h, []) > filelist.append(fullname) > > for x in hashlist: > currenthash = hashlist[x] This is confusing both for the names, and for the inefficiency. Try for hash, files in hashlist.items(): hash is what you called x, and files is what you called currenthash. > #goes through and if has has more than one file listed with it > #considers it a duplicate and adds it to the output list > if len(currenthash) > 1: > dups.append(currenthash) Now with the renaming, this becomes: if len(files) > 1: dups.append(files) Note that if I were you, I'd make it dups.append(hash, files) that way, the output would (by default) show the hash that these files supposedly shared. > output = open('duplicates.txt','w') > output.write(str(dups)) > output.close() Clearly this output could be made prettier, once you're confident the other parts are working. But I imagine you just hadn't gotten to that yet. Now, the code worked fine for me, and I doublechecked each of the duplicates it found with md5sum (standard on Linux, and available for Windows). When you look at the output, are there any entries that do NOT have multiple files listed? Have you done a dir /s /b of the same directory tree, redirected it to a file, and compared the size of that file to what this code finds? -- DaveA From bjames at Jamesgang.dyndns.org Tue Jun 11 00:21:39 2013 From: bjames at Jamesgang.dyndns.org (bjames at Jamesgang.dyndns.org) Date: Mon, 10 Jun 2013 17:21:39 -0500 Subject: [Tutor] First program after PyCamp In-Reply-To: <51B64F86.1000505@davea.name> References: <7eea23564907a4a049d861fe3b278c66.squirrel@jamesgang.dyndns.org> <51B64F86.1000505@davea.name> Message-ID: <9ca16f999bfdf07bda034f3a05647ea5.squirrel@jamesgang.dyndns.org> Thank you for your quick response Dave. I found out after I submitted my code here that it does in fact work now. I had spent several interupted hours trying to get it to work and must have changed something and forgotten about the change before submitting it here. I appreciate your suggestions and plan to incorporate at least some of them to make the code better (I understand it's not pythonic method change it once it's working 'well enough' but I'm going to for the learning experience. > On 06/10/2013 04:03 PM, bjames at Jamesgang.dyndns.org wrote: >> Hello I just took a 3 day PyCamp and am working on my first program from >> start to finish at the moment and running into a problem. >> >> Not sure how it's supposed to be on this list > > Please start by defining your version of Python. I'm going to assume > Python 2.7, as in Python 3, you'd have gotten an error from the hashing, > logic, after opening that file in text mode. > > so I'm going to first >> describe what my program is supposed to do and where I'm having the >> problems, then post the actual code. Please don't simply come back with >> a >> working version of the code since I want to know what each step does, >> but >> also explain where I went wrong and why the new version is better, or >> even >> better suggest where I should look to fix it without actually fixing it >> for me. >> >> The program is supposed to be given a directory and then look through >> that >> directory and all sub-directories and find duplicate files and output >> the >> list of duplicates to a text file. This is accomplished by generating a >> MD5 hash for the files then comparing that hash to a list of previous >> hashes that have been generated. >> >> My problem is the text file that is output seems to contain EVERY file >> that the program went through rather than just the duplicates. I've >> tried >> to mentally step through and figure out where/why it's listing all of >> them >> rather than just duplicates and I seem to be failing to spot it. > > First some general comments. Please don't use so many columns for your > source file. That may work for you on your own screen, but it's > problematic when someone else has to deal with the code. In my case, > several of those comments wrapped in the email, and I had to re-edit > them before trying things. > > Next, try to factor your code into reasonable pieces. You have a single > function that does at least 3 things; make it three functions. One > reason is that then you can frequently figure out which ones of them are > correct, and which ones need work. Another reason is you can reuse the > logic you spent time building and testing. > > First function gathers filenames that meet a particular criteria. In > this case, it's simply all files in a subtree of a starting place. > After you get the hang of things, you'll realize this could better be a > generator, but no hurry yet. At present, it should generate a list, and > RETURN that list. Not just tuck things into some global. > > Second function generates md5 checksums of all those file, uses that > checksum as a key, and groups the files having the same key together. > It should return the dict, rather than modifying some global one. > > Third function analyzes the dict created by the second one, and prepares > a report (to file, or to print). > > >> >> here's the code: >> ---begin code paste--- >> import os, hashlib >> #rootdir = 'c:\Python Test' > > I know this is commented out, but notice that the backslash is a big > risk here. If a directory happened to start with t, for example, the > filename would have a tab in it. Either use forward slashes (which do > work in Windows), or use a raw literal. Or escape it with doubling the > backslashes. > >> hashlist = {} # content signature -> list of filenames >> dups = [] >> >> def get_hash(rootdir): >> # """goes through directory tree, compares md5 hash of all files, >> # combines files with same hash value into list in hashmap >> directory""" >> for path, dirs, files in os.walk(rootdir): >> #this section goes through the given directory, and all >> subdirectories/files below >> #as part of a loop reading them in >> for filename in files: >> #steps through each file and starts the process of getting >> the >> MD5 hashes for the file >> #comparing that hash to known hashes that have already been >> calculated and either merges it >> #with the known hash (which indicates duplicates) or adds >> it >> so that it can be compared to future >> #files >> fullname = os.path.join(path, filename) >> with open(fullname) as f: > > You're defaulting to text files, so the checksum will not in general > match the standard md5sum which should get the exact same value. And in > Python 3, this would try to decode the file as text, using some default > encoding, and even if it didn't fail, would then get an error down > below, since the hexdigest() stuff doesn't work on characters, but on > bytes. > > with open(fullname, "rb") as f: > >> #does the actual hashing >> md5 = hashlib.md5() >> while True: >> d = f.read(4096) >> if not d: >> break >> md5.update(d) >> h = md5.hexdigest() >> filelist = hashlist.setdefault(h, []) >> filelist.append(fullname) >> >> for x in hashlist: >> currenthash = hashlist[x] > > This is confusing both for the names, and for the inefficiency. Try > for hash, files in hashlist.items(): > > hash is what you called x, and files is what you called currenthash. > >> #goes through and if has has more than one file listed with it >> #considers it a duplicate and adds it to the output list >> if len(currenthash) > 1: >> dups.append(currenthash) > > Now with the renaming, this becomes: > > if len(files) > 1: > dups.append(files) > > Note that if I were you, I'd make it > dups.append(hash, files) > > that way, the output would (by default) show the hash that these files > supposedly shared. > >> output = open('duplicates.txt','w') >> output.write(str(dups)) >> output.close() > > Clearly this output could be made prettier, once you're confident the > other parts are working. But I imagine you just hadn't gotten to that > yet. > > Now, the code worked fine for me, and I doublechecked each of the > duplicates it found with md5sum (standard on Linux, and available for > Windows). > > When you look at the output, are there any entries that do NOT have > multiple files listed? Have you done a dir /s /b of the same directory > tree, redirected it to a file, and compared the size of that file to > what this code finds? > > > -- > DaveA > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From bjames at Jamesgang.dyndns.org Tue Jun 11 00:24:12 2013 From: bjames at Jamesgang.dyndns.org (bjames at Jamesgang.dyndns.org) Date: Mon, 10 Jun 2013 17:24:12 -0500 Subject: [Tutor] First program after PyCamp In-Reply-To: References: <7eea23564907a4a049d861fe3b278c66.squirrel@jamesgang.dyndns.org> Message-ID: <76a80d34cbe12efd2b3287ebdbd3a105.squirrel@jamesgang.dyndns.org> Walter, Thanks for the quick reply, I mentioned to Dave Angel that when I was working on it I spent a few interrupted hours working on it (at work, people asking for things distracted me) and the problem I mentioned WAS happening on small test cases, but yes when I run the code I actually submitted it was no longer happening. Luckily I was using git while doing it so I can go back through my code and figure out what I changed to make the badness go away, sorry to waste your time. > Hi Bryan, > > On 10 June 2013 21:03, wrote: > >> My problem is the text file that is output seems to contain EVERY file >> that the program went through rather than just the duplicates. >> > > "Seems" does not sound very certain... have you double checked whether > your > suspicion is in fact correct? E.g. have you tested your program with, > say, a small test folder with a known number of test duplicates and non > duplicates to and gotten incorrect results? (It appears to work for me... > Maybe you just have many duplicates? ) > > Walter > From alan.gauld at btinternet.com Tue Jun 11 00:39:20 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Jun 2013 23:39:20 +0100 Subject: [Tutor] First program after PyCamp In-Reply-To: <9ca16f999bfdf07bda034f3a05647ea5.squirrel@jamesgang.dyndns.org> References: <7eea23564907a4a049d861fe3b278c66.squirrel@jamesgang.dyndns.org> <51B64F86.1000505@davea.name> <9ca16f999bfdf07bda034f3a05647ea5.squirrel@jamesgang.dyndns.org> Message-ID: On 10/06/13 23:21, bjames at Jamesgang.dyndns.org wrote: > suggestions and plan to incorporate at least some of them to make the code > better (I understand it's not pythonic method change it once it's working > 'well enough' but I'm going to for the learning experience. There is nothing unpythonic about making bad code better. Thee is a school of thought that says "if it ain't broke don't fix it" but you won't find many professional programmers who subscribe to it - especially maintenance programmers. Getting code to work is only the first step to producing good quality code. Making it readable, easy to maintain and, possibly, more efficient are all reasons to do another pass. OTOH you can spend forever tweaking code to make it perfect and that is a waste of time. You have to make a judgement call about when code is good enough. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue Jun 11 01:38:58 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 11 Jun 2013 09:38:58 +1000 Subject: [Tutor] three numbers for one In-Reply-To: References: <51B49DC3.1090003@pearwood.info> Message-ID: <51B66392.1030008@pearwood.info> On 10/06/13 22:55, Oscar Benjamin wrote: > Yes, but I thought it was using a different unambiguous and easier > (for me) to understand definition of decimal digits. It's no easier. You have a list (in your head) of characters that are decimal digits. In your head, you have ten of them, because you are an English speaker and probably have never learned any language that uses other digits, or used DOS codepages or Windows charsets with alternate versions of digits (such as the East Asian full width and narrow width forms). You probably *have* used charsets like Latin-1 containing ??? but probably not often enough to think about them as potentially digits. But either way, in your head you have a list of decimal digits. Python also has a list of decimal digits, except it is longer. (Strictly speaking, it probably doesn't keep an explicit list "these chars are digits" in memory, but possibly looks them up in a Unicode property database as needed. But then, who knows how memories and facts are stored in the human brain? Strictly speaking, there's probably no list in your head either.) > I guess that I'm > just coming to realise exactly what Python 3's unicode support really > means and in many cases it means that the interpreter is doing things > that I don't want or need. With respect, it's not that you don't want or need them, but that you don't *know* that you actually do want and need them. (I assume you are releasing software for others to use. If all your software is private, for your own use and nobody else, then you may not care.) If your software accepts numeric strings from the user -- perhaps it reads a file, perhaps it does something like this: number = int(input("Please enter a number: ")) -- you want it to do the right thing when the user enters a number. Thanks to the Internet, your program is available to people all over the world. Well, in probably half the world, those digits are not necessarily the same as ASCII 0-9. Somebody downloads your app in Japan, points it at a data file containing fullwidth or halfwidth digits, and in Python 3 it just works. (Provided, of course, that you don't sabotage its ability to do so with inappropriate decimal only data validation.) > For example I very often pipe streams of ascii numeric text from one > program to another. No you don't. Never. Not once in the history of computers has anyone ever piped streams of text from one program to another. They just *think* they have. They pipe *bytes* from one program to another. > In some cases the cost of converting to/from > decimal is actually significant and Python 3 will add to this both > with a more complex conversion Let your mind be at rest on this account. Python 3.3 int() is nearly twice as fast as Python 2.7 for short strings: [steve at ando ~]$ python2.7 -m timeit "int('12345')" 1000000 loops, best of 3: 0.924 usec per loop [steve at ando ~]$ python3.3 -m timeit "int('12345')" 1000000 loops, best of 3: 0.485 usec per loop and about 25% faster for long strings: [steve at ando ~]$ python2.7 -m timeit "int('1234567890'*5)" 100000 loops, best of 3: 2.06 usec per loop [steve at ando ~]$ python3.3 -m timeit "int('1234567890'*5)" 1000000 loops, best of 3: 1.45 usec per loop It's a little slower when converting the other way: [steve at ando ~]$ python2.7 -m timeit "str(12345)" 1000000 loops, best of 3: 0.333 usec per loop [steve at ando ~]$ python3.3 -m timeit "str(12345)" 1000000 loops, best of 3: 0.5 usec per loop but for big numbers, the difference is negligible: [steve at ando ~]$ python2.7 -m timeit -s "n=1234567890**5" "str(n)" 1000000 loops, best of 3: 1.12 usec per loop [steve at ando ~]$ python3.3 -m timeit -s "n=1234567890**5" "str(n)" 1000000 loops, best of 3: 1.16 usec per loop and in any case, the time taken to convert to a string is trivial. > and with its encoding/decoding part of > the io stack. I'm wondering whether I should really just be using > binary mode for this kind of thing in Python 3 since this at least > removes an unnecessary part of the stack. I'm thinking that you're engaging in premature optimization. Have you profiled your code to confirm that the bottlenecks are where you think they are? > In a previous thread where I moaned about the behaviour of the int() > function Eryksun suggested that it would be better if int() wan't used > for parsing strings at all. Since then I've thought about that and I > agree. There should be separate functions for each kind of string to > number conversion with one just for ascii decimal only. I think that is a terrible, terrible idea. It moves responsibility for something absolutely trivial ("convert a string to a number") from the language to the programmer, *who will get it wrong*. # The right way: number = int(string) # The wrong, horrible, terrible way (and buggy too): try: number = ascii_int(string) except ValueError: try: number = fullwidth_int(string) except ValueError: try: number = halfwidth_int(string) except ValueError: try: number = thai_int(string) except ... # and so on, for a dozen or so other scripts... # oh gods, think of the indentation!!! except ValueError: # Maybe it's a mixed script number? # Fall back to char by char conversion. n = 0 for c in string: if c in ascii_digits: n += ord(c) - ord('0') elif c in halfwidth_digits: n += ord(c) - ord('\N{HALFWIDTH DIGIT ZERO}' elif ... # and so forth else: raise ValueError Of course, there are less stupid ways to do this. But you don't have to, because it already works. >>> An alternative method depending on where your strings are actually >>> coming from would be to use byte-strings or the ascii codec. I may >>> consider doing this in future; in my own applications if I pass a >>> non-ascii digit to int() then I definitely have data corruption. >> >> It's not up to built-ins like int() to protect you from data corruption. >> Would you consider it reasonable for me to say "in my own applications, if I >> pass a number bigger than 100, I definitely have data corruption, therefore >> int() should not support numbers bigger than 100"? > > I expect the int() function to reject invalid input. It does. What makes you think it doesn't? > I thought that its definition of invalid matched up with my own. If your definition is something other than "a string containing non-digits, apart from a leading plus or minus sign", then it is your definition that is wrong. -- Steven From cybervigilante at gmail.com Tue Jun 11 03:19:30 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 10 Jun 2013 18:19:30 -0700 Subject: [Tutor] Trying to get mp3play-0.1.15 module to work on Windows 7 In-Reply-To: References: Message-ID: On 10 June 2013 12:01, Mark Lawrence wrote: > On 10/06/2013 18:48, Michael Sparks wrote: >> > What doesn't work about the installation instructions here > http://code.google.com/p/mp3play/ ? I think they want the full error list, preferably from the ms-dos command line so the editor doesn't interfere. Here's my two cents anyway: I'm new at this and just went through figuring a lot of this module garbola, so I might as well share ;'). If you don't like this idea or it's voted down, ignore it, but here is what I think is the easiest way, which is to start over. Uninstall your python. Go to http://www.activestate.com/activepython/downloads and download theirs to install on your laptop. Download py2.7 - for x86 - I had compatibility problems with the 64 bit download even though I have a 64 bit computer. You don't need 64-bit if it's a hassle and 32 bit will play on either computer. Especially if you're operating fro two computers that might have different word sizes. The ActiveState python already has pip (an automated module installing program), along with a few other extras, which makes installing modules very easy, and also uninstalling, which can otherwise be a hassle. Yes, it is good to learn the intricacies of manual module installation after you learn a bit of python, but I think the complexity of that at first is a roadblock that can be done without for a time. If you don't use the ActiveState install you have to install setuptools first, then install pip, and the first install for pip I found for 2.7 was a bare text file I had to copy to a file and save, then run, so it's a big hassle. Py 3.3 has a complete windows installer for pip, though. I don't know about 2.7 since I had already done it the hard way ;') So if you went ActiveState to do it the easy way, you just go to the ms-dos command line after pyton installs (cmd in my Find bar in win 7) type pip install mp3play and enter. mp3play is in PyPI so it downloads and installs. Oh, if you already installed mp3play partially and it didn't work, type pip freeze in msdos first, to get a list of what's installed. Then, if you see mp3play in the list, pip uninstall mp3play to start over so you can copy the install error messages from the dos command console. pip will often uninstall anything it finds with freeze, even if it didn't install it. I already did that and was surprised it did, since I saw mention it had to install to uninstall. I mention uninstalling because I tried reinstalling to get the error list, but it had installed enough to not reinstall. If you can still install with the Same error messages you got, you don't have to uninstall it because it never installed. Come to think of it, the defective mp3play shouldn't be there if you uninstalled Py properly, and reinstalled it; although if the uninstall left a directory, as some uninstalls do, that might not be the case. This way, after running pip install mp3play , if it didn't work you should see a bunch of error messages in the dos box. If there are no error messages, pip worked and it installed, so the problem now is to figure out how to use mp3play. If import mp3play works in Python, it's there. Alternatively, if the install gave error messages in the dos window, just drag-highlight any errors on the msdos screen (it's a column highlight), and right click to copy so you can post here. Then you have the error messages everyone can parse. If you just want to see if Python can play a sound file, import winsound, which is already a part of Python, and you can play wav files only (See how by printing help(winsound) in Python, after importing winsound.) The winsound help is easy to follow. I found the mp3play instructions a bit terse. (mp3play doesn't actually work on py 3.3, even after I tried some fixups, mostly of print statements, but it installed and uninstalled just fine, with pip. I don't have a need for it right now. I can always record a wav and play it with winsound, with no module installs necessary, if I want a verbal program warning or something. It might be nice to have the except statements shout "You screwed up!" Actually, that sound like fun. I think I'll go do it.) For win 7, though, the windows sound recorder now records wma rather than wav, as it used to, so you need something else, like Audacity, to make a wav. Or get a wav file from windows\media - the raga folder has some nice sounds. -- Jim Today is the day that would have been tomorrow if yesterday was today From cybervigilante at gmail.com Tue Jun 11 08:17:12 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 10 Jun 2013 23:17:12 -0700 Subject: [Tutor] On a looping input, subsequent inputs are hidden Message-ID: This is puzzling me. I'm inputing an integer, giving a different visual and audio alert depending if it's bad or good, and that works fine. I'm looping input to ask for input again if a noninteger is entered. That works. But the Second and subsequent inputs, in Windows, hide the input with dots, while the first shows the input, and I can't figure out why. I don't change a thing between the first and subsequent calls to input except changing the input message to an error message. But it's just python input, not tkinter. Unless it's a Windows peculiarity. The input Always shows in DOS. But if it doesn't show in Linux, let's say, then I would guess it's a Python thing, and maybe there's a switch to turn that effect off. ============ main program ====================== #Using Python 3.3.2 on Win 7 - jimsbiginteger.py in jimprogs '''dependencies - pop.py''' import pop user_message = 'Type an integer: ' while True: try: num = int(input(user_message)) break except ValueError: user_message = ''' Sorry,that's not an integer. Try again or Cancel by using Cancel in a GUI window, or Ctrl-Z in DOS. or Ctrl-C in Linux. One mo try. Type an integer: ''' except (KeyboardInterrupt, EOFError): #1st Except for GUI, 2nd for Cmd window pop.popup('You cancelled, you so bad!') #string must contain 'bad' to trigger audio exit(0) pop.popup('\n You printed {} '.format(num)) ============ imported module ======================= #Using Python 3.3.2 on Win 7 - pop.py in jimlib '''dependencies - winsound, tkinter''' import winsound import tkinter from tkinter.constants import * def popup(usermessage): if 'bad' in usermessage: winsound.PlaySound('c://Python33//media//wtf.wav',1) else: winsound.PlaySound('c://Python33//media//goody.wav',1) tk = tkinter.Tk() frame = tkinter.Frame(tk, relief=RIDGE, borderwidth=2) frame.pack(fill=BOTH,expand=1) label = tkinter.Label(frame, text=usermessage) label.pack(fill=X, expand=1) button = tkinter.Button(frame,text="Exit",command=tk.destroy) button.pack(side=BOTTOM) tk.focus_force() #must be here or tkinter window may hide behind other windows tk.mainloop() -- Jim Today is the day that would have been tomorrow if yesterday was today From alan.gauld at btinternet.com Tue Jun 11 10:07:11 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Jun 2013 09:07:11 +0100 Subject: [Tutor] On a looping input, subsequent inputs are hidden In-Reply-To: References: Message-ID: On 11/06/13 07:17, Jim Mooney wrote: > But the Second and subsequent inputs, in Windows, hide the input with > dots, while the first shows the input, and I can't figure out why. Neither can I and I don't have Windows to test on. However there are a couple of things I'd say about the code. First you are effectively creating an entire Tkinter app inside popup() each time. That's a pretty heavyweight way to generate a messagebox. Have you used the Tkinter standard message dialogs? >>> import tkinter as tk >>> from tkinter import messagebox as mb >>> top = tk.Tk() # get the framework running >>> top.withdraw() # hide the root window Now you can create as many message boxes as you need... >>> mb.showinfo("Hello", "My message here") 'ok' >>> mb.showinfo("Hello", "and another") 'ok' >>> You can wrap the showinfo() calls in a function with your calls to winsound if you really want to. The other thing was the use of // in the path spec. You don't need that, Windows is quite happy with a single forward slash. It's only backslashes(\) that need doubling. Finally, to try to debug your problem somewhat I'd try commenting out the winsound stuff and see if that makes a difference. I don't see how it would but eliminating anything that might be confusing the issue is always a good starting point. > > def popup(usermessage): > if 'bad' in usermessage: > winsound.PlaySound('c://Python33//media//wtf.wav',1) > else: > winsound.PlaySound('c://Python33//media//goody.wav',1) > tk = tkinter.Tk() > frame = tkinter.Frame(tk, relief=RIDGE, borderwidth=2) > frame.pack(fill=BOTH,expand=1) > label = tkinter.Label(frame, text=usermessage) > label.pack(fill=X, expand=1) > button = tkinter.Button(frame,text="Exit",command=tk.destroy) > button.pack(side=BOTTOM) > tk.focus_force() #must be here or tkinter window may hide behind > other windows > tk.mainloop() > > HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From arijit.ukil at tcs.com Tue Jun 11 10:54:10 2013 From: arijit.ukil at tcs.com (Arijit Ukil) Date: Tue, 11 Jun 2013 14:24:10 +0530 Subject: [Tutor] Regarding python function arguments Message-ID: i am writing following python function: def my_func (arg1, arg2, arg3): however, I am not always going to pass all the arguments. sometimes only arg1 is passed, sometimes arg1 and arg2 are passed; sometimes arg1, arg2, arg3 are passed. How can i manage this? Regards, Arijit Ukil Tata Consultancy Services Mailto: arijit.ukil at tcs.com Website: http://www.tcs.com ____________________________________________ Experience certainty. IT Services Business Solutions Consulting ____________________________________________ =====-----=====-----===== Notice: The information contained in this e-mail message and/or attachments to it may contain confidential or privileged information. If you are not the intended recipient, any dissemination, use, review, distribution, printing or copying of the information contained in this e-mail message and/or attachments to it are strictly prohibited. If you have received this communication in error, please notify us by reply e-mail or telephone and immediately and permanently delete the message and any attachments. Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From pasokan at talentsprint.com Tue Jun 11 11:13:37 2013 From: pasokan at talentsprint.com (Asokan Pichai) Date: Tue, 11 Jun 2013 14:43:37 +0530 Subject: [Tutor] Regarding python function arguments In-Reply-To: References: Message-ID: On Tue, Jun 11, 2013 at 2:24 PM, Arijit Ukil wrote: > i am writing following python function: > > def my_func (arg1, arg2, arg3): > however, I am not always going to pass all the arguments. sometimes only > arg1 is passed, sometimes arg1 and arg2 are passed; sometimes arg1, arg2, > arg3 are passed. > How can i manage this? > Look at keyword arguments: http://docs.python.org/release/1.5.1p1/tut/keywordArgs.html BTW, don't you think that the signature attached by your organization is rather unsuitable for this list. For example, do I need an explicit disclaimer from you that you are not sharing company confidential information, if you post a solution? Asokan Pichai "Expecting the world to treat you fairly because you are a good person is a little like expecting the bull to not attack you because you are a vegetarian" -------------- next part -------------- An HTML attachment was scrubbed... URL: From c.t.matsumoto at gmail.com Tue Jun 11 11:14:33 2013 From: c.t.matsumoto at gmail.com (Todd Matsumoto) Date: Tue, 11 Jun 2013 11:14:33 +0200 Subject: [Tutor] Regarding python function arguments In-Reply-To: References: Message-ID: One way you can do that is by using default arguments. def my_func (arg1=False, arg2=False, arg3=False): # Check the arguments. On Tue, Jun 11, 2013 at 10:54 AM, Arijit Ukil wrote: > i am writing following python function: > > def my_func (arg1, arg2, arg3): > > however, I am not always going to pass all the arguments. sometimes only > arg1 is passed, sometimes arg1 and arg2 are passed; sometimes arg1, arg2, > arg3 are passed. > How can i manage this? > > Regards, > Arijit Ukil > Tata Consultancy Services > Mailto: arijit.ukil at tcs.com > Website: http://www.tcs.com > ____________________________________________ > Experience certainty. IT Services > Business Solutions > Consulting > ____________________________________________ > > =====-----=====-----===== > Notice: The information contained in this e-mail > message and/or attachments to it may contain > confidential or privileged information. If you are > not the intended recipient, any dissemination, use, > review, distribution, printing or copying of the > information contained in this e-mail message > and/or attachments to it are strictly prohibited. If > you have received this communication in error, > please notify us by reply e-mail or telephone and > immediately and permanently delete the message > and any attachments. Thank you > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Todd Matsumoto -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Jun 11 11:21:59 2013 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Jun 2013 11:21:59 +0200 Subject: [Tutor] Regarding python function arguments References: Message-ID: Arijit Ukil wrote: > i am writing following python function: > > def my_func (arg1, arg2, arg3): > > however, I am not always going to pass all the arguments. sometimes only > arg1 is passed, sometimes arg1 and arg2 are passed; sometimes arg1, arg2, > arg3 are passed. > How can i manage this? You can provide default values for some arguments: def my_func(arg1, arg2=None, arg3=None): print(arg1, arg2, arg3) my_func(1) # 1 None None my_func(1, 2) # 1 2 None my_func(1, arg3=3) # 1 None 3 my_func(1, arg1=1) # TypeError Note that evey argument after the first with a default must have a default, too: def my_func(arg1, arg2=None, arg3): # SyntaxError From emailkgnow at gmail.com Tue Jun 11 11:53:02 2013 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Tue, 11 Jun 2013 12:53:02 +0300 Subject: [Tutor] producing PDF files Message-ID: Hi, Do you know of a python module for converting text files to PDF format? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Tue Jun 11 11:51:33 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 11 Jun 2013 02:51:33 -0700 (PDT) Subject: [Tutor] Splitting on punctuation In-Reply-To: References: <1370852843.6017.YahooMailNeo@web163802.mail.gq1.yahoo.com> Message-ID: <1370944293.19798.YahooMailNeo@web163806.mail.gq1.yahoo.com> ----- Original Message ----- > From: eryksun > To: Albert-Jan Roskam > Cc: Alan Gauld ; "tutor at python.org" > Sent: Monday, June 10, 2013 12:12 PM > Subject: Re: [Tutor] Splitting on punctuation > > On Mon, Jun 10, 2013 at 4:27 AM, Albert-Jan Roskam > wrote: >> >>>>> string.punctuation >> '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' >>>>> re.split("[" + string.punctuation + "]+", > "yes, but no. But: yes, no") >> ['yes', ' but no', ' But', ' yes', ' > no'] > > Even though you didn't use re.escape(), that almost works, except for > backslash. Since the string doesn't start with ^ or end with ], > neither is treated specially. Also, because string.punctuation is > sorted, the range ,-. is valid, and even correct: Thank you. I should have been aware of all those meta-characters. I did not know about re.escape but it's handy indeed. ? ? > ? ? >>> pat = re.compile('[,-.]', re.DEBUG) > ? ? in > ? ? ? range (44, 46) > > ? ? >>> map(ord, ',-.') > ? ? [44, 45, 46] I tried using re.DEBUG but I can't really make sense of the output. If I am really desperate I sometimes use redemo.py in the scripts directory (or I'll email you guys --> I'll do that after this mail ;-) ? ? ? > However, the otherwise harmless escape \] does consume the backslash. > So remember to use re.escape. > > Without re.escape: > > ? ? >>> pat1 = re.compile('[%s]+' % string.punctuation) > ? ? >>> pat1.split(r'yes, but no... But: yes\no') > ? ? ['yes', ' but no', ' But', ' > yes\\no'] > > With re.escape: > > ? ? >>> pat2 = re.compile('[%s]+' % > re.escape(string.punctuation)) > ? ? >>> pat2.split(r'yes, but no... But: yes\no') > ? ? ['yes', ' but no', ' But', ' yes', > 'no'] > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From c.t.matsumoto at gmail.com Tue Jun 11 12:13:31 2013 From: c.t.matsumoto at gmail.com (Todd Matsumoto) Date: Tue, 11 Jun 2013 12:13:31 +0200 Subject: [Tutor] producing PDF files In-Reply-To: References: Message-ID: I don't know how good it is, but OpenERP's report.pyPdf module is what I've been using to do this. As quoted from the pdf.py module: "A pure-Python PDF library with very minimal capabilities. It was designed to be able to split and merge PDF files by page, and that's about all it can do. It may be a solid base for future PDF file work in Python." On Tue, Jun 11, 2013 at 11:53 AM, Khalid Al-Ghamdi wrote: > Hi, > > Do you know of a python module for converting text files to PDF format? > > thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Todd Matsumoto -------------- next part -------------- An HTML attachment was scrubbed... URL: From emailkgnow at gmail.com Tue Jun 11 12:20:20 2013 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Tue, 11 Jun 2013 13:20:20 +0300 Subject: [Tutor] sqlite question Message-ID: Hi, I have a dictionary with keys as employee badges and values as their names. Both key and value are strings. I want to read the badges from a sql select and use that to look up the names in the dictionary. But since the result is a tuple, it doesnt' work. how can i overcome this? 1. >>> for data in cur.execute('select badge from sched'): 2. r_data()[data] 3. 4. 5. Traceback (most recent call last): 6. File "", line 2, in 7. r_data()[data] 8. KeyError: (80385,) PS: the r_data () above is just a func that returns the before mentioned dictionary. Here is r_data(). 1. def r_data(): 2. d={} 3. with open('data.csv') as f: 4. reader = csv.reader(f) 5. for sn, badge, name, grp, major, track, stage, tc, subject, course in reader: 6. d[badge]=name 7. return d -------------- next part -------------- An HTML attachment was scrubbed... URL: From pasokan at talentsprint.com Tue Jun 11 12:05:49 2013 From: pasokan at talentsprint.com (Asokan Pichai) Date: Tue, 11 Jun 2013 15:35:49 +0530 Subject: [Tutor] producing PDF files In-Reply-To: References: Message-ID: On Tue, Jun 11, 2013 at 3:23 PM, Khalid Al-Ghamdi wrote: > Hi, > > Do you know of a python module for converting text files to PDF format? > > thanks > Reportlab http://www.reportlab.com/software/opensource/ sphinx http://sphinx-doc.org/ is a great choice too. Asokan Pichai "Expecting the world to treat you fairly because you are a good person is a little like expecting the bull to not attack you because you are a vegetarian" > > _______________________________________________ > 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 __peter__ at web.de Tue Jun 11 12:38:56 2013 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Jun 2013 12:38:56 +0200 Subject: [Tutor] sqlite question References: Message-ID: Khalid Al-Ghamdi wrote: > Hi, > > I have a dictionary with keys as employee badges and values as their > names. Both key and value are strings. > > I want to read the badges from a sql select and use that to look up the > names in the dictionary. But since the result is a tuple, it doesnt' work. > > how can i overcome this? > > > 1. >>> for data in cur.execute('select badge from sched'): > 2. r_data()[data] > 3. > 4. > 5. Traceback (most recent call last): > 6. File "", line 2, in > 7. r_data()[data] > 8. KeyError: (80385,) (80385,) instead of just 80385 should give you a hint that data is a tuple with a single item. Once you unpack it with key = data[0] you should be alright. So: for data in cur.execute(...): badge = data[0] r_data()[badge] You can make the unpacking implicit to the for loop with for badge, in cur.execute(...): # note the trailing comma r_data()[badge] or somewhat less subtle for [badge] in cur.execute(...): r_data()[badge] > PS: the r_data () above is just a func that returns the before > mentioned dictionary. Here is r_data(). > > 1. def r_data(): > 2. d={} > 3. with open('data.csv') as f: > 4. reader = csv.reader(f) > 5. for sn, badge, name, grp, major, track, stage, tc, > subject, > course in reader: > 6. d[badge]=name > 7. return d I assume in your final code you are not going to reread the csv for every row in the sched table... From c.t.matsumoto at gmail.com Tue Jun 11 12:40:44 2013 From: c.t.matsumoto at gmail.com (Todd Matsumoto) Date: Tue, 11 Jun 2013 12:40:44 +0200 Subject: [Tutor] sqlite question In-Reply-To: References: Message-ID: I think you are missing the fetch call. The cursor only executed your query, but hasn't fetched any thing out. On Tue, Jun 11, 2013 at 12:20 PM, Khalid Al-Ghamdi wrote: > Hi, > > I have a dictionary with keys as employee badges and values as their > names. Both key and value are strings. > > I want to read the badges from a sql select and use that to look up the > names in the dictionary. But since the result is a tuple, it doesnt' work. > > how can i overcome this? > > > 1. >>> for data in cur.execute('select badge from sched'): > 2. r_data()[data] > 3. > 4. > 5. Traceback (most recent call last): > 6. File "", line 2, in > 7. r_data()[data] > 8. KeyError: (80385,) > > PS: the r_data () above is just a func that returns the before > mentioned dictionary. Here is r_data(). > > 1. def r_data(): > 2. d={} > 3. with open('data.csv') as f: > 4. reader = csv.reader(f) > 5. for sn, badge, name, grp, major, track, stage, tc, > subject, course in reader: > 6. d[badge]=name > 7. return d > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Todd Matsumoto -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Tue Jun 11 12:56:34 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 11 Jun 2013 03:56:34 -0700 (PDT) Subject: [Tutor] regex: don't match embedded quotes Message-ID: <1370948194.52445.YahooMailNeo@web163801.mail.gq1.yahoo.com> Hi, ? I have written a regex that is supposed to match correctly quoted (single quotes on each side, or double quotes on each side) text. It works, but it also matches embedded quoted text, which I don't want to happen. I should somehow modify the 'comment' group such that it backreferences to 'quote' and includes only the inner quote sign. Background: I am playing around with this to see how hard it would be to write my own Pygments lexer, which I could then also use in IPython notebook. ? >>> import re >>> s = "some enumeration 1 'test' 2 'blah' 3 'difficult \"One\"'." >>> matches = re.finditer("(?P['\"])(?P[^'\"]*)(?P=quote)", s, re.DEBUG) subpattern 1 ? in ??? literal 39 ??? literal 34 subpattern 2 ? max_repeat 1 65535 ??? in ????? negate None ????? literal 39 ????? literal 34 groupref 1 # follow-up to a previous thread about splitting on punctuation: I have no idea how the output of re.DEBUG could help me improve my regex. >>> [match.group("comment") for match in matches] ['test', 'blah', 'One']? # I do not want to match "One" 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? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From __peter__ at web.de Tue Jun 11 13:03:19 2013 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Jun 2013 13:03:19 +0200 Subject: [Tutor] sqlite question References: Message-ID: Todd Matsumoto wrote: [Please don't top-post] > On Tue, Jun 11, 2013 at 12:20 PM, Khalid Al-Ghamdi > wrote: >> 1. >>> for data in cur.execute('select badge from sched'): >> 2. r_data()[data] > I think you are missing the fetch call. The cursor only executed your > query, but hasn't fetched any thing out. No, sqlite supports iterating over the cursor directly. From fomcl at yahoo.com Tue Jun 11 13:05:38 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 11 Jun 2013 04:05:38 -0700 (PDT) Subject: [Tutor] regex: don't match embedded quotes In-Reply-To: <1370948194.52445.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <1370948194.52445.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: <1370948738.41687.YahooMailNeo@web163804.mail.gq1.yahoo.com> ----- Original Message ----- > From: Albert-Jan Roskam > To: Python Mailing List > Cc: > Sent: Tuesday, June 11, 2013 12:56 PM > Subject: [Tutor] regex: don't match embedded quotes > > Hi, > ? > I have written a regex that is supposed to match correctly quoted (single quotes > on each side, or double quotes on each side) text. It works, but it also matches > embedded quoted text, which I don't want to happen. > I should somehow modify the 'comment' group such that it backreferences > to 'quote' and includes only the inner quote sign. Background: I am > playing around with this to see how hard it would be to write my own Pygments > lexer, which I could then also use in IPython notebook. > ? >>>> import re >>>> s = "some enumeration 1 'test' 2 'blah' 3 > 'difficult \"One\"'." >>>> matches = > re.finditer("(?P['\"])(?P[^'\"]*)(?P=quote)", > s, re.DEBUG) ? Okay, I am having blood-shut eyes now, but I think I've got it: ? >>> matches = re.finditer("(?P['\"])(?P(?>> [match.group("comment") for match in matches] ['test', 'blah', 'difficult "One"'] In other words: The 'comment' group should preceded by be a negative lookbehind (? <1370948738.41687.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam wrote: >> I have written a regex that is supposed to match correctly quoted (single >> quotes on each side, or double quotes on each side) text. It works, but > Okay, I am having blood-shut eyes now, but I think I've got it: >>>> matches = >>>> re.finditer("(?P['\"])(?P(?>>> s) >>>> [match.group("comment") for match in matches] > ['test', 'blah', 'difficult "One"'] > > In other words: The 'comment' group should preceded by be a negative > lookbehind (? anything (.*?). Not sure if ".*?" is a good idea, ie > zero-or-more-of-anything. I think a non-greedy match is sufficient; you don't need the look-behind: >>> s = "some enumeration 1 'test' 2 'blah' 3 'difficult \"One\"'." >>> matches = re.finditer("(?P['\"])(?P.*?)(?P=quote)", s) >>> [match.group("comment") for match in matches] ['test', 'blah', 'difficult "One"'] From steve at pearwood.info Tue Jun 11 14:59:21 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 11 Jun 2013 22:59:21 +1000 Subject: [Tutor] On a looping input, subsequent inputs are hidden In-Reply-To: References: Message-ID: <51B71F29.9030907@pearwood.info> On 11/06/13 16:17, Jim Mooney wrote: > This is puzzling me. I'm inputing an integer, giving a different > visual and audio alert depending if it's bad or good, and that works > fine. I'm looping input to ask for input again if a noninteger is > entered. That works. > > But the Second and subsequent inputs, in Windows, hide the input with > dots, while the first shows the input, and I can't figure out why. I'm afraid I don't understand what you mean. Second and subsequent inputs? I only see one. Hide the input with dots? Can you copy and paste an example? Further comments below. > I > don't change a thing between the first and subsequent calls to input > except changing the input message to an error message. But it's just > python input, not tkinter. Unless it's a Windows peculiarity. The > input Always shows in DOS. But if it doesn't show in Linux, let's say, > then I would guess it's a Python thing, and maybe there's a switch to > turn that effect off. For what it's worth, I cannot replicate this error. When I try your code on Linux, with a few minor adjustments to make it work (e.g. commenting out the winsound parts) it works fine for me. > ============ main program ====================== [snip code] > except (KeyboardInterrupt, EOFError): #1st Except for GUI, 2nd for > Cmd window > pop.popup('You cancelled, you so bad!') #string must contain > 'bad' to trigger audio > exit(0) What's exit()? Is that sys.exit? -- Steven From __peter__ at web.de Tue Jun 11 15:36:48 2013 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Jun 2013 15:36:48 +0200 Subject: [Tutor] On a looping input, subsequent inputs are hidden References: <51B71F29.9030907@pearwood.info> Message-ID: Steven D'Aprano wrote: > What's exit()? Is that sys.exit? One of those things a newbie finds out immediately, a veteran never ;) Since 2.5 site.py adds a Quitter object under the names "exit" and "quit" to Python's built-ins. They are meant to provide the accidental Python user with an obvious way to leave the interactive interpreter and /almost/ succeed: >>> exit Use exit() or Ctrl-D (i.e. EOF) to exit According to "[t]hey are useful for the interactive interpreter shell and should not be used in programs". From oscar.j.benjamin at gmail.com Tue Jun 11 16:21:57 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 11 Jun 2013 15:21:57 +0100 Subject: [Tutor] three numbers for one In-Reply-To: <51B66392.1030008@pearwood.info> References: <51B49DC3.1090003@pearwood.info> <51B66392.1030008@pearwood.info> Message-ID: On 11 June 2013 00:38, Steven D'Aprano wrote: > On 10/06/13 22:55, Oscar Benjamin wrote: > > With respect, it's not that you don't want or need them, but that you don't > *know* that you actually do want and need them. (I assume you are releasing > software for others to use. If all your software is private, for your own > use and nobody else, then you may not care.) Not all of it, but the bulk of my software is intended to be used only by me which obviously affects my attitude towards in a number of ways. > If your software accepts > numeric strings from the user -- perhaps it reads a file, perhaps it does > something like this: > > number = int(input("Please enter a number: ")) > > -- you want it to do the right thing when the user enters a number. Thanks > to the Internet, your program is available to people all over the world. > Well, in probably half the world, those digits are not necessarily the same > as ASCII 0-9. Somebody downloads your app in Japan, points it at a data file > containing fullwidth or halfwidth digits, and in Python 3 it just works. > (Provided, of course, that you don't sabotage its ability to do so with > inappropriate decimal only data validation.) What exactly are these? I tried looking for the HALFWIDTH DIGIT ZERO that you mentioned but I can't find it: >>> '\N{HALFWIDTH DIGIT ZERO}' File "", line 1 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-23: unknown Unicode character name I had thought that Japanese people just used Arabic numerals. I just looked at Japanese numerals on Wikipedia and found that there is also an alternative system but it is not strictly a base 10 scheme (like Roman numerals): http://en.wikipedia.org/wiki/Japanese_numerals http://en.wikipedia.org/wiki/List_of_CJK_Unified_Ideographs,_part_1_of_4 The int() function rejects these characters: O:\>py -3.3 Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> int('\u4e00') Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: '\u4e00' (Also the Japanese numerals page shows a character ? (kei) with a bigger numeric value than the ? (ch?) character that Eryksun referred to earlier). >> For example I very often pipe streams of ascii numeric text from one >> program to another. [snip] >> In some cases the cost of converting to/from >> decimal is actually significant and Python 3 will add to this both >> with a more complex conversion > > Let your mind be at rest on this account. Python 3.3 int() is nearly twice > as fast as Python 2.7 for short strings: > > [steve at ando ~]$ python2.7 -m timeit "int('12345')" > 1000000 loops, best of 3: 0.924 usec per loop > [steve at ando ~]$ python3.3 -m timeit "int('12345')" > 1000000 loops, best of 3: 0.485 usec per loop This is not really the appropriate test for what I was talking about. [snip] > > and in any case, the time taken to convert to a string is trivial. > >> and with its encoding/decoding part of >> the io stack. I'm wondering whether I should really just be using >> binary mode for this kind of thing in Python 3 since this at least >> removes an unnecessary part of the stack. > > I'm thinking that you're engaging in premature optimization. Have you > profiled your code to confirm that the bottlenecks are where you think they > are? No, I haven't since I'm not properly using Python 3 yet. However I have in the past profiled slow scripts running with Python 2 and found that in some cases binary/decimal conversion for input/output seemed to be a significant part of the time cost. The standard fix that I use (if it's worth it) is to read and write in binary using numpy.ndarray.tofile and numpy.fromfile. These are raw read/write operations to/from a block of memory using the OS file descriptor and are a lot faster. For small integers this can actually increase the total number of bytes transferred but still be significantly faster. I assume this is because it cuts out binary/decimal conversion and bypasses the Python io stack. To give a more appropriate measure of what I mean (On Windows XP): enojb at ENM-OB:/o$ cat gen.py #!/usr/bin/env python from __future__ import print_function import sys # For a fair comparison: try: from itertools import imap as map except ImportError: pass try: range = xrange except NameError: pass numlines = int(sys.argv[1]) for n in range(1, numlines + 1): print(' '.join(map(str, range(n, 10*n, n)))) enojb at ENM-OB:/o$ time py -2.7 gen.py 300000 > dump real 0m6.860s user 0m0.015s sys 0m0.015s enojb at ENM-OB:/o$ time py -2.7 gen.py 300000 > dump real 0m6.891s user 0m0.015s sys 0m0.000s enojb at ENM-OB:/o$ time py -3.2 gen.py 300000 > dump real 0m8.016s user 0m0.015s sys 0m0.031s enojb at ENM-OB:/o$ time py -3.2 gen.py 300000 > dump real 0m7.953s user 0m0.015s sys 0m0.000s enojb at ENM-OB:/o$ time py -3.3 gen.py 300000 > dump real 0m9.109s user 0m0.015s sys 0m0.015s enojb at ENM-OB:/o$ time py -3.3 gen.py 300000 > dump real 0m9.063s user 0m0.015s sys 0m0.015s So Python 3.3 is 30% slower than Python 2.7 in this benchmark. That's not a show-stopper but it's something to think about in a long-running script. I can recover Python 2.7 performance by manually encoding as ascii and writing directly to sys.stdout.buffer: enojb at ENM-OB:/o$ cat genb.py #!/usr/bin/env python import sys numlines = int(sys.argv[1]) for n in range(1, numlines + 1): line = ' '.join(map(str, range(n, 10*n, n))).encode() + b'\r\n' sys.stdout.buffer.write(line) enojb at ENM-OB:/o$ time py -3.3 genb.py 300000 > dumpb real 0m6.829s user 0m0.031s sys 0m0.000s enojb at ENM-OB:/o$ time py -3.3 genb.py 300000 > dumpb real 0m6.890s user 0m0.031s sys 0m0.000s enojb at ENM-OB:/o$ diff -qs dump dumpb Files dump and dumpb are identical >> In a previous thread where I moaned about the behaviour of the int() >> function Eryksun suggested that it would be better if int() wan't used >> for parsing strings at all. Since then I've thought about that and I >> agree. There should be separate functions for each kind of string to >> number conversion with one just for ascii decimal only. > > I think that is a terrible, terrible idea. It moves responsibility for > something absolutely trivial ("convert a string to a number") from the > language to the programmer, *who will get it wrong*. That's the point though. Converting a piece of text to a corresponding number is *not* trivial and there is no unique way that it should work. So I think that there should be appropriately named functions that perform the different types of conversion: int.fromdecimal, int.fromhex, int.fromasciidigits (or something like that). I don't think that int() should be used to convert strings and if it does then it should only be to invert str(a) where a is an integer. Oscar From eryksun at gmail.com Tue Jun 11 18:38:56 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 11 Jun 2013 12:38:56 -0400 Subject: [Tutor] three numbers for one In-Reply-To: References: <51B49DC3.1090003@pearwood.info> <51B66392.1030008@pearwood.info> Message-ID: On Tue, Jun 11, 2013 at 10:21 AM, Oscar Benjamin wrote: > What exactly are these? I tried looking for the HALFWIDTH DIGIT ZERO > that you mentioned but I can't find it: CJK typesetting uses the FULLWIDTH block for the ASCII range 0x21-0x7E: >>> '\N{FULLWIDTH DIGIT ONE}\N{FULLWIDTH DIGIT ZERO}' '??' >>> int('\N{FULLWIDTH DIGIT ONE}\N{FULLWIDTH DIGIT ZERO}') 10 http://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms I'm pretty sure the HALFWIDTH characters for Katakana and Hangul are used in combination with ASCII 0x20-0x7E. >>>> int('\u4e00') > Traceback (most recent call last): > File "", line 1, in > ValueError: invalid literal for int() with base 10: '\u4e00' int() requires a decimal string. The ideograph U+4e00 is only numeric: >>> '\u4e00'.isdecimal() False >>> '\u4e00'.isdigit() False >>> unicodedata.numeric('\u4e00') 1.0 > (Also the Japanese numerals page shows a character ? (kei) with a > bigger numeric value than the ? (ch?) character that Eryksun referred > to earlier). The Unicode database doesn't list ? (U+4EAC) as numeric. http://www.unicode.org/cgi-bin/GetUnihanData.pl?codepoint=4EAC It's primary definition is capital city, with a secondary meaning of 1e16. If you follow the links in wiktionary you'll find ideographs for even larger values such as 1e20, 1e24, and so on (grouped by 10,000). http://en.wiktionary.org/wiki/%E4%BA%AC I think in context it can refer to Beijing or Kyoto, but when combined with "?" (metropolis), it's the proper name for Kyoto: In Japanese, the city has been called Ky? (?), Miyako (?) or Ky? no Miyako (???). In the 11th century, the city was renamed Kyoto ("capital city"), after the Chinese word for capital city, jingdu (??). After Edo was renamed Tokyo (meaning "Eastern Capital") in 1868, Kyoto was known for a short time as Saiky? (??, meaning "Western Capital"). From eryksun at gmail.com Tue Jun 11 18:55:12 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 11 Jun 2013 12:55:12 -0400 Subject: [Tutor] On a looping input, subsequent inputs are hidden In-Reply-To: References: Message-ID: On Tue, Jun 11, 2013 at 2:17 AM, Jim Mooney wrote: > > But the Second and subsequent inputs, in Windows, hide the input with > dots, while the first shows the input, and I can't figure out why. I > don't change a thing between the first and subsequent calls to input > except changing the input message to an error message. I don't understand what you mean by "hide the input with dots". Are you running in a plain console window? (i.e. not IPython Qt console, or Console2, or ConEmu -- let's keep it basic.) Please paste the output in a reply, so everyone can see what you're describing here. > Sorry,that's not an integer. Try again or Cancel by > using Cancel in a GUI window, or Ctrl-Z in DOS. > or Ctrl-C in Linux. One mo try. Type an integer: ''' > except (KeyboardInterrupt, EOFError): > #1st Except for GUI, 2nd for Cmd window By GUI window do you mean an IDE? You should be able to reliably use Ctrl-C with input() in a Windows console. Issue 17619 was resolved in 3.3.2: http://docs.python.org/release/3.3.2/whatsnew/changelog.html P.S. You're running Windows, not DOS. The Windows console is a character-cell window, but otherwise console applications are regular Windows programs. In a GUI app you can even open a console with kernel32 AllocConsole() and open CONIN$ and CONOUT$ for standard I/O. From cybervigilante at gmail.com Tue Jun 11 19:53:54 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 11 Jun 2013 10:53:54 -0700 Subject: [Tutor] On a looping input, subsequent inputs are hidden In-Reply-To: References: Message-ID: On 11 June 2013 01:07, Alan Gauld wrote: > > First you are effectively creating an entire Tkinter app > inside popup() each time. That's a pretty heavyweight way > to generate a messagebox. Have you used the Tkinter > standard message dialogs? > Argh - dumb error. Thanks for pointing that out and to all other commenters. Much useful info. Back to the drawing board. By the time I fix it all, the error will probably disappear of its own accord since it didn't appear on some simple testing of the error by itself. And since it didn't appear in Linux, which I don't have, it may be a windows-only response I can get around by changing the code a bit. But I do like the idea of using plain old words, like "bad" as a switch, instead of some inscrutable program-switch ;') Jim Jim From cybervigilante at gmail.com Tue Jun 11 20:16:06 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 11 Jun 2013 11:16:06 -0700 Subject: [Tutor] On a looping input, subsequent inputs are hidden In-Reply-To: References: Message-ID: >> First you are effectively creating an entire Tkinter app >> inside popup() each time. Actually, that was the source of the error. When I put the app creation above the function, the dots no longer appeared. As to why, I'm not even going to try to figure that out ;') -- Jim Today is the day that would have been tomorrow if yesterday was today From cybervigilante at gmail.com Tue Jun 11 20:33:26 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 11 Jun 2013 11:33:26 -0700 Subject: [Tutor] On a looping input, subsequent inputs are hidden In-Reply-To: References: Message-ID: On 11 June 2013 01:07, Alan Gauld wrote: > First you are effectively creating an entire Tkinter app > inside popup() each time. I partially mis-spoke myself. The error was not caused Just by creating the app every time, but very oddly, by the Combination of recreating the app and using triple quote docstrings to change the error message in the duplicate app. Good Lord, nothing worse than a problem caused by two different things ;') -- Jim Today is the day that would have been tomorrow if yesterday was today From oscar.j.benjamin at gmail.com Tue Jun 11 22:32:24 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 11 Jun 2013 21:32:24 +0100 Subject: [Tutor] producing PDF files In-Reply-To: References: Message-ID: On 11 June 2013 10:53, Khalid Al-Ghamdi wrote: > > Do you know of a python module for converting text files to PDF format? > Why does it have to be a Python module? What do you mean by converting a text file to a pdf file? If I just wanted to create a pdf file containing some verbatim text I would probably use LaTeX. That's not a Python module but you can invoke it easily enough from Python as an external program. Oscar From francois.dion at gmail.com Tue Jun 11 22:42:11 2013 From: francois.dion at gmail.com (Francois Dion) Date: Tue, 11 Jun 2013 16:42:11 -0400 Subject: [Tutor] producing PDF files In-Reply-To: References: Message-ID: http://www.xhtml2pdf.com/ Started life as pisa. Very easy to work with. Francois -- www.pyptug.org - raspberry-python.blogspot.com - @f_dion On Tue, Jun 11, 2013 at 5:53 AM, Khalid Al-Ghamdi wrote: > Hi, > > Do you know of a python module for converting text files to PDF format? > > thanks > > _______________________________________________ > 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 eryksun at gmail.com Wed Jun 12 02:16:35 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 11 Jun 2013 20:16:35 -0400 Subject: [Tutor] On a looping input, subsequent inputs are hidden In-Reply-To: References: Message-ID: On Tue, Jun 11, 2013 at 2:33 PM, Jim Mooney wrote: > On 11 June 2013 01:07, Alan Gauld wrote: > >> First you are effectively creating an entire Tkinter app >> inside popup() each time. > > I partially mis-spoke myself. The error was not caused Just by > creating the app every time, but very oddly, by the Combination of > recreating the app and using triple quote docstrings to change the > error message in the duplicate app. Good Lord, nothing worse than a > problem caused by two different things ;') I wasn't able to reproduce the problem in Python 3.3.2 on Windows. It ran as I expected it to run. Note that triple quoted strings retain the indentation level. At runtime you cam use textwrap.dedent: >>> s = '''\ ... comfy ... chair''' >>> print(s) comfy chair >>> print(textwrap.dedent(s)) comfy chair From steve at pearwood.info Wed Jun 12 04:19:57 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 12 Jun 2013 12:19:57 +1000 Subject: [Tutor] On a looping input, subsequent inputs are hidden In-Reply-To: References: Message-ID: <51B7DACD.1080000@pearwood.info> On 12/06/13 03:53, Jim Mooney wrote: > But I do like the idea of using plain old words, like "bad" as a > switch, instead of some inscrutable program-switch ;') I don't. Trust me on this, you will regret it. As the Zen of Python says, "Explicit is better than implicit". It may seem like a good idea now, but some day you'll write code like this: def reward(msg): print(msg) if 'link' in msg: administer_electric_shock() else: give_cake() def administer_test(username): score = 0 for question, answer in list_of_tests: response = input(question) if response == answer: score += 1 if score > len(list_of_tests): msg = "Congratulations %s, you have passed!" % username else: msg = "%s, you are the weakest link!" % username reward(msg) Can you see the bug? -- Steven From dragondon at dragondon.net Wed Jun 12 06:24:07 2013 From: dragondon at dragondon.net (DragonDon) Date: Wed, 12 Jun 2013 13:24:07 +0900 Subject: [Tutor] Creating a Choose Your Own Adventure Game Message-ID: Greetings all! I've been studying Python for just over a month and got onto the idea of creating a 'choose your own adventure' type of game. learnpythonthehardway.org had some influence in that :) If possible, I would love some feedback on it. Right now it's at v2 and I'm currently working on v3. It is built using 2.7 and is purely a console/text adventure right now (pretty graphics will come after). It is also an adult game as there is occasional sexual innuendo(but never anything graphic) and some swearing so if you do check it out, please keep that in mind. I have it posted for all to view and comment on my blog. http://cosmopolitangeek.wordpress.com Thanks in advance! DragonDon -------------- next part -------------- An HTML attachment was scrubbed... URL: From paradox at pobox.com Wed Jun 12 06:59:48 2013 From: paradox at pobox.com (Paradox) Date: Wed, 12 Jun 2013 12:59:48 +0800 Subject: [Tutor] Creating a Choose Your Own Adventure Game :p: In-Reply-To: References: Message-ID: <51B80044.8060906@pobox.com> >On 06/12/2013 12:24 PM, DragonDon wrote: >http://cosmopolitangeek.wordpress.com Dragon Don, I will check this out but I wonder if you have ever heard of git or mercurial? Putting code for small projects up on github or bitbucket is very simple and makes the sharing, updating, etc. easier. Also using a DVCS allows for rollbacks, updates, incorporating other people's changes, etc. github: github.com Bitbucket: bitbucket.org. thomas From breamoreboy at yahoo.co.uk Wed Jun 12 09:46:23 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Jun 2013 08:46:23 +0100 Subject: [Tutor] [OT]Death of VMS Message-ID: I figured some of the folks out there who appreciate real operating systems might be interested in this http://www.theregister.co.uk/2013/06/10/openvms_death_notice/ -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From dragondon at dragondon.net Wed Jun 12 09:50:25 2013 From: dragondon at dragondon.net (DragonDon) Date: Wed, 12 Jun 2013 16:50:25 +0900 Subject: [Tutor] Creating a Choose Your Own Adventure Game :p: In-Reply-To: <51B80044.8060906@pobox.com> References: <51B80044.8060906@pobox.com> Message-ID: Thanks for the info Thomas. I have heard of github but not bitbucket. I have tried PyPI once from another book(HeadFirst series) but never went further. I don't even know yet if this is something worthy of making available to a broader audience. Outside of my blog and a few select other people, this is my first foray into a more public 'court of opinion' if you will. If I find there is enough interest/feedback to make this a decent bit of code, I'll put it up somewhere I think. DragonDon On Wed, Jun 12, 2013 at 1:59 PM, Paradox wrote: > >On 06/12/2013 12:24 PM, DragonDon wrote: > >http://cosmopolitangeek.**wordpress.com< > http://cosmopolitangeek.**wordpress.com > > > > Dragon Don, > > I will check this out but I wonder if you have ever heard of git or > mercurial? Putting code for small projects up on github or bitbucket is > very simple and makes the sharing, updating, etc. easier. Also using a > DVCS allows for rollbacks, updates, incorporating other people's changes, > etc. > > github: github.com > Bitbucket: bitbucket.org. > > thomas > > ______________________________**_________________ > 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 emailkgnow at gmail.com Wed Jun 12 11:32:22 2013 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Wed, 12 Jun 2013 12:32:22 +0300 Subject: [Tutor] Using __init__ to return a value Message-ID: Hi, Why doesn't this work? And is there way to have an object immediately return a value or object once it is instantiated with using a method call? 1. >>> class k: 2. def __init__(self,n): 3. return n*n 4. 5. 6. >>> khalid=k(3) 7. Traceback (most recent call last): 8. File "", line 1, in 9. khalid=k(3) 10. TypeError: __init__() should return None, not 'int' -------------- next part -------------- An HTML attachment was scrubbed... URL: From dextrous85 at gmail.com Wed Jun 12 11:47:26 2013 From: dextrous85 at gmail.com (vishwajeet singh) Date: Wed, 12 Jun 2013 15:17:26 +0530 Subject: [Tutor] Using __init__ to return a value In-Reply-To: References: Message-ID: On Wed, Jun 12, 2013 at 3:02 PM, Khalid Al-Ghamdi wrote: > Hi, > > Why doesn't this work? And is there way to have an > object immediately return a value or object once it is instantiated with > using a method call? > __init__ returns the newly created object. You cannot (or at least shouldn't) return something else. Try making whatever you want to return an instance variable (or function). Refer this thread http://stackoverflow.com/questions/2491819/python-init-how-to-return-a-value > > 1. >>> class k: > 2. def __init__(self,n): > 3. return n*n > 4. > 5. > 6. >>> khalid=k(3) > 7. Traceback (most recent call last): > 8. File "", line 1, in > 9. khalid=k(3) > 10. TypeError: __init__() should return None, not 'int' > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Vishwajeet Singh +91-9657702154 | dextrous85 at gmail.com | http://bootstraptoday.com Twitter: http://twitter.com/vishwajeets | LinkedIn: http://www.linkedin.com/in/singhvishwajeet -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Jun 12 12:03:35 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 Jun 2013 12:03:35 +0200 Subject: [Tutor] Using __init__ to return a value References: Message-ID: Khalid Al-Ghamdi wrote: > 1. >>> class k: > 2. def __init__(self,n): > 3. return n*n > 4. > 5. > 6. >>> khalid=k(3) > 7. Traceback (most recent call last): > 8. File "", line 1, in > 9. khalid=k(3) > 10. TypeError: __init__() should return None, not 'int' > Why doesn't this work? Leaving out the details, for a class A a = A(...) is essentially a shortcut for a = A.__new__(A, ...) a.__init__(...) __new__(), not __init__() determines what value is bound to the name a. > And is there way to have an > object immediately return a value or object once it is instantiated with > using a method call? You can write your own implementation of __new__(), but that is expert area and hardly ever needed. When you aren't interested in the class instance you shouldn't create one in the first place, and use a function instead: def k(n): return n*n khalid = k(3) From steve at pearwood.info Wed Jun 12 13:42:44 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 12 Jun 2013 21:42:44 +1000 Subject: [Tutor] Using __init__ to return a value In-Reply-To: References: Message-ID: <51B85EB4.6080003@pearwood.info> On 12/06/13 19:32, Khalid Al-Ghamdi wrote: > Hi, > > Why doesn't this work? And is there way to have an > object immediately return a value or object once it is instantiated with > using a method call? It does return a value. It returns the object that was just instantiated. Supposed you could do what you wanted: > 1. >>> class k: > 2. def __init__(self,n): > 3. return n*n > 4. > 5. > 6. >>> khalid=k(3) and khalid receives the value 9. That would be useless, because the instance of class K would be immediately destroyed. If you want to just return a value, use a function. This is the best solution: def k(n): return n*n khalid = k(3) assert khalid == 9 Another alternative is to create a callable object: class K: def __init__(self, n): self.n = n def __call__(self, arg): return arg * self.n k = K(3) k(2) => returns 6 k(5) => returns 15 A third alternative is to use the __new__ method. This only works in Python 3, or for new-style classes that inherit from object: class K(object): def __new__(cls, n): return n*n but don't do this. Really, don't. There are advanced uses where this is useful, but for this trivial example, you should just use a function. -- Steven From bjames at Jamesgang.dyndns.org Wed Jun 12 17:18:27 2013 From: bjames at Jamesgang.dyndns.org (bjames at Jamesgang.dyndns.org) Date: Wed, 12 Jun 2013 10:18:27 -0500 Subject: [Tutor] First program after PyCamp In-Reply-To: References: <7eea23564907a4a049d861fe3b278c66.squirrel@jamesgang.dyndns.org> <51B64F86.1000505@davea.name> <9ca16f999bfdf07bda034f3a05647ea5.squirrel@jamesgang.dyndns.org> Message-ID: <649f72ece08bd8f9bc009b63337bb9be.squirrel@jamesgang.dyndns.org> I've updated this code and to make it more easily readible put it in a github repo https://github.com/CyberCowboy/FindDuplicates Everything is working, however the code is hard to read and I'll be working on cleaning that up, as well as splitting the program into 3 different functions (one that gets hashes, one that finds and identifies the duplicates, and one that outputs the results) However I'm having a problem in that if during the hashing faze a filename with non-ascii characters is encountered the file errors out. Since this is going to be used at work and we have a large number of Chinese and Arabic filenames I need to have the search allow a unicode character set. How would I go about doing this? From bjames at Jamesgang.dyndns.org Wed Jun 12 17:18:39 2013 From: bjames at Jamesgang.dyndns.org (bjames at Jamesgang.dyndns.org) Date: Wed, 12 Jun 2013 10:18:39 -0500 Subject: [Tutor] First program after PyCamp In-Reply-To: References: <7eea23564907a4a049d861fe3b278c66.squirrel@jamesgang.dyndns.org> <51B64F86.1000505@davea.name> <9ca16f999bfdf07bda034f3a05647ea5.squirrel@jamesgang.dyndns.org> Message-ID: <73df5d000561ef05eb0443e65f4d9f29.squirrel@jamesgang.dyndns.org> I've updated this code and to make it more easily readible put it in a github repo https://github.com/CyberCowboy/FindDuplicates Everything is working, however the code is hard to read and I'll be working on cleaning that up, as well as splitting the program into 3 different functions (one that gets hashes, one that finds and identifies the duplicates, and one that outputs the results) However I'm having a problem in that if during the hashing faze a filename with non-ascii characters is encountered the file errors out. Since this is going to be used at work and we have a large number of Chinese and Arabic filenames I need to have the search allow a unicode character set. How would I go about doing this? Python 2.7 btw. From cybervigilante at gmail.com Wed Jun 12 20:15:56 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 12 Jun 2013 11:15:56 -0700 Subject: [Tutor] On a looping input, subsequent inputs are hidden In-Reply-To: <51B7DACD.1080000@pearwood.info> References: <51B7DACD.1080000@pearwood.info> Message-ID: I guess that would be hard on Ben Flinkelstein ;') But I guess I could still have give_cake = True to be more understandable. Or keep the program the way it is, use if '' in msg , and sell it to Guantanamo. Jim On 11 June 2013 19:19, Steven D'Aprano wrote: > On 12/06/13 03:53, Jim Mooney wrote: > > But I do like the idea of using plain old words, like "bad" as a >> switch, instead of some inscrutable program-switch ;') >> > > > I don't. Trust me on this, you will regret it. As the Zen of Python says, > "Explicit is better than implicit". It may seem like a good idea now, but > some day you'll write code like this: > > > def reward(msg): > print(msg) > if 'link' in msg: > administer_electric_shock() > else: > give_cake() > > > def administer_test(username): > score = 0 > for question, answer in list_of_tests: > response = input(question) > if response == answer: > score += 1 > if score > len(list_of_tests): > msg = "Congratulations %s, you have passed!" % username > else: > msg = "%s, you are the weakest link!" % username > reward(msg) > > > Can you see the bug? > > > > > > -- > Steven > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Jim Today is the day that would have been tomorrow if yesterday was today -------------- next part -------------- An HTML attachment was scrubbed... URL: From cbc at unc.edu Wed Jun 12 20:39:02 2013 From: cbc at unc.edu (Chris Calloway) Date: Wed, 12 Jun 2013 14:39:02 -0400 Subject: [Tutor] First program after PyCamp In-Reply-To: <73df5d000561ef05eb0443e65f4d9f29.squirrel@jamesgang.dyndns.org> References: <7eea23564907a4a049d861fe3b278c66.squirrel@jamesgang.dyndns.org> <51B64F86.1000505@davea.name> <9ca16f999bfdf07bda034f3a05647ea5.squirrel@jamesgang.dyndns.org> <73df5d000561ef05eb0443e65f4d9f29.squirrel@jamesgang.dyndns.org> Message-ID: <51B8C046.7030606@unc.edu> On 6/12/2013 11:18 AM, bjames at Jamesgang.dyndns.org wrote: > I've updated this code and to make it more easily readible put it in a > github repo https://github.com/CyberCowboy/FindDuplicates > > Everything is working, however the code is hard to read and I'll be > working on cleaning that up, as well as splitting the program into 3 > different functions (one that gets hashes, one that finds and identifies > the duplicates, and one that outputs the results) > > However I'm having a problem in that if during the hashing faze a filename > with non-ascii characters is encountered the file errors out. Since this > is going to be used at work and we have a large number of Chinese and > Arabic filenames I need to have the search allow a unicode character set. > How would I go about doing this? Python 2.7 btw. Feed os.walk a unicode path and you'll get unicode filenames back. -- Sincerely, Chris Calloway http://nccoos.org/Members/cbc office: 3313 Venable Hall phone: (919) 599-3530 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From cybervigilante at gmail.com Wed Jun 12 22:49:26 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 12 Jun 2013 13:49:26 -0700 Subject: [Tutor] Value Error Message-ID: I'm going through the exceptions so I can recall and use the basic ones (not much use for unicode errors at this point ;') But I'm puzzled by an aspect of the Value Error: *exception *ValueError Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError . I know you can bring this error up easily with a wrong user input, but within a program, what would be an example of something that is the "right type but an inappropriate value"? -- Jim A noun is just a verb with the hiccups -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Wed Jun 12 23:06:57 2013 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 12 Jun 2013 23:06:57 +0200 Subject: [Tutor] Value Error In-Reply-To: References: Message-ID: <51B8E2F1.4070201@gmail.com> On 06/12/2013 10:49 PM, Jim Mooney wrote: > Raised when a built-in operation or function receives an argument that has > the right type but an inappropriate value, and the situation is not > described by a more precise exception such as > IndexError You get this when the function gets the right object but the value of that object is not correct. For example int() will attempt to create an integer object from a string object. However if that string is not a number represented as a sting you run into a ValueError. int('test') Traceback (most recent call last): File "", line 1, in int('test') ValueError: invalid literal for int() with base 10: 'test' When we give it the string representation of 123 int() will convert the string to an integer. int('123') 123 ~Sander From davea at davea.name Wed Jun 12 23:19:20 2013 From: davea at davea.name (Dave Angel) Date: Wed, 12 Jun 2013 17:19:20 -0400 Subject: [Tutor] Value Error In-Reply-To: References: Message-ID: <51B8E5D8.1030407@davea.name> On 06/12/2013 04:49 PM, Jim Mooney wrote: > I'm going through the exceptions so I can recall and use the basic ones > (not much use for unicode errors at this point ;') But I'm puzzled by an > aspect of the Value Error: > *exception *ValueError > > Raised when a built-in operation or function receives an argument that has > the right type but an inappropriate value, and the situation is not > described by a more precise exception such as > IndexError > . > > I know you can bring this error up easily with a wrong user input, but > within a program, what would be an example of something that is the "right > type but an inappropriate value"? > > import math print math.sqrt(-1) From md123 at nycap.rr.com Wed Jun 12 23:32:41 2013 From: md123 at nycap.rr.com (Matt D) Date: Wed, 12 Jun 2013 17:32:41 -0400 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B28759.60201@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> Message-ID: <51B8E8F9.2030206@nycap.rr.com> On 06/10/2013 12:23 PM, Prasad, Ramit wrote: > Matt D wrote: >> Ramit Prasad wrote: >>>>> Scrolled panel is just a graphical container that allows for scrolling inside, >>>>> but it is the window that scrolls not widgets inside it. This of it like >>>>> a webpage that scrolls. If you use web email the text widget in the >>>>> email needs to scroll so you can see your full email context and not >>>>> just scroll the page. >>>>> >>>>> You will probably need to create a TextCtrl with the appropriate style >>>>> and append your new data. I have given an example below that should >>>>> automatically scroll with your new data. >>>>> >>>>> #in __init__ >>>>> self.scrolling_widget = wx.TextCtrl( self, wx.ID_ANY, '', size=(-1, 275), >>>> style=wx.TE_AUTO_SCROLL|wx.TE_READONLY|wx.TE_PROCESS_ENTER|wx.TE_WORDWRAP|wx.TE_MULTILINE ) >>>>> >> Hey, >> I added this the above 3 lines of code to my file and ran it. the box >> shows up on the far left, mostly of the pane, to the left of the current >> text feilds. I am having trouble positioning this textbox under where >> the current text fields are. >> I am not sure but maybe this sets up the grid on the pane: >> sizer = wx.GridBagSizer(hgap=10, vgap=10) >> self.fields = {} >> all the current TextCtrl fields are positioned at (1,1) through (5,5). >> I tried adding: >> sizer.Add(field, pos=(1,6)) >> but it did not move the box to the position? > > Just to make sure, you did call it field and not self.scrolling_widget > (which was in my example)? > > Odd that they don't start at (0,0) when adding to the bag. This is > more a wxpython question and their mailing list might prove more > useful. I could figure it out, but I cannot run the app. Trial > and error here will probably help you the most. You can also > try looking at a different sizer (like BoxSizer and GridSizer). > > Personally, I think BoxSizer is the most intuitive as it matches > my thought process. You just set an orientation (vertical/horizontal) > and add widgets to it. To get something in the other direction, you > create another box sizer with the opposite orientation, add widgets > to that sizer, and then add the new sizer to the original sizer. Not > nearly as pretty as grid/grid bag though (by default), but super simple. > > BoxSizer API > http://wxpython.org/docs/api/wx.BoxSizer-class.html > Some other sizers are listed here: > http://wxpython.org/docs/api/wx.Sizer-class.html > >> >> THanks, >> Matt > > Hey, if i put: self.logfile = open('logfile.csv', 'w') in the .py file, within the 'class TrafficPane', then shouldn't logfile.csv be written to the directory the .py file is in? because its not there after running the program? Where should i look for it? Thanks Matt From cybervigilante at gmail.com Wed Jun 12 23:41:39 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 12 Jun 2013 14:41:39 -0700 Subject: [Tutor] Value Error In-Reply-To: <51B8E5D8.1030407@davea.name> References: <51B8E5D8.1030407@davea.name> Message-ID: Dave Angel import math > print math.sqrt(-1) Ah, that's what I was looking for. I already saw it trip on type mismatches like int('blah'). I was looking for what would be an actual inappropriate value that was still the right type. Although I'm not sure why int('blah') wouldn't be a type error rather than a value error. Jim > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Wed Jun 12 23:16:12 2013 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 12 Jun 2013 14:16:12 -0700 Subject: [Tutor] Value Error In-Reply-To: <51B8E2F1.4070201@gmail.com> References: <51B8E2F1.4070201@gmail.com> Message-ID: <9854C44E-F0D8-4778-A124-92AD46CA00BB@alchemy.com> or if you try to take the square root of a negative number, etc. On 12-Jun-2013, at 14:06, Sander Sweers wrote: > On 06/12/2013 10:49 PM, Jim Mooney wrote: >> Raised when a built-in operation or function receives an argument that has >> the right type but an inappropriate value, and the situation is not >> described by a more precise exception such as >> IndexError > > You get this when the function gets the right object but the value of > that object is not correct. For example int() will attempt to create an > integer object from a string object. However if that string is not a > number represented as a sting you run into a ValueError. > > int('test') > > Traceback (most recent call last): > File "", line 1, in > int('test') > ValueError: invalid literal for int() with base 10: 'test' > > When we give it the string representation of 123 int() will convert the > string to an integer. > > int('123') > 123 > > ~Sander > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at alchemy.com Wed Jun 12 23:46:56 2013 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 12 Jun 2013 14:46:56 -0700 Subject: [Tutor] Value Error In-Reply-To: References: <51B8E5D8.1030407@davea.name> Message-ID: int('blah') is not a type error because the int() function is expecting to be given a string, and it was given a string. The 'blah' is of the correct type. The problem is that int() couldn't do anything useful with the value of that string. Steve On 12-Jun-2013, at 14:41, Jim Mooney wrote: > Dave Angel > > import math > print math.sqrt(-1) > > Ah, that's what I was looking for. I already saw it trip on type mismatches like int('blah'). I was looking for what would be an actual inappropriate value that was still the right type. Although I'm not sure why int('blah') wouldn't be a type error rather than a value error. > > Jim > > > _______________________________________________ > 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 roel at roelschroeven.net Wed Jun 12 23:49:50 2013 From: roel at roelschroeven.net (Roel Schroeven) Date: Wed, 12 Jun 2013 23:49:50 +0200 Subject: [Tutor] Value Error In-Reply-To: References: <51B8E5D8.1030407@davea.name> Message-ID: Jim Mooney schreef: > Although I'm not sure why int('blah') wouldn't be a type error rather > than a value error. Because passing a string to int() is perfectly okay, as long as the string has an appropriate value: int('42') works, int('forty two') raises ValueError. -- "People almost invariably arrive at their beliefs not on the basis of proof but on the basis of what they find attractive." -- Pascal Blaise roel at roelschroeven.net From davea at davea.name Wed Jun 12 23:59:47 2013 From: davea at davea.name (Dave Angel) Date: Wed, 12 Jun 2013 17:59:47 -0400 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B8E8F9.2030206@nycap.rr.com> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B28759.60201@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> <51B8E8F9.2030206@nycap.rr.com> Message-ID: <51B8EF53.7030201@davea.name> On 06/12/2013 05:32 PM, Matt D wrote: > On 06/10/2013 12:23 PM, Prasad, Ramit wrote: >> Matt D wrote: >>> Ramit Prasad wrote: >>>>>> Scrolled panel is just a graphical container that allows for scrolling inside, >>>>>> but it is the window that scrolls not widgets inside it. This of it like >>>>>> a webpage that scrolls. If you use web email the text widget in the >>>>>> email needs to scroll so you can see your full email context and not >>>>>> just scroll the page. >>>>>> >>>>>> You will probably need to create a TextCtrl with the appropriate style >>>>>> and append your new data. I have given an example below that should >>>>>> automatically scroll with your new data. >>>>>> >>>>>> #in __init__ >>>>>> self.scrolling_widget = wx.TextCtrl( self, wx.ID_ANY, '', size=(-1, 275), >>>>> style=wx.TE_AUTO_SCROLL|wx.TE_READONLY|wx.TE_PROCESS_ENTER|wx.TE_WORDWRAP|wx.TE_MULTILINE ) >>>>>> >>> Hey, >>> I added this the above 3 lines of code to my file and ran it. the box >>> shows up on the far left, mostly of the pane, to the left of the current >>> text feilds. I am having trouble positioning this textbox under where >>> the current text fields are. >>> I am not sure but maybe this sets up the grid on the pane: >>> sizer = wx.GridBagSizer(hgap=10, vgap=10) >>> self.fields = {} >>> all the current TextCtrl fields are positioned at (1,1) through (5,5). >>> I tried adding: >>> sizer.Add(field, pos=(1,6)) >>> but it did not move the box to the position? >> >> Just to make sure, you did call it field and not self.scrolling_widget >> (which was in my example)? >> >> Odd that they don't start at (0,0) when adding to the bag. This is >> more a wxpython question and their mailing list might prove more >> useful. I could figure it out, but I cannot run the app. Trial >> and error here will probably help you the most. You can also >> try looking at a different sizer (like BoxSizer and GridSizer). >> >> Personally, I think BoxSizer is the most intuitive as it matches >> my thought process. You just set an orientation (vertical/horizontal) >> and add widgets to it. To get something in the other direction, you >> create another box sizer with the opposite orientation, add widgets >> to that sizer, and then add the new sizer to the original sizer. Not >> nearly as pretty as grid/grid bag though (by default), but super simple. >> >> BoxSizer API >> http://wxpython.org/docs/api/wx.BoxSizer-class.html >> Some other sizers are listed here: >> http://wxpython.org/docs/api/wx.Sizer-class.html >> >>> >>> THanks, >>> Matt >> >> > Hey, > if i put: > > self.logfile = open('logfile.csv', 'w') > > in the .py file, within the 'class TrafficPane', then shouldn't > logfile.csv be written to the directory the .py file is in? because its > not there after running the program? Where should i look for it? > Thanks > Matt > It should put it in the current directory. That *may* be the directory the script is in, but not necessarily. It's easy to run something like: python somdir/myscript.py in which case the file would be in the parent directory to myscript.py Note that in some environments, the current directory is invisibly set to some convenient place. For example, when right-clicking on a script in Windows Explorer, they make the bald assumption that you want to set the current directory the same as the location of the script. That's about the worse place for it, but nevermind. -- DaveA From cybervigilante at gmail.com Thu Jun 13 00:07:15 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 12 Jun 2013 15:07:15 -0700 Subject: [Tutor] Value Error In-Reply-To: <9854C44E-F0D8-4778-A124-92AD46CA00BB@alchemy.com> References: <51B8E2F1.4070201@gmail.com> <9854C44E-F0D8-4778-A124-92AD46CA00BB@alchemy.com> Message-ID: On 12 June 2013 14:16, Steve Willoughby wrote: > or if you try to take the square root of a negative number, etc. > Or the log of -10. Although sqrt(-1) works fine for cmath.sqrt(-1) - I think I get it. Come to think of it you can do cmath.log(-10), but that's getting scary ;') Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Jun 13 00:31:47 2013 From: davea at davea.name (Dave Angel) Date: Wed, 12 Jun 2013 18:31:47 -0400 Subject: [Tutor] Value Error In-Reply-To: References: <51B8E2F1.4070201@gmail.com> <9854C44E-F0D8-4778-A124-92AD46CA00BB@alchemy.com> Message-ID: <51B8F6D3.6000308@davea.name> On 06/12/2013 06:07 PM, Jim Mooney wrote: > On 12 June 2013 14:16, Steve Willoughby wrote: > >> or if you try to take the square root of a negative number, etc. >> > > Or the log of -10. Although sqrt(-1) works fine for cmath.sqrt(-1) - I > think I get it. > > Come to think of it you can do cmath.log(-10), but that's getting scary ;') > > Jim > >>> import math, cmath >>> i = complex(0,1) >>> math.sqrt((math.e **(i * math.pi)).real) Traceback (most recent call last): File "", line 1, in ValueError: math domain error >>> cmath.sqrt(float((math.e **(i * math.pi)).real)) 1j -- DaveA From marc.tompkins at gmail.com Thu Jun 13 02:08:58 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 12 Jun 2013 17:08:58 -0700 Subject: [Tutor] Value Error In-Reply-To: <51B8F6D3.6000308@davea.name> References: <51B8E2F1.4070201@gmail.com> <9854C44E-F0D8-4778-A124-92AD46CA00BB@alchemy.com> <51B8F6D3.6000308@davea.name> Message-ID: On Wed, Jun 12, 2013 at 3:31 PM, Dave Angel wrote: > >>> cmath.sqrt(float((math.e **(i * math.pi)).real)) > 1j > Sh*t just got real. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jun 13 02:35:38 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Jun 2013 01:35:38 +0100 Subject: [Tutor] Value Error In-Reply-To: References: <51B8E2F1.4070201@gmail.com> <9854C44E-F0D8-4778-A124-92AD46CA00BB@alchemy.com> <51B8F6D3.6000308@davea.name> Message-ID: On 13/06/13 01:08, Marc Tompkins wrote: > On Wed, Jun 12, 2013 at 3:31 PM, Dave Angel > wrote: > > >>> cmath.sqrt(float((math.e **(i * math.pi)).real)) > 1j > > Sh*t just got real. no, it's imaginary. :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From md123 at nycap.rr.com Thu Jun 13 02:46:22 2013 From: md123 at nycap.rr.com (Matt D) Date: Wed, 12 Jun 2013 20:46:22 -0400 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B8EF53.7030201@davea.name> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B28759.60201@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> <51B8E8F9.2030206@nycap.rr.com> <51B8EF53.7030201@davea.name> Message-ID: <51B9165E.3080305@nycap.rr.com> On 06/12/2013 05:59 PM, Dave Angel wrote: > On 06/12/2013 05:32 PM, Matt D wrote: >> On 06/10/2013 12:23 PM, Prasad, Ramit wrote: >>> Matt D wrote: >>>> Ramit Prasad wrote: >>>>>>> Scrolled panel is just a graphical container that allows for >>>>>>> scrolling inside, >>>>>>> but it is the window that scrolls not widgets inside it. This of >>>>>>> it like >>>>>>> a webpage that scrolls. If you use web email the text widget in the >>>>>>> email needs to scroll so you can see your full email context and not >>>>>>> just scroll the page. >>>>>>> >>>>>>> You will probably need to create a TextCtrl with the appropriate >>>>>>> style >>>>>>> and append your new data. I have given an example below that should >>>>>>> automatically scroll with your new data. >>>>>>> >>>>>>> #in __init__ >>>>>>> self.scrolling_widget = wx.TextCtrl( self, wx.ID_ANY, '', >>>>>>> size=(-1, 275), >>>>>> style=wx.TE_AUTO_SCROLL|wx.TE_READONLY|wx.TE_PROCESS_ENTER|wx.TE_WORDWRAP|wx.TE_MULTILINE >>>>>> ) >>>>>>> >>>> Hey, >>>> I added this the above 3 lines of code to my file and ran it. the box >>>> shows up on the far left, mostly of the pane, to the left of the >>>> current >>>> text feilds. I am having trouble positioning this textbox under where >>>> the current text fields are. >>>> I am not sure but maybe this sets up the grid on the pane: >>>> sizer = wx.GridBagSizer(hgap=10, vgap=10) >>>> self.fields = {} >>>> all the current TextCtrl fields are positioned at (1,1) through (5,5). >>>> I tried adding: >>>> sizer.Add(field, pos=(1,6)) >>>> but it did not move the box to the position? >>> >>> Just to make sure, you did call it field and not self.scrolling_widget >>> (which was in my example)? >>> >>> Odd that they don't start at (0,0) when adding to the bag. This is >>> more a wxpython question and their mailing list might prove more >>> useful. I could figure it out, but I cannot run the app. Trial >>> and error here will probably help you the most. You can also >>> try looking at a different sizer (like BoxSizer and GridSizer). >>> >>> Personally, I think BoxSizer is the most intuitive as it matches >>> my thought process. You just set an orientation (vertical/horizontal) >>> and add widgets to it. To get something in the other direction, you >>> create another box sizer with the opposite orientation, add widgets >>> to that sizer, and then add the new sizer to the original sizer. Not >>> nearly as pretty as grid/grid bag though (by default), but super simple. >>> >>> BoxSizer API >>> http://wxpython.org/docs/api/wx.BoxSizer-class.html >>> Some other sizers are listed here: >>> http://wxpython.org/docs/api/wx.Sizer-class.html >>> >>>> >>>> THanks, >>>> Matt >>> >>> >> Hey, >> if i put: >> >> self.logfile = open('logfile.csv', 'w') >> >> in the .py file, within the 'class TrafficPane', then shouldn't >> logfile.csv be written to the directory the .py file is in? because its >> not there after running the program? Where should i look for it? >> Thanks >> Matt >> > > It should put it in the current directory. That *may* be the directory > the script is in, but not necessarily. It's easy to run something like: > > python somdir/myscript.py > > in which case the file would be in the parent directory to myscript.py > > Note that in some environments, the current directory is invisibly set > to some convenient place. For example, when right-clicking on a script > in Windows Explorer, they make the bald assumption that you want to set > the current directory the same as the location of the script. That's > about the worse place for it, but nevermind. > > > Yes, that was my assumption (even thought I am using linux); and right again, it is a very inconvenient place for it to be. however in the interest of speed of testing i figured i would make sure the log was logging the way i want it to and then try to find some sort of wx wigit to let the user of the gui name/save to desired location. meanwhile . . . so you think it saved somewhere right? From losermeloser at yahoo.com Thu Jun 13 02:53:10 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Wed, 12 Jun 2013 17:53:10 -0700 (PDT) Subject: [Tutor] hello. Message-ID: <1371084790.95122.YahooMailNeo@web121105.mail.ne1.yahoo.com> http://pictmania.com/tez.php -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Jun 13 03:02:58 2013 From: davea at davea.name (Dave Angel) Date: Wed, 12 Jun 2013 21:02:58 -0400 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B9165E.3080305@nycap.rr.com> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B28759.60201@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> <51B8E8F9.2030206@nycap.rr.com> <51B8EF53.7030201@davea.name> <51B9165E.3080305@nycap.rr.com> Message-ID: <51B91A42.9030903@davea.name> On 06/12/2013 08:46 PM, Matt D wrote: > On 06/12/2013 05:59 PM, Dave Angel wrote: >> On 06/12/2013 05:32 PM, Matt D wrote: >>> Hey, >>> if i put: >>> >>> self.logfile = open('logfile.csv', 'w') >>> >>> in the .py file, within the 'class TrafficPane', then shouldn't >>> logfile.csv be written to the directory the .py file is in? because its >>> not there after running the program? Where should i look for it? >>> Thanks >>> Matt >>> >> >> It should put it in the current directory. That *may* be the directory >> the script is in, but not necessarily. It's easy to run something like: >> >> python somdir/myscript.py >> >> in which case the file would be in the parent directory to myscript.py >> >> Note that in some environments, the current directory is invisibly set >> to some convenient place. For example, when right-clicking on a script >> in Windows Explorer, they make the bald assumption that you want to set >> the current directory the same as the location of the script. That's >> about the worse place for it, but nevermind. >> >> >> > Yes, that was my assumption (even thought I am using linux); and right > again, it is a very inconvenient place for it to be. however in the > interest of speed of testing i figured i would make sure the log was > logging the way i want it to and then try to find some sort of wx wigit > to let the user of the gui name/save to desired location. meanwhile . . > . so you think it saved somewhere right? There are other ways a script might change the current directory. For example, some naive scripts use os.chdir() But how is it you don't know what the current directory was when the code ran? A simply pwd can tell you, if your prompt doesn't already reveal it. -- DaveA From md123 at nycap.rr.com Thu Jun 13 03:23:45 2013 From: md123 at nycap.rr.com (Matt D) Date: Wed, 12 Jun 2013 21:23:45 -0400 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B91A42.9030903@davea.name> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B28759.60201@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> <51B8E8F9.2030206@nycap.rr.com> <51B8EF53.7030201@davea.name> <51B9165E.3080305@nycap.rr.com> <51B91A42.9030903@davea.name> Message-ID: <51B91F21.7090401@nycap.rr.com> > There are other ways a script might change the current directory. For > example, some naive scripts use os.chdir() > > But how is it you don't know what the current directory was when the > code ran? A simply pwd can tell you, if your prompt doesn't already > reveal it. > > hey i found the logfile. just took a few minutes of looking round. the file is logged all out of order so i have some work to do on that formatting issue. if you have a sec can you take a look at my code please? def update(self, field_values): # logger code--------------- # first write the CURRENT date/time self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", gmtime())))) # loop through each of the TextCtrl objects for k,v in self.fields.items(): # get the value of the current TextCtrl field f = field_values.get(k, None) if f: #output the value with trailing comma self.logfile.write('%s,'%(str(f))) self.logfile.write('\n') #end logger code ---------------- #if the field 'duid' == 'hdu', then clear all the fields if field_values['duid'] == 'hdu': self.clear() #loop through all TextCtrl fields storing the key/value pairs in k, v for k,v in self.fields.items(): # get the pickle value for this text control f = field_values.get(k, None) # if the value is empty then set the new value if f: v.SetValue(f) When i open the .csv file the fields are all out of order. what i want is have them all in one row beginning with the date/time. and idea? Thanks! From davea at davea.name Thu Jun 13 03:44:21 2013 From: davea at davea.name (Dave Angel) Date: Wed, 12 Jun 2013 21:44:21 -0400 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B91F21.7090401@nycap.rr.com> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B28759.60201@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> <51B8E8F9.2030206@nycap.rr.com> <51B8EF53.7030201@davea.name> <51B9165E.3080305@nycap.rr.com> <51B91A42.9030903@davea.name> <51B91F21.7090401@nycap.rr.com> Message-ID: <51B923F5.5060204@davea.name> On 06/12/2013 09:23 PM, Matt D wrote: > >> There are other ways a script might change the current directory. For >> example, some naive scripts use os.chdir() >> >> But how is it you don't know what the current directory was when the >> code ran? A simply pwd can tell you, if your prompt doesn't already >> reveal it. >> >> > hey i found the logfile. just took a few minutes of looking round. the > file is logged all out of order Do you have more than one thread? Perhaps you have a race condition. > so i have some work to do on that > formatting issue. if you have a sec can you take a look at my code please? > > def update(self, field_values): > > # logger code--------------- > # first write the CURRENT date/time > self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", gmtime())))) The return value of strftime is already a str, so why do you call str() on it? > # loop through each of the TextCtrl objects > for k,v in self.fields.items(): items() returns an unordered list; what order did you actually want? > # get the value of the current TextCtrl field > f = field_values.get(k, None) > if f: > #output the value with trailing comma > self.logfile.write('%s,'%(str(f))) > self.logfile.write('\n') That looks like a newline, not a comma > #end logger code ---------------- > > #if the field 'duid' == 'hdu', then clear all the fields > if field_values['duid'] == 'hdu': > self.clear() > #loop through all TextCtrl fields storing the key/value pairs in k, v > for k,v in self.fields.items(): Same ordering problem here. If you have a specific order in mind, you'll need to preserve it in a list, not in a dict. > # get the pickle value for this text control > f = field_values.get(k, None) > # if the value is empty then set the new value > if f: > v.SetValue(f) > > > When i open the .csv file the fields are all out of order. what i want > is have them all in one row beginning with the date/time. and idea? > Thanks! > > A dictionary is unsorted, so those two are probably your problem. As I mentioned above, you can't count on the items() order. Of course, self.items might not really be a dict. This fragment doesn't prove that one way or another. -- DaveA From cybervigilante at gmail.com Thu Jun 13 04:00:15 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 12 Jun 2013 19:00:15 -0700 Subject: [Tutor] Value Error In-Reply-To: References: <51B8E2F1.4070201@gmail.com> <9854C44E-F0D8-4778-A124-92AD46CA00BB@alchemy.com> <51B8F6D3.6000308@davea.name> Message-ID: On 12 June 2013 17:08, Marc Tompkins wrote: > On Wed, Jun 12, 2013 at 3:31 PM, Dave Angel wrote: > >> >>> cmath.sqrt(float((math.e **(i * math.pi)).real)) >> 1j >> > Sh*t just got real. > ============ I give up. When I got to Complex Analysis I decided to enlist instead. And that was during Vietnam ;') Jim A noun is just a verb with the hiccups -------------- next part -------------- An HTML attachment was scrubbed... URL: From ranjithtenz at gmail.com Thu Jun 13 05:59:44 2013 From: ranjithtenz at gmail.com (Ranjith Kumar) Date: Thu, 13 Jun 2013 09:29:44 +0530 Subject: [Tutor] Any speech to text conversation python library for Linux and mac box Message-ID: Hello all, I'm looking for speech to text conversation python library for linux and mac box, I found few libraries but non of them supports any of these platform. I found following libraries speech, dragonfly and pyspeech supports only windows and sphinx for linux. Any suggestion? -- Cheers, Ranjith Kumar K, Chennai. http://ranjithtenz.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From md123 at nycap.rr.com Thu Jun 13 06:18:58 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 13 Jun 2013 00:18:58 -0400 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B947E8.2040807@nycap.rr.com> References: <51B947E8.2040807@nycap.rr.com> Message-ID: <51B94832.6070308@nycap.rr.com> -------- Original Message -------- Subject: Re: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) Date: Thu, 13 Jun 2013 00:17:44 -0400 From: Matt D To: Dave Angel On 06/12/2013 09:44 PM, Dave Angel wrote: > On 06/12/2013 09:23 PM, Matt D wrote: >> >>> There are other ways a script might change the current directory. For >>> example, some naive scripts use os.chdir() >>> >>> But how is it you don't know what the current directory was when the >>> code ran? A simply pwd can tell you, if your prompt doesn't already >>> reveal it. >>> >>> >> hey i found the logfile. just took a few minutes of looking round. the >> file is logged all out of order > > Do you have more than one thread? Perhaps you have a race condition. > >> so i have some work to do on that >> formatting issue. if you have a sec can you take a look at my code >> please? >> >> def update(self, field_values): > >> >> # logger code--------------- >> # first write the CURRENT date/time >> self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", >> gmtime())))) > > The return value of strftime is already a str, so why do you call str() > on it? > >> # loop through each of the TextCtrl objects >> for k,v in self.fields.items(): > > items() returns an unordered list; what order did you actually want? > >> # get the value of the current TextCtrl field >> f = field_values.get(k, None) >> if f: >> #output the value with trailing comma >> self.logfile.write('%s,'%(str(f))) >> self.logfile.write('\n') > > That looks like a newline, not a comma > >> #end logger code ---------------- >> >> #if the field 'duid' == 'hdu', then clear all the fields >> if field_values['duid'] == 'hdu': >> self.clear() >> #loop through all TextCtrl fields storing the key/value pairs >> in k, v >> for k,v in self.fields.items(): > > Same ordering problem here. If you have a specific order in mind, > you'll need to preserve it in a list, not in a dict. > >> # get the pickle value for this text control >> f = field_values.get(k, None) >> # if the value is empty then set the new value >> if f: >> v.SetValue(f) >> >> >> When i open the .csv file the fields are all out of order. what i want >> is have them all in one row beginning with the date/time. and idea? >> Thanks! >> >> > > A dictionary is unsorted, so those two are probably your problem. As I > mentioned above, you can't count on the items() order. > > Of course, self.items might not really be a dict. This fragment doesn't > prove that one way or another. > > yes the .py file has TextCtrl fields that get there values from a pickled dictionary. Another peice of the code watches a thread for the pickle. this is why i didnt use a list. I have been unable to find a nice way to just make a list with the items i need. would be nice to have that simplicity. What you said is true, the the list is unordered. More importantly the new line comes in at the wrong point. I want all the values in a row starting with time. from there i will look for a way to remove some unwanted items and ordering the others. I attached the .py file for you to see the whole thing hoping this is not too presumptuous. Thanks. -------------- next part -------------- A non-text attachment was scrubbed... Name: op25_traffic_pane.py Type: text/x-python Size: 9188 bytes Desc: not available URL: From md123 at nycap.rr.com Thu Jun 13 06:24:57 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 13 Jun 2013 00:24:57 -0400 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B92673.3090002@davea.name> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B28759.60201@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> <51B8E8F9.2030206@nycap.rr.com> <51B8EF53.7030201@davea.name> <51B9165E.3080305@nycap.rr.com> <51B91A42.9030903@davea.name> <51B91D12.20909@nycap.rr.com> <51B92673.3090002@davea.name> Message-ID: <51B94999.4040707@nycap.rr.com> On 06/12/2013 09:54 PM, Dave Angel wrote: > On 06/12/2013 09:14 PM, Matt D wrote: >> On 06/12/2013 09:02 PM, Dave Angel wrote: >>> On 06/12/2013 08:46 PM, Matt D wrote: >>>> On 06/12/2013 05:59 PM, Dave Angel wrote: >>>>> On 06/12/2013 05:32 PM, Matt D wrote: >>> >>> >>> >>>>>> Hey, >>>>>> if i put: >>>>>> >>>>>> self.logfile = open('logfile.csv', 'w') >>>>>> >>>>>> in the .py file, within the 'class TrafficPane', then shouldn't >>>>>> logfile.csv be written to the directory the .py file is in? because >>>>>> its >>>>>> not there after running the program? Where should i look for it? >>>>>> Thanks >>>>>> Matt >>>>>> >>>>> >>>>> It should put it in the current directory. That *may* be the >>>>> directory >>>>> the script is in, but not necessarily. It's easy to run something >>>>> like: >>>>> >>>>> python somdir/myscript.py >>>>> >>>>> in which case the file would be in the parent directory to myscript.py >>>>> >>>>> Note that in some environments, the current directory is invisibly set >>>>> to some convenient place. For example, when right-clicking on a >>>>> script >>>>> in Windows Explorer, they make the bald assumption that you want to >>>>> set >>>>> the current directory the same as the location of the script. That's >>>>> about the worse place for it, but nevermind. >>>>> >>>>> >>>>> >>>> Yes, that was my assumption (even thought I am using linux); and right >>>> again, it is a very inconvenient place for it to be. however in the >>>> interest of speed of testing i figured i would make sure the log was >>>> logging the way i want it to and then try to find some sort of wx wigit >>>> to let the user of the gui name/save to desired location. meanwhile . . >>>> . so you think it saved somewhere right? >>> >>> There are other ways a script might change the current directory. For >>> example, some naive scripts use os.chdir() >>> >>> But how is it you don't know what the current directory was when the >>> code ran? A simply pwd can tell you, if your prompt doesn't already >>> reveal it. >>> >>> >> i was assuming the file would write to where the .py file is located. >> of course i know where that is because i put the file there but the >> logfile.csv is not in there. i did a search in the file system and >> nothing so i don't know what is going on here? guess keep looking? its >> gota be here somewhere? no? >> > > So is somebody else running your program? As I said before, how can you > NOT know what your current directory (cwd) is when you ran the script? > And again, the location of the script is irrelevant. > > No more offlist messages. This is a public forum, and I don't do private. > > DaveA > > please pardon mailing you only. when i press reply your email and not the list's email comes in. listen; i run another program in terminal in home directory; that program uses the .py file in the python directory. I already told you i found the file? why would someone else be running the program? From alan.gauld at btinternet.com Thu Jun 13 09:39:30 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Jun 2013 08:39:30 +0100 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B94999.4040707@nycap.rr.com> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B28759.60201@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> <51B8E8F9.2030206@nycap.rr.com> <51B8EF53.7030201@davea.name> <51B9165E.3080305@nycap.rr.com> <51B91A42.9030903@davea.name> <51B91D12.20909@nycap.rr.com> <51B92673.3090002@davea.name> <51B94999.4040707@nycap.rr.com> Message-ID: On 13/06/13 05:24, Matt D wrote: > I already told you i found the file? why would someone else be running > the program? Because it does something useful? Most pro programmers write programs for other people to use. Even an amateur may be creating something for their family use. If someone other than you were running it that might explain why the current directory wasn't what you expected since they will have a different $HOME for example. That's why Dave was asking. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From eryksun at gmail.com Thu Jun 13 10:09:03 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 13 Jun 2013 04:09:03 -0400 Subject: [Tutor] Value Error In-Reply-To: <51B8F6D3.6000308@davea.name> References: <51B8E2F1.4070201@gmail.com> <9854C44E-F0D8-4778-A124-92AD46CA00BB@alchemy.com> <51B8F6D3.6000308@davea.name> Message-ID: On Wed, Jun 12, 2013 at 6:31 PM, Dave Angel wrote: > >>>> i = complex(0,1) >>> 1j 1j http://en.wikipedia.org/wiki/Imaginary_unit#Alternative_notations >>>> cmath.sqrt(float((math.e **(i * math.pi)).real)) The real/imag attributes are already floats: >>> from math import e, pi, sin, cos >>> cos(pi / 3), (e ** (1j * pi / 3)).real (0.5000000000000001, 0.5000000000000001) >>> sin(pi / 3), (e ** (1j * pi / 3)).imag (0.8660254037844386, 0.8660254037844386) From davea at davea.name Thu Jun 13 12:39:18 2013 From: davea at davea.name (Dave Angel) Date: Thu, 13 Jun 2013 06:39:18 -0400 Subject: [Tutor] Value Error In-Reply-To: References: <51B8E2F1.4070201@gmail.com> <9854C44E-F0D8-4778-A124-92AD46CA00BB@alchemy.com> <51B8F6D3.6000308@davea.name> Message-ID: <51B9A156.2050309@davea.name> On 06/13/2013 04:09 AM, eryksun wrote: > On Wed, Jun 12, 2013 at 6:31 PM, Dave Angel wrote: >> >>>>> i = complex(0,1) > > >>> 1j > 1j I had forgotten that notation for a complex literal. I knew the magic syntax had j in it, but didn't remember it needs to be part of the numeric token. Of course the output of the debugger should have reminded me, but you did a better job. > > http://en.wikipedia.org/wiki/Imaginary_unit#Alternative_notations > > >>>>> cmath.sqrt(float((math.e **(i * math.pi)).real)) > > The real/imag attributes are already floats: > > >>> from math import e, pi, sin, cos > > >>> cos(pi / 3), (e ** (1j * pi / 3)).real > (0.5000000000000001, 0.5000000000000001) > > >>> sin(pi / 3), (e ** (1j * pi / 3)).imag > (0.8660254037844386, 0.8660254037844386) > Yeah, I know. I originally put the float in to get rid of the small bit of imaginary noise that the complex exponentiation created. When that failed, (apparently you can't use float() to get the real portion of a complex value), I added the .real() and forgot to remove the float(). In case this wasn't obvious to everyone, I was just playing with the "e to the I PI is minus one" trick, then feeding that -1 to square root. -- DaveA From davea at davea.name Thu Jun 13 14:22:00 2013 From: davea at davea.name (Dave Angel) Date: Thu, 13 Jun 2013 08:22:00 -0400 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B94832.6070308@nycap.rr.com> References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com> Message-ID: <51B9B968.5070908@davea.name> On 06/13/2013 12:18 AM, Matt D wrote: > > > >> >> > yes the .py file has TextCtrl fields that get there values from a > pickled dictionary. Another peice of the code watches a thread for the > pickle. this is why i didnt use a list. I have been unable to find a > nice way to just make a list with the items i need. would be nice to > have that simplicity. > What you said is true, the the list is unordered. More importantly the > new line comes in at the wrong point. I want all the values in a row > starting with time. from there i will look for a way to remove some > unwanted items and ordering the others. > I attached the .py file for you to see the whole thing hoping this is > not too presumptuous. Thanks. > > I don't mind the attached source file. Note that some readers may not be able to see it (attachments aren't guaranteed to survive), and others might find it excessive in length. But I'm fine with it. I notice you didn't change the newline to a comma, in the place that I commented earlier. You explicitly separate the fields with newlines, while commenting that it's done with commas. What you presumably want is to change the line inside the loop self.logfile.write('\n') to self.logfile.write(',') and add one of the former lines outside the loop, after writing the last field. About the ordering: Do you have a specific ordering in mind? Who decides it? The program that creates the pickle? How tightly bound are the two? Is there a 3rd program that's going to read the csv file? Are all of these programs written in Python? Will there be multiple versions, over time? If all of these programs have to share the same definition for the csv file, then at least some of it should be in common code. Simplest is to have the list/tuple of field names as a real list, defined in a module that they all import. Then, instead of using self.fields.items(), you use something like common.FIELD_LIST_NAMES common.py might have a line something like: #define the tuple of names that will be used for the csv file FIELD_LIST_NAMES = ("date", "duid", "nac", "source", "dest", "mfid", "algid", "kid", "mi", "tgid") Notice that TrafficPanel.init() might well collapse into a loop, if you add just a little more information into common.py Then you'd find that editing the one place adds a new field, both to the csv file but also to the gui. However, then if you add a new field, or remove one, you're obsoleting any csv files that may still be lying around, with no way to detect which ones are new and which ones are old. Typically this is managed with a version field in the first line of the file. But another, more standard, way to manage this is to make it a real csv file, with the field names in the first line (also comma separated). Python has a csv module, which solves another potential problem your logic may have: what happens if any of those values has a comma in it? I know I only hinted at the possible implementations, but until you make some architectural choices clear, I really cannot add much more. Here are some other remarks about the code: line 53: method Clone() should be lowercase, per Pep8. I don't believe it does anything useful, but you don't call it anyway. line 76: deleting a local just before a method returns does exactly nothing. When the method ends, the local will go out of scope, and the effect in either case is to decrement the refcount for the created DataEvent instance. Incidentally, if you happen to be using Thunderbird, you might look for the Reply-List button. -- DaveA From md123 at nycap.rr.com Thu Jun 13 15:28:17 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 13 Jun 2013 09:28:17 -0400 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B28759.60201@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> <51B8E8F9.2030206@nycap.rr.com> <51B8EF53.7030201@davea.name> <51B9165E.3080305@nycap.rr.com> <51B91A42.9030903@davea.name> <51B91D12.20909@nycap.rr.com> <51B92673.3090002@davea.name> <51B94999.4040707@nycap.rr.com> Message-ID: <51B9C8F1.2040405@nycap.rr.com> On 06/13/2013 03:39 AM, Alan Gauld wrote: > On 13/06/13 05:24, Matt D wrote: > >> I already told you i found the file? why would someone else be running >> the program? > > Because it does something useful? > Most pro programmers write programs for other people to use. > Even an amateur may be creating something for their family use. > > If someone other than you were running it that might explain why the > current directory wasn't what you expected since they will have a > different $HOME for example. That's why Dave was asking. > yeah i am not a programmer. just trying to increase the utility of a program (open source) someone else wrote. the file was in the home directory but i have so much pollution there that it took too long for me to spot it. not sure whey the file search didn't work. From md123 at nycap.rr.com Thu Jun 13 16:37:16 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 13 Jun 2013 10:37:16 -0400 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B9B968.5070908@davea.name> References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com> <51B9B968.5070908@davea.name> Message-ID: <51B9D91C.8030707@nycap.rr.com> On 06/13/2013 08:22 AM, Dave Angel wrote: > On 06/13/2013 12:18 AM, Matt D wrote: >> >> >> >>> >>> >> yes the .py file has TextCtrl fields that get there values from a >> pickled dictionary. Another peice of the code watches a thread for the >> pickle. this is why i didnt use a list. I have been unable to find a >> nice way to just make a list with the items i need. would be nice to >> have that simplicity. >> What you said is true, the the list is unordered. More importantly the >> new line comes in at the wrong point. I want all the values in a row >> starting with time. from there i will look for a way to remove some >> unwanted items and ordering the others. >> I attached the .py file for you to see the whole thing hoping this is >> not too presumptuous. Thanks. >> >> > > I don't mind the attached source file. Note that some readers may not > be able to see it (attachments aren't guaranteed to survive), and others > might find it excessive in length. But I'm fine with it. > > I notice you didn't change the newline to a comma, in the place that I > commented earlier. You explicitly separate the fields with newlines, > while commenting that it's done with commas. > > What you presumably want is to change the line inside the loop > > self.logfile.write('\n') > to > self.logfile.write(',') > > and add one of the former lines outside the loop, after writing the last > field. > > About the ordering: Do you have a specific ordering in mind? Who > decides it? The program that creates the pickle? How tightly bound are > the two? Is there a 3rd program that's going to read the csv file? Are > all of these programs written in Python? Will there be multiple > versions, over time? > > If all of these programs have to share the same definition for the csv > file, then at least some of it should be in common code. Simplest is to > have the list/tuple of field names as a real list, defined in a module > that they all import. Then, instead of using self.fields.items(), you > use something like common.FIELD_LIST_NAMES > > common.py might have a line something like: > > #define the tuple of names that will be used for the csv file > FIELD_LIST_NAMES = ("date", "duid", "nac", "source", "dest", "mfid", > "algid", "kid", "mi", "tgid") > > Notice that TrafficPanel.init() might well collapse into a loop, if you > add just a little more information into common.py Then you'd find that > editing the one place adds a new field, both to the csv file but also to > the gui. > > However, then if you add a new field, or remove one, you're obsoleting > any csv files that may still be lying around, with no way to detect > which ones are new and which ones are old. Typically this is managed > with a version field in the first line of the file. > > But another, more standard, way to manage this is to make it a real csv > file, with the field names in the first line (also comma separated). > Python has a csv module, which solves another potential problem your > logic may have: what happens if any of those values has a comma in it? > > > I know I only hinted at the possible implementations, but until you make > some architectural choices clear, I really cannot add much more. > > Here are some other remarks about the code: > > line 53: method Clone() should be lowercase, per Pep8. I don't believe > it does anything useful, but you don't call it anyway. > > line 76: deleting a local just before a method returns does exactly > nothing. When the method ends, the local will go out of scope, and the > effect in either case is to decrement the refcount for the created > DataEvent instance. > > Incidentally, if you happen to be using Thunderbird, you might look for > the Reply-List button. > Hey, line 202: self.logfile.write('%s,'%(str(f))) d does put the comma in properly but, line 203: self.logfile.write('\n') was putting the newline after each value like you said. I moved this back outside of the if statement to see (i am still a little unsure about the indention and i have to test) if it will create a new row only when all the k,v values have been looped through. the ordering: yes this is quite a hole in my understanding of what is going on here. the pickle is created in a collection of pretty complicated C++ code that doesn't explicitly show how the pickle is ordered or whats in it even in the pickle.cc and pickle.h files. the pickle files take in some sort of stream, pickle the data, and send it to a message queue that the trafficpanel waits on. i need to log this pickle or at at least dump it to terminal because i am pretty sure the 'source' and 'dest' fields (which currently are not available) are in the pickle, albeit in a different data unit. I have read "http://www.python.org/doc//current/library/pickle.html" two times already and still cant find a way to print the pickle in human readable form. my understanding of pickling stinks. The ordering at this point is not so important (not nearly as important as getting the 'source' 'dest' fields) because the point of the .csv file is just to import it into librecalc and work time series analysis on the data manually. at some later point in the development maybe this this task can be automated but for now just an unordered file will suffice. and yes i think there probably is some bit rot there its just that once i get it running without errors i don't feel confident messing about with other lines. Thanks a bunch! From fomcl at yahoo.com Thu Jun 13 17:09:36 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 13 Jun 2013 08:09:36 -0700 (PDT) Subject: [Tutor] regex grouping/capturing Message-ID: <1371136176.25009.YahooMailNeo@web163804.mail.gq1.yahoo.com> ? Hello, ? I have a string of the form "required optional3 optional2 optional1 optional3" ('optional' may be any kind of string, so it's not simply 'optional\d+'. I would like to use a regex so I can distinguish groups. Desired outcome: ('required', 'optional3', 'optional2', 'optional1', 'optional3'). Below is a fragment of the many things I have tried. ? >>> import re >>> regex = r"(required) (optional1)* (optional2)* (optional3)*" >>> #regex = r"(required) (?:(optional1)*|(optional2)*|(optional3)*)*" >>> #regex = r"(required) (optional1|optional2|optional3)*" >>> s = "required optional3 optional2 optional1 optional3" >>> re.search(regex, s).groups() Traceback (most recent call last): ? File "", line 1, in ??? re.search(regex, s).groups() AttributeError: 'NoneType' object has no attribute 'groups' >>> s2 = "required optional1 optional2 optional3" >>> re.search(regex, s2).groups() ('required', 'optional1', 'optional2', 'optional3') # it only 'works' if the optional words are in the same order as in the regex, and not specified multiple times. How can I make this work? Thank you in advance! 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? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From davea at davea.name Thu Jun 13 17:23:47 2013 From: davea at davea.name (Dave Angel) Date: Thu, 13 Jun 2013 11:23:47 -0400 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B9D91C.8030707@nycap.rr.com> References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com> <51B9B968.5070908@davea.name> <51B9D91C.8030707@nycap.rr.com> Message-ID: <51B9E403.4070003@davea.name> On 06/13/2013 10:37 AM, Matt D wrote: > On 06/13/2013 08:22 AM, Dave Angel wrote: >> On 06/13/2013 12:18 AM, Matt D wrote: >>> >>> >>> >>>> >>>> >> > Hey, > line 202: self.logfile.write('%s,'%(str(f))) d > does put the comma in properly but, > line 203: self.logfile.write('\n') > was putting the newline after each value like you said. > I moved this back outside of the if statement to see (i am still a > little unsure about the indention and i have to test) if it will create > a new row only when all the k,v values have been looped through. Then put it AFTER the loop, not after the if. It should line up with the for statement. And if you mix spaces with tabs, heaven help you. Different people have different preferences, but I despise tabs in source code. Notice that you've done it at least four places: #output the value with trailing comma #if the field 'duid' == 'hdu', then clear all the fields return 0 main() If your editor let you do that, you aren't using the right settings on the editor (or the right editor). This didn't affect anything, since indentation doesn't matter on comments, and the other two lines are isolated indentations. > > the ordering: yes this is quite a hole in my understanding of what is > going on here. the pickle is created in a collection of pretty > complicated C++ code that doesn't explicitly show how the pickle is > ordered or whats in it even in the pickle.cc and pickle.h files. the > pickle files take in some sort of stream, pickle the data, and send it > to a message queue that the trafficpanel waits on. i need to log this > pickle or at at least dump it to terminal because i am pretty sure the > 'source' and 'dest' fields (which currently are not available) are in > the pickle, albeit in a different data unit. I have read > "http://www.python.org/doc//current/library/pickle.html" two times > already and still cant find a way to print the pickle in human readable > form. my understanding of pickling stinks. The ordering at this point > is not so important (not nearly as important as getting the 'source' > 'dest' fields) because the point of the .csv file is just to import it > into librecalc and work time series analysis on the data manually. at > some later point in the development maybe this this task can be > automated but for now just an unordered file will suffice. If you want a consistent ordering, then add the line I described to your own source code, at module scope. Since you have no access to (control over) the C++ code, you'll just have to make up your own list, as you've already effectively done with your GUI. For every field that is NOT in the dict, you should be outputting a simple comma. So your if test is wrong, since it will eat zeros as well as missing values. And you need an else clause: for k,v in FIELD_LIST_NAMES: # get the value of the current TextCtrl field f = field_values.get(k, None) if not f is None: #output the value with trailing comma self.logfile.write('%s,'%(str(f))) else: self.logfile.write(",") self.logfile.write("\n") And don't forget to add in the header line to your csv file, naming the fields that are to be used in every line. -- -- DaveA From md123 at nycap.rr.com Thu Jun 13 18:32:47 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 13 Jun 2013 12:32:47 -0400 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B9E403.4070003@davea.name> References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com> <51B9B968.5070908@davea.name> <51B9D91C.8030707@nycap.rr.com> <51B9E403.4070003@davea.name> Message-ID: <51B9F42F.3000001@nycap.rr.com> On 06/13/2013 11:23 AM, Dave Angel wrote: > On 06/13/2013 10:37 AM, Matt D wrote: >> On 06/13/2013 08:22 AM, Dave Angel wrote: >>> On 06/13/2013 12:18 AM, Matt D wrote: >>>> >>>> >>>> >>>>> >>>>> >>> >> Hey, >> line 202: self.logfile.write('%s,'%(str(f))) d >> does put the comma in properly but, >> line 203: self.logfile.write('\n') >> was putting the newline after each value like you said. >> I moved this back outside of the if statement to see (i am still a >> little unsure about the indention and i have to test) if it will create >> a new row only when all the k,v values have been looped through. > > Then put it AFTER the loop, not after the if. It should line up with > the for statement. And if you mix spaces with tabs, heaven help you. > Different people have different preferences, but I despise tabs in > source code. Notice that you've done it at least four places: > > #output the value with trailing comma > #if the field 'duid' == 'hdu', then clear all the fields > return 0 > main() > > If your editor let you do that, you aren't using the right settings on > the editor (or the right editor). This didn't affect anything, since > indentation doesn't matter on comments, and the other two lines are > isolated indentations. > > >> >> the ordering: yes this is quite a hole in my understanding of what is >> going on here. the pickle is created in a collection of pretty >> complicated C++ code that doesn't explicitly show how the pickle is >> ordered or whats in it even in the pickle.cc and pickle.h files. the >> pickle files take in some sort of stream, pickle the data, and send it >> to a message queue that the trafficpanel waits on. i need to log this >> pickle or at at least dump it to terminal because i am pretty sure the >> 'source' and 'dest' fields (which currently are not available) are in >> the pickle, albeit in a different data unit. I have read >> "http://www.python.org/doc//current/library/pickle.html" two times >> already and still cant find a way to print the pickle in human readable >> form. my understanding of pickling stinks. The ordering at this point >> is not so important (not nearly as important as getting the 'source' >> 'dest' fields) because the point of the .csv file is just to import it >> into librecalc and work time series analysis on the data manually. at >> some later point in the development maybe this this task can be >> automated but for now just an unordered file will suffice. > > If you want a consistent ordering, then add the line I described to your > own source code, at module scope. Since you have no access to (control > over) the C++ code, you'll just have to make up your own list, as you've > already effectively done with your GUI. For every field that is NOT in > the dict, you should be outputting a simple comma. > > So your if test is wrong, since it will eat zeros as well as missing > values. And you need an else clause: > > for k,v in FIELD_LIST_NAMES: > # get the value of the current TextCtrl field > f = field_values.get(k, None)2013-06-12 16:28:59,Unknown (0x658), DES-OFB, HDU, 0xa4d5010ca0bbdb0900, 0xfff, Standard MFID (pre-2001), 00x1, > if not f is None: > #output the value with trailing comma > self.logfile.write('%s,'%(str(f))) > else: > self.logfile.write(",") > self.logfile.write("\n") > > And don't forget to add in the header line to your csv file, naming the > fields that are to be used in every line. > as of now the order in the .csv file is like this: 2013-06-12 16:28:59,Unknown (0x658), 00x80, $80 Clear, 0xa4d5010ca0bbdb0900, 0xfff, Standard MFID (pre-2001), 00x1, and keeps repeating this order as long as HUDs are coming in. i am unsure why the date/time is on the same line as NAC? Oh and i have not tested yet with the '\n' newline command out of the if statement. If i have to i can modify the C++ code but was hoping not to have to do that at this stage. the C++ is used for what is computationally intense and the Python is used mainly for the UI. Any idea of a way to write the pickle to file to see what it contains? because it is not explicit in the C++ files, at least not as far as I can tell as of yet. Thanks! From howewriter2000 at yahoo.com Thu Jun 13 19:21:40 2013 From: howewriter2000 at yahoo.com (jessica peters) Date: Thu, 13 Jun 2013 10:21:40 -0700 (PDT) Subject: [Tutor] sound implementation problems Message-ID: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> Hi I'm about 2 yrs into studying Python - started with "Hello World", and I'm working with v 2.5.1 right now. ?The past year I've begun trying to write my own interactive fiction. ?That works pretty well, but now I'm attempting to put some music into programs (I thought background music would be good), and I'm running into roadblocks. I've tried several different things for this, and come up with either my text that comes to a halt eventually at an error message (can't read from the files or mixer isn't initialized are the most common ones), or a completely blank screen with no sound. ?I've tried both .mp3 files and .wav ones, neither works for this. Here's the most recent code I've attempted: import pygame , sys import random size=[500,500] def run(self): ? ? import pygame.mixer ? ? pygame.mixer.init(22050, -16, 2, 4096) ? ? self.sound.seek(0) ? ? snd = pygame.mixer.Sound(self.sound) ? ? pygame.mixer.Sound.play("bach-cello-suite-1.wav") ? ? musicPlaying = True Any ideas would ?be appreciated. ?Thanks. ? my website: http://jahowe.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Jun 13 19:48:02 2013 From: davea at davea.name (Dave Angel) Date: Thu, 13 Jun 2013 13:48:02 -0400 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B9F42F.3000001@nycap.rr.com> References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com> <51B9B968.5070908@davea.name> <51B9D91C.8030707@nycap.rr.com> <51B9E403.4070003@davea.name> <51B9F42F.3000001@nycap.rr.com> Message-ID: <51BA05D2.3030208@davea.name> On 06/13/2013 12:32 PM, Matt D wrote: > On 06/13/2013 11:23 AM, Dave Angel wrote: >> On 06/13/2013 10:37 AM, Matt D wrote: >>> On 06/13/2013 08:22 AM, Dave Angel wrote: >>>> On 06/13/2013 12:18 AM, Matt D wrote: >>>>> >>>>> >>>>> >>>>>> >>>>>> >>>> >>> Hey, >>> line 202: self.logfile.write('%s,'%(str(f))) d >>> does put the comma in properly but, >>> line 203: self.logfile.write('\n') >>> was putting the newline after each value like you said. >>> I moved this back outside of the if statement to see (i am still a >>> little unsure about the indention and i have to test) if it will create >>> a new row only when all the k,v values have been looped through. >> >> Then put it AFTER the loop, not after the if. It should line up with >> the for statement. And if you mix spaces with tabs, heaven help you. >> Different people have different preferences, but I despise tabs in >> source code. Notice that you've done it at least four places: >> >> #output the value with trailing comma >> #if the field 'duid' == 'hdu', then clear all the fields >> return 0 >> main() >> >> If your editor let you do that, you aren't using the right settings on >> the editor (or the right editor). This didn't affect anything, since >> indentation doesn't matter on comments, and the other two lines are >> isolated indentations. >> >> >>> >>> the ordering: yes this is quite a hole in my understanding of what is >>> going on here. the pickle is created in a collection of pretty >>> complicated C++ code that doesn't explicitly show how the pickle is >>> ordered or whats in it even in the pickle.cc and pickle.h files. the >>> pickle files take in some sort of stream, pickle the data, and send it >>> to a message queue that the trafficpanel waits on. i need to log this >>> pickle or at at least dump it to terminal because i am pretty sure the >>> 'source' and 'dest' fields (which currently are not available) are in >>> the pickle, albeit in a different data unit. I have read >>> "http://www.python.org/doc//current/library/pickle.html" two times >>> already and still cant find a way to print the pickle in human readable >>> form. my understanding of pickling stinks. The ordering at this point >>> is not so important (not nearly as important as getting the 'source' >>> 'dest' fields) because the point of the .csv file is just to import it >>> into librecalc and work time series analysis on the data manually. at >>> some later point in the development maybe this this task can be >>> automated but for now just an unordered file will suffice. >> >> If you want a consistent ordering, then add the line I described to your >> own source code, at module scope. Since you have no access to (control >> over) the C++ code, you'll just have to make up your own list, as you've >> already effectively done with your GUI. For every field that is NOT in >> the dict, you should be outputting a simple comma. >> >> So your if test is wrong, since it will eat zeros as well as missing >> values. And you need an else clause: >> >> for k,v in FIELD_LIST_NAMES: >> # get the value of the current TextCtrl field >> f = field_values.get(k, None)2013-06-12 16:28:59,Unknown (0x658), > DES-OFB, > HDU, > 0xa4d5010ca0bbdb0900, > 0xfff, > Standard MFID (pre-2001), > 00x1, >> if not f is None: >> #output the value with trailing comma >> self.logfile.write('%s,'%(str(f))) >> else: >> self.logfile.write(",") >> self.logfile.write("\n") >> >> And don't forget to add in the header line to your csv file, naming the >> fields that are to be used in every line. >> > as of now the order in the .csv file is like this: > > 2013-06-12 16:28:59,Unknown (0x658), > 00x80, > $80 Clear, > 0xa4d5010ca0bbdb0900, > 0xfff, > Standard MFID (pre-2001), > 00x1, > > and keeps repeating this order as long as HUDs are coming in. i am > unsure why the date/time is on the same line as NAC? Because you don't have a bogus newline after the date/time, but do after all the other fields. Oh and i have not > tested yet with the '\n' newline command out of the if statement. If i > have to i can modify the C++ code but was hoping not to have to do that > at this stage. the C++ is used for what is computationally intense and > the Python is used mainly for the UI. Any idea of a way to write the > pickle to file to see what it contains? because it is not explicit in > the C++ files, at least not as far as I can tell as of yet. > Thanks! > I don't see any need to modify the C++ sources. I don't know how to examine a pickle, file or otherwise. You can, however, trivially print out all the keys (and values even) in field_values, for each record, and make sure they match your FIELD_LIST_NAMES, other than for order. Perhaps they named source and dest as Source and dESt, respectively, or src and dst, or whatever. If you really want the pickle as a file, you could write pickled_dict to a separate file. Just be sure to create that file as binary, since (some ?) pickle formats are not text. -- DaveA From davea at davea.name Thu Jun 13 19:55:32 2013 From: davea at davea.name (Dave Angel) Date: Thu, 13 Jun 2013 13:55:32 -0400 Subject: [Tutor] sound implementation problems In-Reply-To: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> Message-ID: <51BA0794.40200@davea.name> On 06/13/2013 01:21 PM, jessica peters wrote: > Hi > > I'm about 2 yrs into studying Python - started with "Hello World", and I'm working with v 2.5.1 right now. The past year I've begun trying to write my own interactive fiction. That works pretty well, but now I'm attempting to put some music into programs (I thought background music would be good), and I'm running into roadblocks. > > I've tried several different things for this, and come up with either my text that comes to a halt eventually at an error message (can't read from the files or mixer isn't initialized are the most common ones), or a completely blank screen with no sound. I've tried both .mp3 files and .wav ones, neither works for this. > > Here's the most recent code I've attempted: > > import pygame , sys > import random > size=[500,500] > def run(self): It's not customary to use self as a name in a non-class function. > import pygame.mixer > pygame.mixer.init(22050, -16, 2, 4096) > self.sound.seek(0) What is the object that has this sound attribute? > snd = pygame.mixer.Sound(self.sound) > pygame.mixer.Sound.play("bach-cello-suite-1.wav") > musicPlaying = True > Nobody calls the function, so this file will silently exit. > Any ideas would be appreciated. Thanks. > Somebody familiar with both pygame and with sound might be able to help. But you really ought to tell them what version of pygame, and what OS you're running on. And if you get an error message, copy/paste the whole thing, don't paraphrase, and show the same code as what was failing. -- DaveA From cybervigilante at gmail.com Thu Jun 13 19:56:06 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Thu, 13 Jun 2013 10:56:06 -0700 Subject: [Tutor] sound implementation problems In-Reply-To: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> Message-ID: I'll assume you're using Windows. If not, ignore this ;') winsound on windows is Python native, much simpler, and always works. After importing it you can type help(winsound) to see its controls. But here is the usage for a wav file (it doesn't play mp3s) There is no rule you have to use the pygame functionality, which is more complex, to get a sound, if that's all you want. import winsound winsound.PlaySound('c:/python33/media/wtf.wav', 1) Make sure you end with the "1". The helpfile doesn't mention what to use as the second parameter, but 1 works fine. And one other thing that tripped me up. If you're using an IDE or editor, mine has the unfortunate habit of loading in its own directory, and having no option to automatically access files from my program directory. It saves a program into the last used directory, but looks for sounds in its own directory. Ugh. When I thought my program was accessing a wav from my standard program directory, it was really trying to find it in the PyScripter directory ;') So use the Full Path to your sound file, and avoid that possible problem. I have a startup script that now stays in my program directory, though. Of course, if you have an IDE or editor that lets you set the default directory that's no problem. If your editor doesn't do default directories but has startup scripts this will work (changing the directoy in chdir to your system, of course) import os os.chdir('c:/python33/jimprogs') del(os) Jim On 13 June 2013 10:21, jessica peters wrote: > Hi > > I'm about 2 yrs into studying Python - started with "Hello World", and I'm > working with v 2.5.1 right now. The past year I've begun trying to write > my own interactive fiction. That works pretty well, but now I'm attempting > to put some music into programs (I thought background music would be good), > and I'm running into roadblocks. > > I've tried several different things for this, and come up with either my > text that comes to a halt eventually at an error message (can't read from > the files or mixer isn't initialized are the most common ones), or a > completely blank screen with no sound. I've tried both .mp3 files and .wav > ones, neither works for this. > > Here's the most recent code I've attempted: > > import pygame , sys > import random > size=[500,500] > def run(self): > import pygame.mixer > pygame.mixer.init(22050, -16, 2, 4096) > self.sound.seek(0) > snd = pygame.mixer.Sound(self.sound) > pygame.mixer.Sound.play("bach-cello-suite-1.wav") > musicPlaying = True > > Any ideas would be appreciated. Thanks. > > my website: http://jahowe.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Jim A noun is just a verb with the hiccups -------------- next part -------------- An HTML attachment was scrubbed... URL: From francois.dion at gmail.com Thu Jun 13 21:21:45 2013 From: francois.dion at gmail.com (Francois Dion) Date: Thu, 13 Jun 2013 15:21:45 -0400 Subject: [Tutor] sound implementation problems In-Reply-To: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> Message-ID: I'd start with something simple first, to make sure you have sound output etc. Run python interactively in the directory you have your wav file. At a minimum, you need to import pygame, init the mixer (args are not really needed, but I'll use what you had), set up the sound file and finally, play it: >>> import pygame >>> pygame.mixer.init(22050,-16,2,4096) >>> snd = pygame.mixer.Sound("bach-cello-suite-1.wav") >>> music = snd.play() music will start playing in the background. To check if the music is still playing: >>> music.get_busy() 1 >>> music.get_busy() 1 >>> music.get_busy() 0 And that's that. In your code, your run() function was probably a method taken out of a class where sound returns a filename and seek(0) seeks to the beginning of a file. You are missing the rest of the class. But, like I said, you really only need 4 lines to play a wav file. BTW, nice russian ?????????? in the background image of your site. Francois -- www.pyptug.org - raspberry-python.blogspot.com - @f_dion On Thu, Jun 13, 2013 at 1:21 PM, jessica peters wrote: > Hi > > I'm about 2 yrs into studying Python - started with "Hello World", and I'm > working with v 2.5.1 right now. The past year I've begun trying to write > my own interactive fiction. That works pretty well, but now I'm attempting > to put some music into programs (I thought background music would be good), > and I'm running into roadblocks. > > I've tried several different things for this, and come up with either my > text that comes to a halt eventually at an error message (can't read from > the files or mixer isn't initialized are the most common ones), or a > completely blank screen with no sound. I've tried both .mp3 files and .wav > ones, neither works for this. > > Here's the most recent code I've attempted: > > import pygame , sys > import random > size=[500,500] > def run(self): > import pygame.mixer > pygame.mixer.init(22050, -16, 2, 4096) > self.sound.seek(0) > snd = pygame.mixer.Sound(self.sound) > pygame.mixer.Sound.play("bach-cello-suite-1.wav") > musicPlaying = True > > Any ideas would be appreciated. Thanks. > > my website: http://jahowe.com > > _______________________________________________ > 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 andipersti at gmail.com Thu Jun 13 20:09:02 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Thu, 13 Jun 2013 20:09:02 +0200 Subject: [Tutor] regex grouping/capturing In-Reply-To: <1371136176.25009.YahooMailNeo@web163804.mail.gq1.yahoo.com> References: <1371136176.25009.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: <51BA0ABE.9010702@gmail.com> On 13.06.2013 17:09, Albert-Jan Roskam wrote: > I have a string of the form "required optional3 optional2 optional1 > optional3" ('optional' may be any kind of string, so it's not simply > 'optional\d+'. > I would like to use a regex so I can distinguish groups. Desired > outcome: ('required', 'optional3', 'optional2', 'optional1', > 'optional3'). Below is a fragment of the many things I have tried. [SNIP] > How can I make this work? If you really want to use a regex: >>> import re >>> s = "required optional3 optional2 optional1 optional3" >>> s2 = "required optional1 optional2 optional3" >>> pattern = "required|optional1|optional2|optional3" >>> re.findall(pattern, s) ['required', 'optional3', 'optional2', 'optional1', 'optional3'] >>> re.findall(pattern, s2) ['required', 'optional1', 'optional2', 'optional3'] But why not simply: >>> s.split() ['required', 'optional3', 'optional2', 'optional1', 'optional3'] >>> s2.split() ['required', 'optional1', 'optional2', 'optional3'] Bye, Andreas From iafleischer at gmail.com Thu Jun 13 23:32:09 2013 From: iafleischer at gmail.com (I. Alejandro Fleischer) Date: Thu, 13 Jun 2013 17:32:09 -0400 Subject: [Tutor] find a tutorial for starting with python and netbeans (Igor Fleischer) Message-ID: Hi, Im starting to learn Python, and downloaded Net Beans as an IDE. Would you recomend me please a tutorial for a begining with this two integrated enviroments? Thank you very much. On Thu, Jun 13, 2013 at 3:21 PM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: sound implementation problems (Dave Angel) > 2. Re: sound implementation problems (Jim Mooney) > 3. Re: sound implementation problems (Francois Dion) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 13 Jun 2013 13:55:32 -0400 > From: Dave Angel > To: tutor at python.org > Subject: Re: [Tutor] sound implementation problems > Message-ID: <51BA0794.40200 at davea.name> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 06/13/2013 01:21 PM, jessica peters wrote: > > Hi > > > > I'm about 2 yrs into studying Python - started with "Hello World", and > I'm working with v 2.5.1 right now. The past year I've begun trying to > write my own interactive fiction. That works pretty well, but now I'm > attempting to put some music into programs (I thought background music > would be good), and I'm running into roadblocks. > > > > I've tried several different things for this, and come up with either my > text that comes to a halt eventually at an error message (can't read from > the files or mixer isn't initialized are the most common ones), or a > completely blank screen with no sound. I've tried both .mp3 files and .wav > ones, neither works for this. > > > > Here's the most recent code I've attempted: > > > > import pygame , sys > > import random > > size=[500,500] > > def run(self): > > It's not customary to use self as a name in a non-class function. > > > import pygame.mixer > > pygame.mixer.init(22050, -16, 2, 4096) > > self.sound.seek(0) > > What is the object that has this sound attribute? > > > snd = pygame.mixer.Sound(self.sound) > > pygame.mixer.Sound.play("bach-cello-suite-1.wav") > > musicPlaying = True > > > > Nobody calls the function, so this file will silently exit. > > > Any ideas would be appreciated. Thanks. > > > > Somebody familiar with both pygame and with sound might be able to help. > But you really ought to tell them what version of pygame, and what OS > you're running on. > > And if you get an error message, copy/paste the whole thing, don't > paraphrase, and show the same code as what was failing. > > > -- > DaveA > > > ------------------------------ > > Message: 2 > Date: Thu, 13 Jun 2013 10:56:06 -0700 > From: Jim Mooney > To: jessica peters > Cc: "Tutor at python.org" > Subject: Re: [Tutor] sound implementation problems > Message-ID: > ycvyjSVOdDXU_D48zKdQDSRzjma4Oe7xCUhMrv0zw at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > I'll assume you're using Windows. If not, ignore this ;') > > winsound on windows is Python native, much simpler, and always works. After > importing it you can type help(winsound) to see its controls. But here is > the usage for a wav file (it doesn't play mp3s) There is no rule you have > to use the pygame functionality, which is more complex, to get a sound, if > that's all you want. > > import winsound > winsound.PlaySound('c:/python33/media/wtf.wav', 1) > > Make sure you end with the "1". The helpfile doesn't mention what to use as > the second parameter, but 1 works fine. And one other thing that tripped me > up. If you're using an IDE or editor, mine has the unfortunate habit of > loading in its own directory, and having no option to automatically access > files from my program directory. It saves a program into the last used > directory, but looks for sounds in its own directory. Ugh. When I thought > my program was accessing a wav from my standard program directory, it was > really trying to find it in the PyScripter directory ;') > > So use the Full Path to your sound file, and avoid that possible problem. I > have a startup script that now stays in my program directory, though. Of > course, if you have an IDE or editor that lets you set the default > directory that's no problem. > > If your editor doesn't do default directories but has startup scripts this > will work (changing the directoy in chdir to your system, of course) > > import os > os.chdir('c:/python33/jimprogs') > del(os) > > > Jim > > On 13 June 2013 10:21, jessica peters wrote: > > > Hi > > > > I'm about 2 yrs into studying Python - started with "Hello World", and > I'm > > working with v 2.5.1 right now. The past year I've begun trying to write > > my own interactive fiction. That works pretty well, but now I'm > attempting > > to put some music into programs (I thought background music would be > good), > > and I'm running into roadblocks. > > > > I've tried several different things for this, and come up with either my > > text that comes to a halt eventually at an error message (can't read from > > the files or mixer isn't initialized are the most common ones), or a > > completely blank screen with no sound. I've tried both .mp3 files and > .wav > > ones, neither works for this. > > > > Here's the most recent code I've attempted: > > > > import pygame , sys > > import random > > size=[500,500] > > def run(self): > > import pygame.mixer > > pygame.mixer.init(22050, -16, 2, 4096) > > self.sound.seek(0) > > snd = pygame.mixer.Sound(self.sound) > > pygame.mixer.Sound.play("bach-cello-suite-1.wav") > > musicPlaying = True > > > > Any ideas would be appreciated. Thanks. > > > > my website: http://jahowe.com > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- > Jim > A noun is just a verb with the hiccups > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20130613/df20d7c5/attachment-0001.html > > > > ------------------------------ > > Message: 3 > Date: Thu, 13 Jun 2013 15:21:45 -0400 > From: Francois Dion > To: jessica peters > Cc: "Tutor at python.org" > Subject: Re: [Tutor] sound implementation problems > Message-ID: > GiXp4_K4TvRNqzJzGH0GDLvKw at mail.gmail.com> > Content-Type: text/plain; charset="utf-8" > > I'd start with something simple first, to make sure you have sound output > etc. Run python interactively in the directory you have your wav file. At a > minimum, you need to import pygame, init the mixer (args are not really > needed, but I'll use what you had), set up the sound file and finally, play > it: > > >>> import pygame > >>> pygame.mixer.init(22050,-16,2,4096) > >>> snd = pygame.mixer.Sound("bach-cello-suite-1.wav") > >>> music = snd.play() > > music will start playing in the background. To check if the music is still > playing: > > >>> music.get_busy() > 1 > >>> music.get_busy() > 1 > >>> music.get_busy() > 0 > > And that's that. In your code, your run() function was probably a method > taken out of a class where sound returns a filename and seek(0) seeks to > the beginning of a file. You are missing the rest of the class. But, like I > said, you really only need 4 lines to play a wav file. > > BTW, nice russian ?????????? in the background image of your site. > > Francois > -- > www.pyptug.org - raspberry-python.blogspot.com - @f_dion > > > > On Thu, Jun 13, 2013 at 1:21 PM, jessica peters >wrote: > > > Hi > > > > I'm about 2 yrs into studying Python - started with "Hello World", and > I'm > > working with v 2.5.1 right now. The past year I've begun trying to write > > my own interactive fiction. That works pretty well, but now I'm > attempting > > to put some music into programs (I thought background music would be > good), > > and I'm running into roadblocks. > > > > I've tried several different things for this, and come up with either my > > text that comes to a halt eventually at an error message (can't read from > > the files or mixer isn't initialized are the most common ones), or a > > completely blank screen with no sound. I've tried both .mp3 files and > .wav > > ones, neither works for this. > > > > Here's the most recent code I've attempted: > > > > import pygame , sys > > import random > > size=[500,500] > > def run(self): > > import pygame.mixer > > pygame.mixer.init(22050, -16, 2, 4096) > > self.sound.seek(0) > > snd = pygame.mixer.Sound(self.sound) > > pygame.mixer.Sound.play("bach-cello-suite-1.wav") > > musicPlaying = True > > > > Any ideas would be appreciated. Thanks. > > > > my website: http://jahowe.com > > > > _______________________________________________ > > 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: < > http://mail.python.org/pipermail/tutor/attachments/20130613/d42716e0/attachment.html > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 112, Issue 52 > ************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Fri Jun 14 01:18:40 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Thu, 13 Jun 2013 16:18:40 -0700 Subject: [Tutor] find a tutorial for starting with python and netbeans (Igor Fleischer) In-Reply-To: References: Message-ID: On 13 June 2013 14:32, I. Alejandro Fleischer wrote: > Hi, > > Im starting to learn Python, and downloaded Net Beans as an IDE. > Would you recomend me please a tutorial for a begining with this two > integrated enviroments? > I'm just starting, also, went that route, and quickly ditched NetBeans. It's Huge overkill and you'll spend more time fighting with it and setting it up than learning Python. Try Wing 101, which is python-specific, very easy to understand, and works for Python right out of the box. Available for Windows, Linux, and OS-X http://wingware.com/downloads/wingide-101/4.1.13-1/binaries However, if you want to learn a general all-around IDE for all sorts of languages, netbeans or some of the other big IDEs are good for that. Depends on your purposes. But I'm only focusing on Python right now. Python also comes with a GUI, called IDLE, which should be already installed. Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jun 14 02:09:56 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Jun 2013 01:09:56 +0100 Subject: [Tutor] find a tutorial for starting with python and netbeans (Igor Fleischer) In-Reply-To: References: Message-ID: On 13/06/13 22:32, I. Alejandro Fleischer wrote: > Hi, Hi, welcome to the list. In future please delete any irrelevant messages from the digest listing. It confuses things and also costs money to those who pay by the byte who have to download lots of irrelevant stuff to read your message. Also its good to know your background. Can you already program in other languages or are you a complete programming beginner? Which OS are you using? Which version of Python are you using? > I'm starting to learn Python, and downloaded Net Beans as an IDE. Any good reason why you did that if you don't know how to use it? It's way overkill for learning Python. Learning one thing at a time is usually easier. > Would you recommend me please a tutorial for a beginning with this two > integrated environments? There are many tutorials listed on the Python web site but which one best suits you depends on: 1) Your starting level 2) Your personal learning style (humorous, concise, theory based, hands-on, etc) 3) Your long term objectives (sys admin automation v games for example) But you could try mine for starters :-) It's aimed at complete beginners, provides background theory, is fairly comprehensive and is moderately serious in tone. It aims to teach programming in general rather than Python specifically. Otherwise try the python web site and/or tell us more about your objectives and background. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jun 14 02:19:25 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Jun 2013 01:19:25 +0100 Subject: [Tutor] sound implementation problems In-Reply-To: References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> Message-ID: On 13/06/13 18:56, Jim Mooney wrote: > tripped me up. If you're using an IDE or editor, mine has the > unfortunate habit of loading in its own directory, and having no option > to automatically access files from my program directory. It saves a > program into the last used directory, This is a function of the IDE application itself > but looks for sounds in its own directory. And this is a function of the interpreter that the IDE is using to execute your code. The IDE has no direct control over that. It's important when using an IDE to appreciate the bits of your workflow that are being done by the IDE code and the bits being done by the interpreter that the IDE uses to execute your code. > So use the Full Path to your sound file, and avoid that possible > problem. This is good practice in any program you write. Either derive the full path or set the working directory prior to accessing the files. Full paths are ultimately the only sure way. > I have a startup script that now stays in my program directory, > though. Of course, if you have an IDE or editor that lets you set the > default directory that's no problem. That's a dodgy way to solve the problem since if you change IDE or run the program outside the IDE that startup script will likely get forgotten and not be used. Remember you are not expected to use an IDE for anything other than developing the code, its not intended to be a runtime environment. Relying on the IDE is a bad habit to develop. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Fri Jun 14 02:33:18 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 14 Jun 2013 10:33:18 +1000 Subject: [Tutor] find a tutorial for starting with python and netbeans (Igor Fleischer) In-Reply-To: References: Message-ID: <51BA64CE.6010500@pearwood.info> On 14/06/13 07:32, I. Alejandro Fleischer wrote: > Hi, > > Im starting to learn Python, and downloaded Net Beans as an IDE. > Would you recomend me please a tutorial for a begining with this two > integrated enviroments? > > Thank you very much. [trimmed almost FIVE PAGES of quoted text] Alejandro, please do not reply to digests without deleting the unnecessary quoted text. We have already see all the messages in the digest, we don't need to see them again copied in your email. I'm afraid I don't know anything about Net Beans, so I can't help you there. But for general Python tutorials, you can start here: http://docs.python.org/2/tutorial/index.html If you are using Python 3, you should start here instead: http://docs.python.org/3/tutorial/index.html Also try this: http://www.alan-g.me.uk/ Good luck, and feel free to come back with any questions! (I recommend that you change your subscription settings away from Digest mode to individual emails. It makes it MUCH easier to carry on a conversation, asking questions and receiving replies, with individual emails.) -- Steven From dragondon at dragondon.net Fri Jun 14 02:47:25 2013 From: dragondon at dragondon.net (DragonDon) Date: Fri, 14 Jun 2013 09:47:25 +0900 Subject: [Tutor] For those who downloaded the game code... Message-ID: Seems I made a rather dumb mistake and uploaded a version of the core code that was a partial conversion for the next update, and thus failed miserably when you ran it. I am mobile but did a quick edit and updated the link with something that at least works and doesn't throw errors immediately. Thanks for your patience and efforts! DragonDon -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Fri Jun 14 05:55:25 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Thu, 13 Jun 2013 20:55:25 -0700 Subject: [Tutor] sound implementation problems In-Reply-To: References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> Message-ID: Alan Gauld That's a dodgy way to solve the problem since if you change IDE or run the > program outside the IDE that startup script will likely get forgotten and > not be used. Remember you are not expected to use > an IDE for anything other than developing the code, its not > intended to be a runtime environment. Relying on the IDE is > a bad habit to develop. > Got me already ;') I reinstalled Py2.7 since there are too many things not available yet for Py3.3 - but I know which one is loading at the command line since I specify Python2.7 or Python3.3 (The Activestate dist copies and renames one of the Pys so that's clear - I just went and copied and renamed the other - along with pip) My IDE startup script has been changed to also go to the proper working directory. BUT - Py 3.3 at the command prompt uses my 3.3 working directory, and Py 2.7 ALSO uses the 3.3 working directory, which is not what I want, obviously. Those are two different sets of scripts that won't always play together. Is there a way to set up each different interpreter, either Py 3.3 or Py 2.2, to automatically change to a particular working directory when you call it - with a command line switch for instance? I can os.chdir after it starts, of course, but that's a drag and I'll forget to do it at some point. If I can do that from the call to Python I can make a batch file for each one, with two different names - and easy typing ones like Py27 and Py33 ;') I see one possible candidate in python --help -c cmd : program passed in as string (terminates option list) But what does "program passed in as a string(terminates option list)" mean? How do I stringify import os > os.chdir('my directory') ? That's unclear to me. Speaking of Py distributions I used ActiveState for various reasons, but I looked at Enthought Canopy and was really annoyed. You can go over their entire website and they don't tell you which Python version it's for - 2.7 and 3.3 being a bit different. It's almost like they hide it. ActiveState makes it clear so I used them. I'm pretty sure Canopy is for 2.7 but I'm not going to do a huge download on a slow connection when they don't tell you. -- Jim A noun is just a verb with the hiccups -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Fri Jun 14 06:53:32 2013 From: davea at davea.name (Dave Angel) Date: Fri, 14 Jun 2013 00:53:32 -0400 Subject: [Tutor] sound implementation problems In-Reply-To: References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> Message-ID: <51BAA1CC.6070904@davea.name> On 06/13/2013 11:55 PM, Jim Mooney wrote: > Alan Gauld > > That's a dodgy way to solve the problem since if you change IDE or run the >> program outside the IDE that startup script will likely get forgotten and >> not be used. Remember you are not expected to use >> an IDE for anything other than developing the code, its not >> intended to be a runtime environment. Relying on the IDE is >> a bad habit to develop. >> > > Got me already ;') I reinstalled Py2.7 since there are too many things not > available yet for Py3.3 - but I know which one is loading at the command > line since I specify Python2.7 or Python3.3 (The Activestate dist copies > and renames one of the Pys so that's clear Renames one of what "Pys" ? > - I just went and copied and > renamed the other - along with pip) My IDE startup script has been changed > to also go to the proper working directory. What IDE would that be? > > BUT - Py 3.3 at the command prompt Do you mean Py 3.3.bat ? With a space in the program name, even? Or something else? > uses my 3.3 working directory, and Py > 2.7 ALSO uses the 3.3 working directory, which is not what I want, Then why did you write those batch files to change directories at all? What's wrong with getting the current directory from "the actual current directory" ? > obviously. Those are two different sets of scripts that won't always play > together. > > Is there a way to set up each different interpreter, either Py 3.3 or Py > 2.2, to automatically change to a particular working directory when you > call it - with a command line switch for instance? I can os.chdir after it > starts, of course, but that's a drag and I'll forget to do it at some > point. So you're intending that all the 2.7 scripts you write will use the same current directory? Regardless of the wishes of the author/user? If I can do that from the call to Python I can make a batch file for > each one, with two different names - and easy typing ones like Py27 and > Py33 ;') > > I see one possible candidate in python --help > -c cmd : program passed in as string (terminates option list) > > But what does "program passed in as a string(terminates option list)" mean? > How do I stringify import os > os.chdir('my directory') ? That's unclear to > me. > > Speaking of Py distributions I used ActiveState for various reasons, but I > looked at Enthought Canopy and was really annoyed. You can go over their > entire website and they don't tell you which Python version it's for - 2.7 > and 3.3 being a bit different. It's almost like they hide it. ActiveState > makes it clear so I used them. I'm pretty sure Canopy is for 2.7 but I'm > not going to do a huge download on a slow connection when they don't tell > you. > > I don't understand your problem at all. Current directory should nearly always be decided by the user of the code, and should have nothing to do with either the location of the interpreter or the location of the script. And in the 1% of scripts where you cannot figure out how to work with that, you can add the two lines to the beginning of the script. (And lots more lines to the documentation for the script) As for how the unknown IDE decides what to make the current directory when running a particular script, that presumably is the job of the project file. If it forces all scripts to run in the same directory, then contact the author and ask for an update. As others have said, many times the files your script wants to manipulate will go in locations determined at run time, and not relative to the current directory. The current directory should only be used as a target (if at all) for those files you the user wants to create explicitly. In that case, he decides their location by switching to that directory. What I really detest (as a user) is programs that allow me to specify the filename, but won't let me specify a complete path, instead making their own decision on file path. So filename completion won't work, and any intuitive understanding of where this named file will go goes up in smoke. -- DaveA From fomcl at yahoo.com Fri Jun 14 10:48:13 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 14 Jun 2013 01:48:13 -0700 (PDT) Subject: [Tutor] regex grouping/capturing In-Reply-To: <51BA0ABE.9010702@gmail.com> References: <1371136176.25009.YahooMailNeo@web163804.mail.gq1.yahoo.com> <51BA0ABE.9010702@gmail.com> Message-ID: <1371199693.55970.YahooMailNeo@web163802.mail.gq1.yahoo.com> ----- Original Message ----- > From: Andreas Perstinger > To: tutor at python.org > Cc: > Sent: Thursday, June 13, 2013 8:09 PM > Subject: Re: [Tutor] regex grouping/capturing > > On 13.06.2013 17:09, Albert-Jan Roskam wrote: >> I have a string of the form "required optional3 optional2 optional1 >> optional3" ('optional' may be any kind of string, so it's > not simply >> 'optional\d+'. >> I would like to use a regex so I can distinguish groups. Desired >> outcome: ('required', 'optional3', 'optional2', > 'optional1', >> 'optional3'). Below is? a fragment of the many things I have tried. > [SNIP] >> How can I make this work? > > If you really want to use a regex: >>>> import re >>>> s = "required optional3 optional2 optional1 optional3" >>>> s2 = "required optional1 optional2 optional3" >>>> pattern = "required|optional1|optional2|optional3" >>>> re.findall(pattern, s) > ['required', 'optional3', 'optional2', > 'optional1', 'optional3'] >>>> re.findall(pattern, s2) > ['required', 'optional1', 'optional2', > 'optional3'] Hi Andreas, thanks for your reply. I am trying to create a pygments regex lexer. It?parses code and classfies it (in my case) commands, subcommands and keywords. AFAIK, re.findall can't be used with pygments, but maybe I am mistaken. The quantifier of groups (a plus sign in my case) just works different from what I expect. It seems that only optional (with a "?") groups can be used, not other quantifiers. Here's a simplfied example of the 'set' command that I would like to parse. ? >>> s = 'set workspace = 6148 header on.' >>> r = "(set)\s+(header|workspace)+\s*=?\s*.*\.$" >>> re.search(r, s, re.I).groups() [('set', 'workspace')]? # desired output: [('set', 'workspace', 'header')] >>> r = "(set)\s+(?:(header|workspace)\s*=?\s*.*)+\.$" >>> re.search(r, s, re.I).groups() ('set', 'workspace')? # grrr, still no luck? From andipersti at gmail.com Fri Jun 14 14:23:46 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Fri, 14 Jun 2013 14:23:46 +0200 Subject: [Tutor] regex grouping/capturing In-Reply-To: <1371199693.55970.YahooMailNeo@web163802.mail.gq1.yahoo.com> References: <1371136176.25009.YahooMailNeo@web163804.mail.gq1.yahoo.com> <51BA0ABE.9010702@gmail.com> <1371199693.55970.YahooMailNeo@web163802.mail.gq1.yahoo.com> Message-ID: <51BB0B52.6070804@gmail.com> On 14.06.2013 10:48, Albert-Jan Roskam wrote: > I am trying to create a pygments regex lexer. Well, writing a lexer is a little bit more complex than your original example suggested. > Here's a simplfied example of the 'set' command that I would like to > parse. >>>> s = 'set workspace = 6148 header on.' As I understand it the order of the parts following "set" is arbitrary, i. e. set workspace = 6148 header on. is equivalent to set header on workspace = 6148. correct? I'm not sure if a single regex can capture this. But looking at the pygments docs I think you need something along the lines of (adapt the token names to your need): class ExampleLexer(RegexLexer): tokens = { 'root': [ (r'\s+', Text), (r'set', Keyword), (r'workspace|header', Name), (r'\S+', Text), ] } Does this help? Bye, Andreas From md123 at nycap.rr.com Fri Jun 14 14:45:50 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 14 Jun 2013 08:45:50 -0400 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51BA05D2.3030208@davea.name> References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com> <51B9B968.5070908@davea.name> <51B9D91C.8030707@nycap.rr.com> <51B9E403.4070003@davea.name> <51B9F42F.3000001@nycap.rr.com> <51BA05D2.3030208@davea.name> Message-ID: <51BB107E.3030309@nycap.rr.com> i am trying to figure a way to to use a list to log/print my data: # tmplist = [time, 'nac', 'tgid', 'source', 'dest', 'algid'] is what we want tmplist = [] tmplist.append((str(strftime("%Y-%m-%d %H:%M:%S", localtime()))) tmplist.append(field_values["nac"]) tmplist.append(field_values["tgid"]) tmplist.append(field_values["source"]) tmplist.append(field_values["dest"]) tmplist.append(field_values["algid"]) When i run the code program dies like this: tmplist.append(field_values["nac"]) ^ SyntaxError: invalid syntax I cant figure why it stops on the third line above? Anyone have an idea? Thanks! From md123 at nycap.rr.com Fri Jun 14 15:27:25 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 14 Jun 2013 09:27:25 -0400 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com><51B9B968.5070908@davea.name> <51B9D91C.8030707@nycap.rr.com><51B9E403.4070003@davea.name> <51B9F42F.3000001@nycap.rr.com><51BA05D2.3030208@davea.name> <51BB107E.3030309@nycap.rr.com> Message-ID: <51BB1A3D.7070108@nycap.rr.com> im sorry i dont get it. there is too many brackets in this lin: tmplist.append(field_values["nac"]) Thats where the error is but i dont see too many brackets? On 06/14/2013 08:56 AM, Flynn, Stephen (L & P - IT) wrote: > Not enough closing brackets on the previous line... or actually too many > opening brackets - you don't need all those that you have there already. > > >> # tmplist = [time, 'nac', 'tgid', 'source', 'dest', 'algid'] is what > we >> want >> tmplist = [] >> tmplist.append((str(strftime("%Y-%m-%d %H:%M:%S", > localtime()))) >> tmplist.append(field_values["nac"]) >> tmplist.append(field_values["tgid"]) >> tmplist.append(field_values["source"]) >> tmplist.append(field_values["dest"]) >> tmplist.append(field_values["algid"]) >> >> When i run the code program dies like this: >> >> tmplist.append(field_values["nac"]) >> ^ >> SyntaxError: invalid syntax >> >> I cant figure why it stops on the third line above? Anyone have an > idea? >> Thanks! > > > This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. > > Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. > > All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. > > Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. > From dfjennings at gmail.com Fri Jun 14 15:36:57 2013 From: dfjennings at gmail.com (Don Jennings) Date: Fri, 14 Jun 2013 09:36:57 -0400 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51BB1A3D.7070108@nycap.rr.com> References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com><51B9B968.5070908@davea.name> <51B9D91C.8030707@nycap.rr.com><51B9E403.4070003@davea.name> <51B9F42F.3000001@nycap.rr.com><51BA05D2.3030208@davea.name> <51BB107E.3030309@nycap.rr.com> <51BB1A3D.7070108@nycap.rr.com> Message-ID: On Jun 14, 2013, at 9:27 AM, Matt D wrote: > im sorry i dont get it. there is too many brackets in this lin: > > tmplist.append(field_values["nac"]) > > Thats where the error is but i dont see too many brackets? Please don't top post. The error is not on this line, but on the previous one. See below. > > On 06/14/2013 08:56 AM, Flynn, Stephen (L & P - IT) wrote: >> Not enough closing brackets on the previous line... or actually too many >> opening brackets - you don't need all those that you have there already. >> >> >>> # tmplist = [time, 'nac', 'tgid', 'source', 'dest', 'algid'] is what >> we >>> want >>> tmplist = [] >>> tmplist.append((str(strftime("%Y-%m-%d %H:%M:%S", >> localtime()))) Count the number of opening and closing parentheses. I count five opening ones, and only four closing. I believe the extraneous one is right before "str". Take care, Don From steve at pearwood.info Fri Jun 14 15:53:27 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 14 Jun 2013 23:53:27 +1000 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51BB107E.3030309@nycap.rr.com> References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com> <51B9B968.5070908@davea.name> <51B9D91C.8030707@nycap.rr.com> <51B9E403.4070003@davea.name> <51B9F42F.3000001@nycap.rr.com> <51BA05D2.3030208@davea.name> <51BB107E.3030309@nycap.rr.com> Message-ID: <51BB2057.5080303@pearwood.info> On 14/06/13 22:45, Matt D wrote: > tmplist = [] > tmplist.append((str(strftime("%Y-%m-%d %H:%M:%S", localtime()))) > tmplist.append(field_values["nac"]) [...] > > When i run the code program dies like this: > > tmplist.append(field_values["nac"]) > ^ > SyntaxError: invalid syntax > > I cant figure why it stops on the third line above? Anyone have an idea? When you get a syntax error, sometimes the actual problem occurs on the PREVIOUS line, but isn't detected until this line. Go back to the previous line, the one containing strftime, and match up each pair of round brackets. How many Open brackets ( do you count? How many Close brackets ) do you count? -- Steven From alan.gauld at btinternet.com Fri Jun 14 16:27:32 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Jun 2013 15:27:32 +0100 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51BB1A3D.7070108@nycap.rr.com> References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com><51B9B968.5070908@davea.name> <51B9D91C.8030707@nycap.rr.com><51B9E403.4070003@davea.name> <51B9F42F.3000001@nycap.rr.com><51BA05D2.3030208@davea.name> <51BB107E.3030309@nycap.rr.com> <51BB1A3D.7070108@nycap.rr.com> Message-ID: On 14/06/13 14:27, Matt D wrote: > im sorry i dont get it. there is too many brackets in this lin: > > tmplist.append(field_values["nac"]) > > Thats where the error is No, that's where Python *detected* that an error existed. The actual error is on the previous line. This is quite common, especially in cases of mismatched parens or quotes. There is a difference between where an error *occurs* and where an error is *detected*. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From md123 at nycap.rr.com Fri Jun 14 16:37:04 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 14 Jun 2013 10:37:04 -0400 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com><51B9B968.5070908@davea.name> <51B9D91C.8030707@nycap.rr.com><51B9E403.4070003@davea.name> <51B9F42F.3000001@nycap.rr.com><51BA05D2.3030208@davea.name> <51BB107E.3030309@nycap.rr.com> <51BB1A3D.7070108@nycap.rr.com> Message-ID: <51BB2A90.7030700@nycap.rr.com> On 06/14/2013 10:27 AM, Alan Gauld wrote: > On 14/06/13 14:27, Matt D wrote: >> im sorry i dont get it. there is too many brackets in this lin: >> >> tmplist.append(field_values["nac"]) >> >> Thats where the error is > > No, that's where Python *detected* that an error existed. > The actual error is on the previous line. This is quite > common, especially in cases of mismatched parens or quotes. > > There is a difference between where an error *occurs* and > where an error is *detected*. > got it. the error can be in the previous line. its running now. Thanks guys! From md123 at nycap.rr.com Fri Jun 14 16:48:30 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 14 Jun 2013 10:48:30 -0400 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com><51B9B968.5070908@davea.name> <51B9D91C.8030707@nycap.rr.com><51B9E403.4070003@davea.name> <51B9F42F.3000001@nycap.rr.com><51BA05D2.3030208@davea.name> <51BB107E.3030309@nycap.rr.com> <51BB1A3D.7070108@nycap.rr.com> Message-ID: <51BB2D3E.3090108@nycap.rr.com> Hey, here is a snip of my code. #logger code---------------------------------------------- # first new line #self.logfile.write('\n') # date and time #self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", gmtime())))) # blah = [time, 'nac', 'tgid', 'source', 'dest', 'algid'] is what we want tmplist = [] tmplist.append(str(strftime("%Y-%m-%d %H:%M:%S", localtime()))) tmplist.append(field_values["nac"]) tmplist.append(field_values["tgid"]) tmplist.append(field_values["source"]) tmplist.append(field_values["dest"]) tmplist.append(field_values["algid"]) #this prints the current row of data to the terminal #print tmplist # this prints the current row of data to the csv file for item in tmplist: self.logfile.write('%s,' % (str(item))) self.logfile.write('\n') # loop through each of the TextCtrl objects #for k,v in self.fields.items(): # get the value of the current TextCtrl field # f = field_values.get(k, None) #if f: # check if k is the field you want # output the value with trailing comma #self.logfile.write('%s,'%(str(f))) # self.logfile.write('\n') # here is where you would put it #end logger code------------------------------- i know its ugly. but there is two ways to log here. one makes a list (current) and the other (commented out) loops through the TextCtrls and writes. is their a better way than what i have here? the TextCtrl fields get their values from a pickle. From dotancohen at gmail.com Fri Jun 14 17:23:56 2013 From: dotancohen at gmail.com (Dotan Cohen) Date: Fri, 14 Jun 2013 18:23:56 +0300 Subject: [Tutor] What are these two string-formatting styles called? Message-ID: What are these two string-formatting styles called? '%.3f' % x '{0:.3f}'.format(x) Where in the fine manual is their names shown? Thanks! -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From alan.gauld at btinternet.com Fri Jun 14 17:43:32 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Jun 2013 16:43:32 +0100 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51BB2A90.7030700@nycap.rr.com> References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com><51B9B968.5070908@davea.name> <51B9D91C.8030707@nycap.rr.com><51B9E403.4070003@davea.name> <51B9F42F.3000001@nycap.rr.com><51BA05D2.3030208@davea.name> <51BB107E.3030309@nycap.rr.com> <51BB1A3D.7070108@nycap.rr.com> <51BB2A90.7030700@nycap.rr.com> Message-ID: On 14/06/13 15:37, Matt D wrote: >> There is a difference between where an error *occurs* and >> where an error is *detected*. >> > got it. the error can be in the previous line. Yeah, or more. I've seen errors that originated 3 or 4 lines back from the reported location. So just remember that if you can't spot it immediately start working backwards. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cybervigilante at gmail.com Fri Jun 14 17:43:40 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 14 Jun 2013 08:43:40 -0700 Subject: [Tutor] sound implementation problems In-Reply-To: <51BAA1CC.6070904@davea.name> References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> <51BAA1CC.6070904@davea.name> Message-ID: On 13 June 2013 21:53, Dave Angel wrote: > On 06/13/2013 11:55 PM, Jim Mooney wrote: > >> Alan Gauld >> > This is for my own convenience on my own machine. As a former webmaster I'm of course used to idiot-proofing anything released into the wild so it is usable by everyone on every machine ;') The script to change directories for PyScripter is a PyScripter startup file, not a bat file. I meant I needed an additional bat file that would do the same for MS-DOS. As usual I was marvelously unclear. But anyway, I figured it out. Here is the batch for starting 2.7 and ensuring its in the 2.7 working directory. Since I'm running 2.7 and 3.3 I just want to make sure I don't trip over my own feet. I know I could do all this with virtualenv, but I'd rather a simple hack than all that mess. The two Pys are now separated in every possible way: MS batch file py27.bat python2.7 -i -c "import os;os.chdir('c:/python27/jimprogs');del(os) -- Jim A noun is just a verb with the hiccups -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Jun 14 17:46:50 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 15 Jun 2013 01:46:50 +1000 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: Message-ID: <51BB3AEA.8040808@pearwood.info> On 15/06/13 01:23, Dotan Cohen wrote: > What are these two string-formatting styles called? > '%.3f' % x > '{0:.3f}'.format(x) "String formatting", and "string formatting" *wink* Sometimes the first is called "string interpolation". Sometimes it is called "printf-style formatting", after the C function. > Where in the fine manual is their names shown? Thanks! Like most things to do with strings, the place to start is the section on strings: http://docs.python.org/3/library/stdtypes.html#text-sequence-type-str which leads to: http://docs.python.org/3/library/stdtypes.html#str.format and http://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting For Python 2, start here instead: http://docs.python.org/2/library/stdtypes.html -- Steven From eryksun at gmail.com Fri Jun 14 17:49:29 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 14 Jun 2013 11:49:29 -0400 Subject: [Tutor] sound implementation problems In-Reply-To: References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> Message-ID: On Thu, Jun 13, 2013 at 11:55 PM, Jim Mooney wrote: > > My IDE startup script has been changed to also go to the proper working > directory. > BUT - Py 3.3 at the command prompt uses my 3.3 working directory, and Py 2.7 > ALSO uses the 3.3 working directory, which is not what I want, obviously. > Those are two different sets of scripts that won't always play together. Why would running python.exe change the current working directory? Anyway, I don't know much about ActivePython, so I shouldn't even ask. > Is there a way to set up each different interpreter, either Py 3.3 or Py > 2.2, to automatically change to a particular working directory when you call > it - with a command line switch for instance? I can os.chdir after it > starts, of course, but that's a drag and I'll forget to do it at some point. > If I can do that from the call to Python I can make a batch file for each > one, with two different names - and easy typing ones like Py27 and Py33 ;') Is this for imports relative to the current directory? If so I recommend using the user site-packages in your profile directory. Run the following to print its location: import site print(site.getusersitepackages()) It's probably the following directory (but I know next to nothing about ActivePython): "%appdata%\Python\Python??\site-packages" (substitute the 2-digit version number for ??) Using this directory avoids sharing paths between interpreters via the PYTHONPATH environment variable. Just add a .pth file containing the absolute path to your personal library of modules/packages for Python??. > I see one possible candidate in python --help > -c cmd : program passed in as string (terminates option list) > > But what does "program passed in as a string(terminates option list)" mean? > How do I stringify import os > os.chdir('my directory') ? That's unclear to > me. I don't agree with the end goal here, but running a micro-script from the shell can be convenient, especially when paired with macros/aliases. Here's how to start Python in a particular directory: C:\>python -i -c "import os; os.chdir('C:/Python33')" >>> os.getcwd() 'C:\\Python33' -i drops into interactive mode after the command completes. In Windows you have to use double quotes for the argument after -c. But single-quotes are fine for string literals within the command. The Windows command-line is a bit weird in that it stores per-executable input history and aliases in the console itself instead of in the shell. In some ways it's convenient because it lets you define aliases that target a particular exe, such as python.exe or cmd.exe. And if you quit and restart (the program, not the console window), it remembers your history (press F7 for a pop-up scrollbox). Anyway, the interface should be familiar to anyone who ever used MS-DOS. It's doskey (no, it's not a DOS program): C:\>doskey calc=c:\python33\python -c "from cmath import *;print($*)" C:\>calc e**(1j*pi/3) (0.5000000000000001+0.8660254037844386j) $1 is parameter 1, and so on, and $* globs all of the parameters. From cybervigilante at gmail.com Fri Jun 14 18:01:14 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 14 Jun 2013 09:01:14 -0700 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: Message-ID: On 14 June 2013 08:23, Dotan Cohen wrote: > What are these two string-formatting styles called? > '%.3f' % x > '{0:.3f}'.format(x) > The first one is a string Expression, using % as the overloaded operator The second one is a string method, with .format() as the method for a string object put python string expression or python string method in that great teaching tool, Google. I know this since I'm reading that part of my python book right now and can actually remember it. Although I fell asleep on the third page of explanations of the more convoluted ways to use {}, which can get convoluted indeed ;') -- Jim A noun is just a verb with the hiccups -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Fri Jun 14 18:05:58 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 14 Jun 2013 09:05:58 -0700 Subject: [Tutor] sound implementation problems In-Reply-To: References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> Message-ID: On 14 June 2013 08:49, eryksun wrote: > C:\>doskey calc=c:\python33\python -c "from cmath import *;print($*)" > > C:\>calc e**(1j*pi/3) > (0.5000000000000001+0.8660254037844386j) > > Cool. I totally forgot about doskey macros. Still could be useful, and it > looks like they're still in win 7. > -- Jim A noun is just a verb with the hiccups -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Fri Jun 14 18:40:26 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 14 Jun 2013 12:40:26 -0400 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: Message-ID: On Fri, Jun 14, 2013 at 12:01 PM, Jim Mooney wrote: > On 14 June 2013 08:23, Dotan Cohen wrote: >> >> What are these two string-formatting styles called? >> '%.3f' % x >> '{0:.3f}'.format(x) > > > The first one is a string Expression, using % as the overloaded operator > The second one is a string method, with .format() as the method for a string > object The str.format method is one part of the new system; the part that you'll usually interact with. But under the hood there's a fundamental shift that puts the object in control of its formatting via the __format__ special method. This works: >>> from decimal import Decimal >>> '{0:.27f}'.format(Decimal(1).exp()) '2.718281828459045235360287471' or with built-in format(): >>> format(Decimal(1).exp(), '.27f') '2.718281828459045235360287471' while the old way prints the wrong value, given the Decimal object's precision: >>> '%.27f' % Decimal(1).exp() '2.718281828459045090795598298' because it first has to be converted to a machine double-precision float, which has 15 decimal digits of precision (15.95 to be a bit more precise). From cybervigilante at gmail.com Fri Jun 14 19:32:00 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 14 Jun 2013 10:32:00 -0700 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: Message-ID: On 14 June 2013 09:40, eryksun wrote: > > or with built-in format(): > > >>> format(Decimal(1).exp(), '.27f') > '2.718281828459045235360287471' > I didn't know .format() also had a builtin. Are there many methods that are dual like that? On the one hand, it's more memorizing, but on the other it might be a simpler syntax. My little finger has trouble finding the : key. All those odd characters are hard to find - they didn't design keyboards for programming. Maybe someday. Now you're going to tell me there's a programmer's keyboard ;') -- Jim A noun is just a verb with the hiccups -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Jun 14 19:56:34 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 15 Jun 2013 03:56:34 +1000 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: Message-ID: <51BB5952.8070703@pearwood.info> On 15/06/13 03:32, Jim Mooney wrote: > Now you're going to tell me there's a programmer's keyboard ;') http://en.wikipedia.org/wiki/Space-cadet_keyboard http://upload.wikimedia.org/wikipedia/commons/4/47/Space-cadet.jpg http://ageinghacker.net/hacks/apl-keyboard/apl-keyboard-2.jpg http://www.rexswain.com/aplinfo.html APL is a real programming language, and no, it was not intended as a joke. Here's an APL program to print letter diamonds like this: A B B C C B B A And here is the code: mat?1 0??mat?(?mat),0 1?mat??(-??letters)??letters?(?A?'E')??A http://aplwiki.com/Studio/LetterDiamonds -- Steven From cybervigilante at gmail.com Fri Jun 14 20:34:41 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 14 Jun 2013 11:34:41 -0700 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: <51BB5952.8070703@pearwood.info> References: <51BB5952.8070703@pearwood.info> Message-ID: On 14 June 2013 10:56, Steven D'Aprano wrote: > On 15/06/13 03:32, Jim Mooney wrote: > > Now you're going to tell me there's a programmer's keyboard ;') >> > > http://en.wikipedia.org/wiki/**Space-cadet_keyboard > > http://upload.wikimedia.org/**wikipedia/commons/4/47/Space-**cadet.jpg > > > http://ageinghacker.net/hacks/**apl-keyboard/apl-keyboard-2.**jpg > > http://www.rexswain.com/**aplinfo.html > Alas, it looks like development stopped on programmer's keyboards quite a while ago. I guess I'll just wait for voice-command and I can code while I eat a burger. Seriously, Python would be the best adapted for voice command with its indenting and English-like syntax. A one-line javascript program littered with symbols, probably not. You couldn't even think it out to say it. At least I couldn't without typing it down, defeating the whole purpose of voice command. Although the string formatting just mentioned brings you right back to head-spinning one-liners of arbitrary complexity; maybe the best would be voice-command for basice concepts, while using the keyboard for stuff that would twist your tongue. Of course, by the time voice command gets really good, computers will be writing the programs, and programmers will be meta-programming using visual syntax - combining colored and adaptable object blocks in 3-D. Back to playing with blocks. Cool. I'm probably going to hear that's already been done, too ;') Jim "Knock, knock!" "Who's there?" "Me." "We got no room - go away" Three years later "Knock, knock!" "Who's there?" "Nobody" "Plenty of room for nobody - please come in." -------------- next part -------------- An HTML attachment was scrubbed... URL: From northriptl at s.dcsdk12.org Fri Jun 14 20:59:04 2013 From: northriptl at s.dcsdk12.org (student Tyler Northrip) Date: Fri, 14 Jun 2013 12:59:04 -0600 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: <51BB5952.8070703@pearwood.info> Message-ID: In response to your points, voice command using visuals, this idea has been explored before. In the book containment by Christian Cantrell they use methods such as this. The main character places a helmet on his head, and writes code using his mind. Voice command was also used as well. Will these ideas work or even be necessary? Perhaps one day we will create computers that rely solely on our minds, so we would only need to think a command and the computer would carry it out. I remember something similar from 3001: a space odyssey. Other than voice command and our thoughts, there is the idea of having a computer create the program for us. Is it even possible to create a computer capable of this? It would have to be an AI, and would it even have the creativity or ingenuity of a human programmer? Food for thought. On Fri, Jun 14, 2013 at 12:34 PM, Jim Mooney wrote: > On 14 June 2013 10:56, Steven D'Aprano wrote: > >> On 15/06/13 03:32, Jim Mooney wrote: >> >> Now you're going to tell me there's a programmer's keyboard ;') >>> >> >> http://en.wikipedia.org/wiki/**Space-cadet_keyboard >> >> http://upload.wikimedia.org/**wikipedia/commons/4/47/Space-**cadet.jpg >> >> >> http://ageinghacker.net/hacks/**apl-keyboard/apl-keyboard-2.**jpg >> >> http://www.rexswain.com/**aplinfo.html >> > > Alas, it looks like development stopped on programmer's keyboards quite a > while ago. I guess I'll just wait for voice-command and I can code while I > eat a burger. > > Seriously, Python would be the best adapted for voice command with its > indenting and English-like syntax. A one-line javascript program littered > with symbols, probably not. You couldn't even think it out to say it. At > least I couldn't without typing it down, defeating the whole purpose of > voice command. > > Although the string formatting just mentioned brings you right back to > head-spinning one-liners of arbitrary complexity; maybe the best would be > voice-command for basice concepts, while using the keyboard for stuff that > would twist your tongue. > > Of course, by the time voice command gets really good, computers will be > writing the programs, and programmers will be meta-programming using visual > syntax - combining colored and adaptable object blocks in 3-D. Back to > playing with blocks. Cool. > > I'm probably going to hear that's already been done, too ;') > > Jim > "Knock, knock!" "Who's there?" "Me." "We got no room - go away" > Three years later > "Knock, knock!" "Who's there?" "Nobody" "Plenty of room for nobody - > please come in." > > _______________________________________________ > 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 northriptl at s.dcsdk12.org Fri Jun 14 21:03:26 2013 From: northriptl at s.dcsdk12.org (student Tyler Northrip) Date: Fri, 14 Jun 2013 13:03:26 -0600 Subject: [Tutor] Fwd: What are these two string-formatting styles called? In-Reply-To: References: <51BB5952.8070703@pearwood.info> Message-ID: In response to your points, voice command using visuals, this idea has been explored before. In the book containment by Christian Cantrell they use methods such as this. The main character places a helmet on his head, and writes code using his mind. Voice command was also used as well. Will these ideas work or even be necessary? Perhaps one day we will create computers that rely solely on our minds, so we would only need to think a command and the computer would carry it out. I remember something similar from 3001: a space odyssey. Other than voice command and our thoughts, there is the idea of having a computer create the program for us. Is it even possible to create a computer capable of this? It would have to be an AI, and would it even have the creativity or ingenuity of a human programmer? Food for thought. _______________________________________________ > 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 cybervigilante at gmail.com Fri Jun 14 21:09:35 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 14 Jun 2013 12:09:35 -0700 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: <51BB5952.8070703@pearwood.info> Message-ID: 14 June 2013 11:59, student Tyler Northrip wrote: > In response to your points, voice command using visuals, this idea has > been explored before. In the book containment by Christian Cantrell theyuse methods such as this. The main character places a helmet on his head, > and writes code using his mind. Voice command was also used as well. > Of course, the real consideration, for those thinking of programming as a career path, is whether programmers will be as obsolete at gaslighters in twenty years - or will they be doing some sort of weird meta-programming? Although this is getting marvelously off-topic, so I'll end it there ;') -- Jim Then there is the lysdexic keyboard, which corrects letter-reversals as you tpye them... -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Fri Jun 14 21:14:48 2013 From: davea at davea.name (Dave Angel) Date: Fri, 14 Jun 2013 15:14:48 -0400 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51BB2D3E.3090108@nycap.rr.com> References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com><51B9B968.5070908@davea.name> <51B9D91C.8030707@nycap.rr.com><51B9E403.4070003@davea.name> <51B9F42F.3000001@nycap.rr.com><51BA05D2.3030208@davea.name> <51BB107E.3030309@nycap.rr.com> <51BB1A3D.7070108@nycap.rr.com> <51BB2D3E.3090108@nycap.rr.com> Message-ID: <51BB6BA8.6050100@davea.name> On 06/14/2013 10:48 AM, Matt D wrote: > Hey, > here is a snip of my code. > > #logger code---------------------------------------------- > # first new line > #self.logfile.write('\n') > # date and time > #self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", gmtime())))) > # blah = [time, 'nac', 'tgid', 'source', 'dest', 'algid'] is what we want > tmplist = [] > tmplist.append(str(strftime("%Y-%m-%d %H:%M:%S", localtime()))) > tmplist.append(field_values["nac"]) > tmplist.append(field_values["tgid"]) > tmplist.append(field_values["source"]) > tmplist.append(field_values["dest"]) > tmplist.append(field_values["algid"]) > tmplist is an unnecessary complication. Did you look at my sample loop, which I'll repeat here with a correction: for k in FIELD_LIST_NAMES: # get the value of the current TextCtrl field f = field_values.get(k, None) if not f is None: #output the value with trailing comma self.logfile.write('%s,'%(str(f))) else: self.logfile.write(",") self.logfile.write("\n") This code preserves your original feature of not crashing when the C++ program fails to fill in all your expected keys. It also makes sure there will be unadorned commas for missing fields, making it possible for a spreadsheet to read the columns correctly. If you want to populate a list first, by all means do so, but do it in a loop, using the FIELD_LIST_NAMES as keys. One thing I didn't handle was the date field. I'd do that by adding it to the field_values dict, or to a copy of it. That way, it's all consistent, even though one field comes from local and the rest from the pickle. > -- DaveA From md123 at nycap.rr.com Fri Jun 14 21:59:39 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 14 Jun 2013 15:59:39 -0400 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51BB6BA8.6050100@davea.name> References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com><51B9B968.5070908@davea.name> <51B9D91C.8030707@nycap.rr.com><51B9E403.4070003@davea.name> <51B9F42F.3000001@nycap.rr.com><51BA05D2.3030208@davea.name> <51BB107E.3030309@nycap.rr.com> <51BB1A3D.7070108@nycap.rr.com> <51BB2D3E.3090108@nycap.rr.com> <51BB6BA8.6050100@davea.name> Message-ID: <51BB762B.4060805@nycap.rr.com> On 06/14/2013 03:14 PM, Dave Angel wrote: > On 06/14/2013 10:48 AM, Matt D wrote: >> Hey, >> here is a snip of my code. >> >> #logger code---------------------------------------------- >> # first new line >> #self.logfile.write('\n') >> # date and time >> #self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", >> gmtime())))) >> # blah = [time, 'nac', 'tgid', 'source', 'dest', 'algid'] is >> what we want >> tmplist = [] >> tmplist.append(str(strftime("%Y-%m-%d %H:%M:%S", localtime()))) >> tmplist.append(field_values["nac"]) >> tmplist.append(field_values["tgid"]) >> tmplist.append(field_values["source"]) >> tmplist.append(field_values["dest"]) >> tmplist.append(field_values["algid"]) >> > > tmplist is an unnecessary complication. Did you look at my sample loop, > which I'll repeat here with a correction: > > > for k in FIELD_LIST_NAMES: > # get the value of the current TextCtrl field > f = field_values.get(k, None) > if not f is None: > #output the value with trailing comma > self.logfile.write('%s,'%(str(f))) > else: > self.logfile.write(",") > self.logfile.write("\n") > > This code preserves your original feature of not crashing when the C++ > program fails to fill in all your expected keys. It also makes sure > there will be unadorned commas for missing fields, making it possible > for a spreadsheet to read the columns correctly. > > If you want to populate a list first, by all means do so, but do it in a > loop, using the FIELD_LIST_NAMES as keys. > > One thing I didn't handle was the date field. I'd do that by adding it > to the field_values dict, or to a copy of it. That way, it's all > consistent, even though one field comes from local and the rest from the > pickle. > > yes acutally this templist business broke my code. the TectCtrls in the traffic panel would were not being populated and the logfile.csv was empty. So should i replace: #logger code--------------- # first new line self.logfile.write('\n') # date and time self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", localtime())))) # loop through each of the TextCtrl objects for k,v in self.fields.items(): # get the value of the current TextCtrl field f = field_values.get(k, None) if f: # output the value with trailing comma self.logfile.write('%s,'%(str(f))) #end logger code ---------------- With the code you posted above? I am pretty sure that the reason i don't get the 'source' and 'dest' fields is because of this: #if the field 'duid' == 'hdu', then clear all the fields if field_values['duid'] == 'hdu': self.clear() since the 'source' and 'dest' are in the LUD1 and not the HDU so it doesn't update when the LDU1 comes through (if the LDU1) does actually get serialized. still haven't found a way to get to view the serialized data. From davea at davea.name Fri Jun 14 22:17:12 2013 From: davea at davea.name (Dave Angel) Date: Fri, 14 Jun 2013 16:17:12 -0400 Subject: [Tutor] Fwd: Re: Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51BB762B.4060805@nycap.rr.com> References: <51B947E8.2040807@nycap.rr.com> <51B94832.6070308@nycap.rr.com><51B9B968.5070908@davea.name> <51B9D91C.8030707@nycap.rr.com><51B9E403.4070003@davea.name> <51B9F42F.3000001@nycap.rr.com><51BA05D2.3030208@davea.name> <51BB107E.3030309@nycap.rr.com> <51BB1A3D.7070108@nycap.rr.com> <51BB2D3E.3090108@nycap.rr.com> <51BB6BA8.6050100@davea.name> <51BB762B.4060805@nycap.rr.com> Message-ID: <51BB7A48.9060709@davea.name> On 06/14/2013 03:59 PM, Matt D wrote: > On 06/14/2013 03:14 PM, Dave Angel wrote: >> On 06/14/2013 10:48 AM, Matt D wrote: >>> Hey, >>> here is a snip of my code. >>> >>> #logger code---------------------------------------------- >>> # first new line >>> #self.logfile.write('\n') >>> # date and time >>> #self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", >>> gmtime())))) >>> # blah = [time, 'nac', 'tgid', 'source', 'dest', 'algid'] is >>> what we want >>> tmplist = [] >>> tmplist.append(str(strftime("%Y-%m-%d %H:%M:%S", localtime()))) >>> tmplist.append(field_values["nac"]) >>> tmplist.append(field_values["tgid"]) >>> tmplist.append(field_values["source"]) >>> tmplist.append(field_values["dest"]) >>> tmplist.append(field_values["algid"]) >>> >> >> tmplist is an unnecessary complication. Did you look at my sample loop, >> which I'll repeat here with a correction: >> >> >> for k in FIELD_LIST_NAMES: >> # get the value of the current TextCtrl field >> f = field_values.get(k, None) >> if not f is None: >> #output the value with trailing comma >> self.logfile.write('%s,'%(str(f))) >> else: >> self.logfile.write(",") >> self.logfile.write("\n") >> >> This code preserves your original feature of not crashing when the C++ >> program fails to fill in all your expected keys. It also makes sure >> there will be unadorned commas for missing fields, making it possible >> for a spreadsheet to read the columns correctly. >> >> If you want to populate a list first, by all means do so, but do it in a >> loop, using the FIELD_LIST_NAMES as keys. >> >> One thing I didn't handle was the date field. I'd do that by adding it >> to the field_values dict, or to a copy of it. That way, it's all >> consistent, even though one field comes from local and the rest from the >> pickle. >> >> > yes acutally this templist business broke my code. the TectCtrls in the > traffic panel would were not being populated and the logfile.csv was > empty. > > So should i replace: > > #logger code--------------- > # first new line > self.logfile.write('\n') > # date and time > self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", > localtime())))) > # loop through each of the TextCtrl objects > for k,v in self.fields.items(): > # get the value of the current TextCtrl field > f = field_values.get(k, None) > if f: > # output the value with trailing comma > self.logfile.write('%s,'%(str(f))) > #end logger code ---------------- > > With the code you posted above? Don't replace anything till you understand it. But if you think you do then my code replaces the part starting at the for loop. > > I am pretty sure that the reason i don't get the 'source' and 'dest' > fields is because of this: > > #if the field 'duid' == 'hdu', then clear all the fields > if field_values['duid'] == 'hdu': > self.clear() > > since the 'source' and 'dest' are in the LUD1 and not the HDU so it > doesn't update when the LDU1 comes through (if the LDU1) does actually > get serialized. I don't know anything about LUDI or HDU. But perhaps you're saying that some fields aren't in every pickle, but the value in the csv for each line should be the last one pickled. In that case, you have a big logic flaw in your code. When you output your stuff to the logfile, you use only the values in field_values, not any values previously stored in self.fields. Do you perhaps mean that whenever a value is missing from the pickle, you want to use the one from self.fields? If you happened to want exactly this, you could add the two middle lines as below. something like: f = field_values.get(k, None) if f is None: #add me f = self.fields.get(k, None) #add me if not f is None: But clearly, that's much more specific than you've ever been. There are also better ways to do it if that's exactly what you want. > still haven't found a way to get to view the serialized > data. print field_values, right at the beginning of update(). Or you could pretty it up, by looping through its items(). -- DaveA From davea at davea.name Fri Jun 14 22:35:21 2013 From: davea at davea.name (Dave Angel) Date: Fri, 14 Jun 2013 16:35:21 -0400 Subject: [Tutor] sound implementation problems In-Reply-To: References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> <51BAA1CC.6070904@davea.name> Message-ID: <51BB7E89.4000503@davea.name> On 06/14/2013 11:43 AM, Jim Mooney wrote: > On 13 June 2013 21:53, Dave Angel wrote: > >> On 06/13/2013 11:55 PM, Jim Mooney wrote: >> >>> Alan Gauld >>> >> > This is for my own convenience on my own machine. As a former webmaster I'm > of course used to idiot-proofing anything released into the wild so it is > usable by everyone on every machine ;') > > The script to change directories for PyScripter is a PyScripter startup > file, not a bat file. I meant I needed an additional bat file that would do > the same for MS-DOS. You're not running MS-DOS. You're running a DOS BOX under Windows, which is a cmd shell. As usual I was marvelously unclear. But anyway, I > figured it out. Here is the batch for starting 2.7 and ensuring its in the > 2.7 working directory. Since I'm running 2.7 and 3.3 I just want to make > sure I don't trip over my own feet. I know I could do all this with > virtualenv, but I'd rather a simple hack than all that mess. The two Pys > are now separated in every possible way: > > MS batch file py27.bat > > python2.7 -i -c "import os;os.chdir('c:/python27/jimprogs');del(os) > That seems rather silly. Why not ------py27.bat------- c: cd \python27\jimprogs python2.7 %$ --------------------- I probably don't have the right syntax for %$, but there is a pseudo-variable you can use which means "all the parameters that were on the batch file invocation. This is the generalization of %1 %2 %3 %4 There's also a pair of cmd.exe internal commands, with names something like SETLOCAL and ENDLOCAL that let you save and restore the current state of the environment including drive letter and current directory. ------py27.bat------- SETLOCAL c: cd \python27\jimprogs python2.7 %$ ENDLOCAL --------------------- Or you could use PUSHD and POPD if the only thing you're customizing is the directory. -- DaveA From davea at davea.name Fri Jun 14 22:47:23 2013 From: davea at davea.name (Dave Angel) Date: Fri, 14 Jun 2013 16:47:23 -0400 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: <51BB5952.8070703@pearwood.info> Message-ID: <51BB815B.7020903@davea.name> On 06/14/2013 03:09 PM, Jim Mooney wrote: > > Of course, the real consideration, for those thinking of programming as a > career path, is whether programmers will be as obsolete at gaslighters in > twenty years - or will they be doing some sort of weird meta-programming? > You mean you don't write your own microcode in hex? New fangled computers get between us and the hardware. Give me instructions that directly manipulate voltages, and I'll be happy again. I have to admit, though that back when I was doing microcode work, I wrote my own assemblers (four at least) to at least avoid typing the hex. -- DaveA From cybervigilante at gmail.com Fri Jun 14 22:53:25 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 14 Jun 2013 13:53:25 -0700 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: <51BB815B.7020903@davea.name> References: <51BB5952.8070703@pearwood.info> <51BB815B.7020903@davea.name> Message-ID: On 14 June 2013 13:47, Dave Angel wrote: > On 06/14/2013 03:09 PM, Jim Mooney wrote: > > You mean you don't write your own microcode in hex? New fangled computers > get between us and the hardware. Give me instructions that directly > manipulate voltages, and I'll be happy again. > I guess there will always be room for people who write drivers. I'm not sure the more advanced robots would want to tackle that ;') Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Fri Jun 14 23:11:51 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 14 Jun 2013 14:11:51 -0700 Subject: [Tutor] sound implementation problems In-Reply-To: <51BB7E89.4000503@davea.name> References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> <51BAA1CC.6070904@davea.name> <51BB7E89.4000503@davea.name> Message-ID: On 14 June 2013 13:35, Dave Angel wrote: > >> MS batch file py27.bat >> >> python2.7 -i -c "import os;os.chdir('c:/python27/**jimprogs');del(os) >> >> > That seems rather silly. Why not > > ------py27.bat------- > c: > cd \python27\jimprogs > python2.7 %$ > --------------------- > That's certainly easier, but since I was looking at Python --help and saw the -c command I thought I'd try passing a program in as a string, since I hadn't done that. I'm still learning and may try out weird stuff. I just broke PyScripter and IDLE running some Fermat numbers, but discovered they printed out just fine, at a dizzying speed, in the DOS box. It's a useless program where you can barely read the results, but it was very useful to find out the DOS box does something when the my IDE and IDLE choke. Midrange machine -this might actually work in a better IDE on a high end machine: import math fermat = ["x is {} and y is {}".format(x,y) for x in range(1000) for y in range(1000) if not isinstance(math.sqrt(x**2 + y**2),int)] print(fermat) DOS started printing almost instantly, which means DOS is much, much faster than my IDE, since the entire list had to be figured before printing (which took a long time in the IDEs ;') Which means the IDE could fool me into thinking something takes forever to run when it gallops in DOS. Useful to know. Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jun 14 23:43:12 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Jun 2013 22:43:12 +0100 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: <51BB5952.8070703@pearwood.info> Message-ID: On 14/06/13 19:34, Jim Mooney wrote: > I'm probably going to hear that's already been done, too ;') Not in 3D to my knowledge but visual programming for sure. One example was ObjectVision from Borland on the PC. It lacked a loop construct because it was event driven but otherwise was a complete visual programming tool. I actually built a couple of business apps using it in the early 90's. There's a YouTube video showing the demos that came with it: http://www.youtube.com/watch?v=Xz37j3fOAc8 Another one, currently popular on the RaspberryPi micro computer is Scratch: http://scratch.mit.edu/projects/editor/?tip_bar=getStarted And on an industrial scale there are several tools that attempt to turn UML/SDL design diagrams into executable code, with varying degrees of success. There's nothing new under the sun :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jun 14 23:46:24 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Jun 2013 22:46:24 +0100 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: <51BB5952.8070703@pearwood.info> Message-ID: On 14/06/13 20:09, Jim Mooney wrote: > Of course, the real consideration, for those thinking of programming as > a career path, is whether programmers will be as obsolete at gaslighters > in twenty years - or will they be doing some sort of weird meta-programming? COBOL - COmmon Business Oriented Language. Designed in the 1950s to enable 'ordinary business users' to write their own programs and thus render programmers obsolete.... And by the standards of the languages I was using in the 1970/80s Python is a kind of weird meta programming! :-) That's been the holy grail of computer science since its inception. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cybervigilante at gmail.com Sat Jun 15 00:35:39 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 14 Jun 2013 15:35:39 -0700 Subject: [Tutor] sound implementation problems In-Reply-To: References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> Message-ID: On 14 June 2013 08:49, eryksun wrote: > On Thu, Jun 13, 2013 at 11:55 PM, Jim Mooney > wrote: > > C:\>python -i -c "import os; os.chdir('C:/Python33')" > Well, that didn't work anyway. Got me the right directory and the interpeter, but I couldn't run a py file from command. Batch file didn't work the way I wanted, either. But PYTHONSTARTUP finally worked nicely, for my personal purposes, by running the same python script that puts PyScripter into the right directory, based on why Py version is run. So all is well ;') -- Jim fi yuo cna raed tihs, yuo hvae a sgtrane mnid. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Jun 15 00:42:00 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 14 Jun 2013 23:42:00 +0100 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: <51BB5952.8070703@pearwood.info> Message-ID: On 14/06/2013 22:46, Alan Gauld wrote: > > COBOL - COmmon Business Oriented Language. > Designed in the 1950s to enable 'ordinary business users' to write their > own programs and thus render programmers obsolete.... > So what COBOL couldn't achieve is now being done with Applescript. -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From davea at davea.name Sat Jun 15 03:09:19 2013 From: davea at davea.name (Dave Angel) Date: Fri, 14 Jun 2013 21:09:19 -0400 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: <51BB5952.8070703@pearwood.info> Message-ID: <51BBBEBF.2020503@davea.name> On 06/14/2013 05:43 PM, Alan Gauld wrote: > On 14/06/13 19:34, Jim Mooney wrote: > >> I'm probably going to hear that's already been done, too ;') > > Not in 3D to my knowledge but visual programming for sure. > One example was ObjectVision from Borland on the PC. It lacked a loop > construct because it was event driven but otherwise was a complete > visual programming tool. I actually built a couple of business apps > using it in the early 90's. There's a YouTube video showing the demos > that came with it: > > http://www.youtube.com/watch?v=Xz37j3fOAc8 > > Another one, currently popular on the RaspberryPi micro computer is > Scratch: > > http://scratch.mit.edu/projects/editor/?tip_bar=getStarted > > And on an industrial scale there are several tools that attempt to turn > UML/SDL design diagrams into executable code, with varying degrees of > success. > > There's nothing new under the sun :-) > How about the program in about 1988 called "The Last One" ? It was supposed to be the last program you'd ever have to buy. -- DaveA From cybervigilante at gmail.com Sat Jun 15 03:36:42 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 14 Jun 2013 18:36:42 -0700 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: <51BBBEBF.2020503@davea.name> References: <51BB5952.8070703@pearwood.info> <51BBBEBF.2020503@davea.name> Message-ID: On 14 June 2013 18:09, Dave Angel wrote: > On 06/14/2013 05:43 PM, Alan Gauld wrote: > >> >> Another one, currently popular on the RaspberryPi micro computer is >> Scratch: >> >> http://scratch.mit.edu/**projects/editor/?tip_bar=**getStarted >> > Hey, that's fun - although my cat kept hitting the wall ;') Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: From amitsaha.in at gmail.com Sat Jun 15 11:53:23 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sat, 15 Jun 2013 19:53:23 +1000 Subject: [Tutor] Python and Symbolic Math for beginners Message-ID: Hello Tutors, Would any of you have any teaching (or substantial self learning) experience with a library for Symbolic math? I am currently exploring sympy (http://sympy.org) as part of writing a book chapter and would like to know if there any better/easier option out there which can successfully introduce symbolic math to young programmers. Thank you for any suggestions in advance. Best, Amit. -- http://echorand.me From eryksun at gmail.com Sat Jun 15 11:59:24 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 15 Jun 2013 05:59:24 -0400 Subject: [Tutor] sound implementation problems In-Reply-To: References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> Message-ID: On Fri, Jun 14, 2013 at 6:35 PM, Jim Mooney wrote: > On 14 June 2013 08:49, eryksun wrote: >> >> C:\>python -i -c "import os; os.chdir('C:/Python33')" > > Well, that didn't work anyway. Got me the right directory and the > interpeter, but I couldn't run a py file from command. Batch file didn't > work the way I wanted, either. But PYTHONSTARTUP finally worked nicely, > for my personal purposes, by running the same python script that puts > PyScripter into the right directory, based on why Py version is run. So > all is well ;') I was just clarifying how -c works, plus for some reason I thought you wanted an interactive session. In fact, I'm still confused about that because PYTHONSTARTUP only runs for an interaction startup. It doesn't run with -c, -m, or a script. If I run a program that's on the PATH, I expect it to load/save files relative to my current working directory, so I'm -1 on changing the working directory. If you have a resource stored relative to the script, use __file__ or sys.argv[0] to find it. Store per-user configuration and data in the user's profile: Windows Registry (HKCU) - %USERPROFILE%\NTUSER.DAT %APPDATA% - %USERPROFILE%\AppData\Roaming %LOCALAPPDATA% - %USERPROFILE%\AppData\Local Linux Freedesktop $XDG_CONFIG_HOME - ~/.config $XDG_DATA_HOME - ~/.local/share $XDG_CACHE_HOME - ~/.cache From eryksun at gmail.com Sat Jun 15 12:14:44 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 15 Jun 2013 06:14:44 -0400 Subject: [Tutor] sound implementation problems In-Reply-To: References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> Message-ID: On Fri, Jun 14, 2013 at 12:05 PM, Jim Mooney wrote: > On 14 June 2013 08:49, eryksun wrote: >> >> C:\>doskey calc=c:\python33\python -c "from cmath import *;print($*)" >> >> C:\>calc e**(1j*pi/3) >> (0.5000000000000001+0.8660254037844386j) >> >> Cool. I totally forgot about doskey macros. Still could be useful, and it >> looks like they're still in win 7. doskey.exe is a Windows COFF/PE executable. It provides a command-line interface to the Windows console alias and history functions, such as GetConsoleAliases GetConsoleAliasExes AddConsoleAlias GetConsoleCommandHistory (undocumented) SetConsoleNumberOfCommands (undocumented) ExpungeConsoleCommandHistory (undocumented) Microsoft has hardly changed the Windows console in 20 years. I think the biggest change was migrating console window management from the system process csrss.exe to the user process conhost.exe in Windows 7 (NT 6.1). http://technet.microsoft.com/en-us/library/cc753867.aspx http://msdn.microsoft.com/en-us/library/ms682073 From dotancohen at gmail.com Sat Jun 15 12:18:09 2013 From: dotancohen at gmail.com (Dotan Cohen) Date: Sat, 15 Jun 2013 13:18:09 +0300 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: <51BB3AEA.8040808@pearwood.info> References: <51BB3AEA.8040808@pearwood.info> Message-ID: On Fri, Jun 14, 2013 at 6:46 PM, Steven D'Aprano wrote: > On 15/06/13 01:23, Dotan Cohen wrote: >> >> What are these two string-formatting styles called? >> '%.3f' % x >> '{0:.3f}'.format(x) > > > "String formatting", and "string formatting" *wink* > > Sometimes the first is called "string interpolation". Sometimes it is called > "printf-style formatting", after the C function. > Thank you. If I were to say "I prefer the first type over the second type", without having the two types in front of me to demostrate which is 'first' and which is 'second', then how might I word that? "I prefer printf-style formatting over ". >> Where in the fine manual is their names shown? Thanks! > > > Like most things to do with strings, the place to start is the section on > strings: > > http://docs.python.org/3/library/stdtypes.html#text-sequence-type-str > > which leads to: > > http://docs.python.org/3/library/stdtypes.html#str.format > > and > > http://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting > Thanks. Actually, I did read that page but the descriptions only _describe_ the methods, they don't really give names. I suppose that printf-style really is given a name, but the other one isn't! -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From dotancohen at gmail.com Sat Jun 15 12:23:21 2013 From: dotancohen at gmail.com (Dotan Cohen) Date: Sat, 15 Jun 2013 13:23:21 +0300 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: Message-ID: On Fri, Jun 14, 2013 at 7:01 PM, Jim Mooney wrote: > On 14 June 2013 08:23, Dotan Cohen wrote: >> >> What are these two string-formatting styles called? >> '%.3f' % x >> '{0:.3f}'.format(x) > > > The first one is a string Expression, using % as the overloaded operator > The second one is a string method, with .format() as the method for a string > object > Thank you. So would it be clear if I were to say "I prefer printf-style formatting over the format method."? > put python string expression or python string method in that great > teaching tool, Google. > Thank you. I had in fact Googled for "Python string" and "Python string variable replacement names" but I didn't get much further than the fine Python manual which doesn't clearly name the second method. I suppose that knowing what to Google for is 90% of the way to an answer! > I know this since I'm reading that part of my python book right now and can > actually remember it. Although I fell asleep on the third page of > explanations of the more convoluted ways to use {}, which can get convoluted > indeed ;') > Oh? Which book is that? I've so far been learning by writing small applications here and there. I have been meaning to go through Learn Python The Hard Way for the longest time. -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From davea at davea.name Sat Jun 15 13:32:12 2013 From: davea at davea.name (Dave Angel) Date: Sat, 15 Jun 2013 07:32:12 -0400 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: Message-ID: <51BC50BC.1030105@davea.name> On 06/15/2013 06:23 AM, Dotan Cohen wrote: > On Fri, Jun 14, 2013 at 7:01 PM, Jim Mooney wrote: >> On 14 June 2013 08:23, Dotan Cohen wrote: >>> >>> What are these two string-formatting styles called? >>> '%.3f' % x >>> '{0:.3f}'.format(x) >> >> >> The first one is a string Expression, using % as the overloaded operator >> The second one is a string method, with .format() as the method for a string >> object >> > > Thank you. So would it be clear if I were to say "I prefer > printf-style formatting over the format method."? > I'd be careful there, since method is an English word as well as a Python one. So I'd make it clear i was referrring to a method of a class, by naming the class. Something like: the format() method of the str class. -- DaveA From steve at pearwood.info Sat Jun 15 13:41:14 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 15 Jun 2013 21:41:14 +1000 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: <51BB3AEA.8040808@pearwood.info> Message-ID: <51BC52DA.2020100@pearwood.info> On 15/06/13 20:18, Dotan Cohen wrote: > On Fri, Jun 14, 2013 at 6:46 PM, Steven D'Aprano wrote: >> On 15/06/13 01:23, Dotan Cohen wrote: >>> >>> What are these two string-formatting styles called? >>> '%.3f' % x >>> '{0:.3f}'.format(x) >> >> >> "String formatting", and "string formatting" *wink* >> >> Sometimes the first is called "string interpolation". Sometimes it is called >> "printf-style formatting", after the C function. >> > > Thank you. If I were to say "I prefer the first type over the second > type", without having the two types in front of me to demostrate which > is 'first' and which is 'second', then how might I word that? "I > prefer printf-style formatting over ". "I prefer % formatting over str.format method." "I prefer percent-formatting over brace-formatting." "I prefer C-style string formatting over the newer string format method." (or vice versa). -- Steven From cybervigilante at gmail.com Sat Jun 15 18:03:02 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 15 Jun 2013 09:03:02 -0700 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: Message-ID: On 15 June 2013 03:23, Dotan Cohen wrote: Oh? Which book is that? I've so far been learning by writing small > applications here and there. I have been meaning to go through Learn > Python The Hard Way for the longest time. > ===================== > > Learning Python, fifth edition, by Mark Lutz. The fifth edition is a few > years old but does cover Py 3, and it's more readily available, used. The > new edition Just came out and is much more Py 3 but I don't have it. > Not sure I'd recommend it as a starter book if it's the Only thing you use - it's a great book, but huge and very detailed, so it's slow going. However, I'm retired so I have a lot of time ;') But you said you go out on the web to try other stuff, which is what I do when I get bored by the Lutz book, so it might be what you want. One thing I like is that it's so detailed he tends to explain where you're going to screw up before you do it. I want the detail since I spent a few year just hacking at javascript as a webmaster. I'd borrow some code and slap it around until it did what I wanted for a web page (or ended in disaster ;') But I didn't really know what I was doing. This time I want Detail, and the Lutz book has it. In fact, as big as it is, it's only the Intro. He then has a second companion book to actually learn how to use Python, called Programming Python. That's newer and is all Python3. I've installed both Python 2.7 and Python 3.3 (after some gymnastics to keep them from conflicting), since Py 3 is the future but a lot of great packages are only for Py 2, so it's good to be able to use both. There's not really a lot of difference to learn at my level - mostly the print statement, since a lot of Py 3 stuff was backported to 2.7. There is also a program that comes with Python, called 2to3, which will translate a Py 2.7 program to a Py 3.3 program. Sometimes it works and sometimes it doesn't - if my IDE doesn't make a disagreeable honk and give me an even more disagreeable big, red Traceback, it worked ;') Jim After indictment the bacon smuggler was put on the no-fry list -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Sat Jun 15 20:41:37 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 15 Jun 2013 11:41:37 -0700 Subject: [Tutor] Is there a programmatic use for keys() and values() Message-ID: When I try to get the keys of a dictionary, such as d.keys(), I get the below instead of a plain list, and it's not very usable. How can I use the keys from this like it was a list, or is this basically useless other than to see the keys or values? *** Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32. *** >>> d.keys() dict_keys(['alpha', 'olf', 'bog', 'dog']) -- Jim After indictment the bacon smuggler was put on the no-fry list From kwpolska at gmail.com Sat Jun 15 20:51:22 2013 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sat, 15 Jun 2013 20:51:22 +0200 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: Message-ID: On Sat, Jun 15, 2013 at 8:41 PM, Jim Mooney wrote: > When I try to get the keys of a dictionary, such as d.keys(), I get > the below instead of a plain list, and it's not very usable. How can I > use the keys from this like it was a list, or is this basically > useless other than to see the keys or values? > > *** Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC > v.1600 32 bit (Intel)] on win32. *** >>>> d.keys() > dict_keys(['alpha', 'olf', 'bog', 'dog']) The standard use is: for k, v in d.items(): do_stuff_with_dict_items_here() You can use the .keys() and .values() in a similar way. You don?t need a list 99% of the time. And if you do, it is not hard to make it one. -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From joel.goldstick at gmail.com Sat Jun 15 20:56:28 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 15 Jun 2013 14:56:28 -0400 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: Message-ID: On Sat, Jun 15, 2013 at 2:41 PM, Jim Mooney wrote: > When I try to get the keys of a dictionary, such as d.keys(), I get > the below instead of a plain list, and it's not very usable. How can I > use the keys from this like it was a list, or is this basically > useless other than to see the keys or values? > > *** Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC > v.1600 32 bit (Intel)] on win32. *** > >>> d.keys() > dict_keys(['alpha', 'olf', 'bog', 'dog']) > I'm not sure what you want to do with your keys, but very commonly people do this: for k in d: # do something with k I'm using python 2.7 but here is an example: >>> d ={'a': 1, 'b': 2} >>> d {'a': 1, 'b': 2} >>> d.keys() ['a', 'b'] >>> for k in d: ... print k ... a b >>> > -- > Jim > After indictment the bacon smuggler was put on the no-fry list > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From andipersti at gmail.com Sat Jun 15 21:34:07 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Sat, 15 Jun 2013 21:34:07 +0200 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: Message-ID: <20130615213407.306cc842@Hof> Jim Mooney wrote: >When I try to get the keys of a dictionary, such as d.keys(), I get >the below instead of a plain list, and it's not very usable. How can I >use the keys from this like it was a list, or is this basically >useless other than to see the keys or values? If you really need a list you can use the built-in list() constructor since the return value of d.keys() is an iterable: >>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} >>> list(d.keys()) ['a', 'c', 'b', 'd'] Notice that the order of the keys is arbitrary. But usually you just iterate over the keys. (In Python 2, d.keys() actually returns a list). Bye, Andreas From steve at pearwood.info Sat Jun 15 21:37:20 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Jun 2013 05:37:20 +1000 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: Message-ID: <51BCC270.6000702@pearwood.info> On 16/06/13 04:41, Jim Mooney wrote: > When I try to get the keys of a dictionary, such as d.keys(), I get > the below instead of a plain list, and it's not very usable. How can I > use the keys from this like it was a list, or is this basically > useless other than to see the keys or values? > > *** Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC > v.1600 32 bit (Intel)] on win32. *** >>>> d.keys() > dict_keys(['alpha', 'olf', 'bog', 'dog']) What you are seeing is called a dict "view" -- it's a live snapshot of the dicts keys, and will update automatically as the dict updates. You can iterate over it as if it were a list: for key in d.keys(): print(key) You can convert it to a list (in which case it will no longer update automatically): keys = list(d.keys()) You can apply set operations, such as taking the union or intersection of two views: py> d1 = dict(a=1, b=2, c=3) py> d2 = dict(c=5, d=7) py> d1.keys() | d2.keys() # All the keys in either dict. {'d', 'b', 'c', 'a'} py> d1.keys() & d2.keys() # The keys in both dicts. {'c'} -- Steven From cybervigilante at gmail.com Sat Jun 15 21:48:35 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 15 Jun 2013 12:48:35 -0700 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: Message-ID: On 15 June 2013 11:51, Chris ?Kwpolska? Warrick wrote: > The standard use is: > > for k, v in d.items(): > do_stuff_with_dict_items_here() > Yes, they're easy to get keys = [x for x in d], or vals = [d[x] for x in d] It's just that Python usually does what I expect and presents me with something useful. All I can do is look at the d.keys or d.values result. But then, I could look at a usable list or tuple just as easily, so I'm surprised they made it kind of useless. -- Jim After indictment the bacon smuggler was put on the no-fry list From cybervigilante at gmail.com Sat Jun 15 21:54:51 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 15 Jun 2013 12:54:51 -0700 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: <20130615213407.306cc842@Hof> References: <20130615213407.306cc842@Hof> Message-ID: On 15 June 2013 12:34, Andreas Perstinger wrote: >>>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} >>>> list(d.keys()) > ['a', 'c', 'b', 'd'] Ah, that simplifies it. I probably read that and forgot it - so little time so much to learn ;') Without you guys the memory-fog would do me in . I just like to avoid typing all those odd little-finger characters. The dictionaries are the worst. I'll have to figure some way around that, but I can only remap so many keys until it becomes a mess. I already remapped Caps Lock to End. Every time I turn around I'm inside something where I need to be at the end, and have to find the right arrow or End key, so remapping was an amazing time saver. I never use Caps Lock. It's Internet rudeness. And if I need all caps for a big section, Clipmate can do that automatically. (Incredible program - amazing timesaver - so I'm giving it a plug.) -- Jim After indictment the bacon smuggler was put on the no-fry list From alan.gauld at btinternet.com Sat Jun 15 23:55:07 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Jun 2013 22:55:07 +0100 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> Message-ID: On 15/06/13 20:54, Jim Mooney wrote: > I just like to avoid typing all those odd little-finger characters. > The dictionaries are the worst. I think your making it harder than it is. Just use the result as you would expect and it will work. Don't get hung up over a list versus an iterable. Just use it as is, mostly it will just do what you expect. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cybervigilante at gmail.com Sun Jun 16 02:33:20 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 15 Jun 2013 17:33:20 -0700 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> Message-ID: On 15 June 2013 14:55, Alan Gauld wrote: > I think your making it harder than it is. > Just use the result as you would expect and it will work. I just meant that since I'm learning I'll create a dictionary on the fly to try something out. All goes well except my IDE will type two quotes if I type one, then center the cursor in between. the same for braces, brackets, etc. It's a great convenience. But in a dictionary I'll get to here: {'alpha':'beta' Only my cursor is to the Left of the final quote. Then I have to go hunt the Right Arrow or End key, which is a big pain since I'm far from a perfect touch typist and they're both far from the home keys. But I solved the problem with a simple cheat instead of writing an IDE or python script to create a dict from a two-by-two list then just copy it from the interpreter. Something like: >>> myfunc(['tippecanoe','tylertoo',1,'wun','nestedlist',[[2,3],[3,5]],'float',3.41]) >>> {'tippecanoe':'tylertoo',1:'wun','nestedlist':[[2,3],[3,5]],'float':3.41} I realized once I got to nested lists, dicts, spaces, complex objects, and so forth, it was getting too deep for me. But it will be a good exercise after awhile, since I can see it would require some parsing, regexes, and recursion. Solving annoying little real-world problems like that strikes me as a good way to learn Python - possibly better than artificial book-exercises, or at least as an adjunct ;') My keyboard cheat was I simply remapped Left Shift + Spacebar to move the cursor one character right, instead. Left Shift + Spacebar is very easy to find without looking and I Never use Left Shift + Spacebar anyway. Now I can type fast and not hunt the stupid right arrow key. Caps Lock gets me out of parentheses by going to End. Between those two I'm done with the keyboard annoyance of hunting the End and Right Arrow key . Thankfully so, since I'm about out of easy remaps. The rest would be as troublesome as the original problem. Well, I still have Right Shift + Spacebar. I'll save that for a special occasion. Come to think of it Caps Lock + a letter key would be easy and give me a dozen more functions for the most common letters, most of them mnemonic. But that's for another day. Too many all at once would just be going backward. That may not seem important but while Python is fun to learn, hunting keys far off from the home keys is annoying, at least to me. Or maybe I'm just really lazy, since I recline way back while typing ;') Jim From steve at pearwood.info Sun Jun 16 02:36:58 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Jun 2013 10:36:58 +1000 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> Message-ID: <51BD08AA.8060202@pearwood.info> On 16/06/13 07:55, Alan Gauld wrote: > On 15/06/13 20:54, Jim Mooney wrote: > >> I just like to avoid typing all those odd little-finger characters. >> The dictionaries are the worst. > > I think your making it harder than it is. > Just use the result as you would expect and it will work. > > Don't get hung up over a list versus an iterable. > Just use it as is, mostly it will just do what you expect. Well, sometimes. for key in sorted(mydict.keys()): ... works fine. On the other hand: keys = mydict.keys() keys.sort() for key in keys: ... does not. -- Steven From cybervigilante at gmail.com Sun Jun 16 03:30:04 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 15 Jun 2013 18:30:04 -0700 Subject: [Tutor] What is the difference between checking false? Message-ID: ##This is puzzling me. If I check the equality of 0, None, empty string, and empty list with False, ##only zero satisfies the equality. But if I use them in a not statement, they all turn out False. ##What gives? #Using C:\Python33\python.exe on Win 7 in c:\python33\jimprogs print('Zero is equal to False' if 0 == False else 'Zero is NOT equal to False') print('None is equal to false' if None == False else 'None is NOT equal to false') print('Empty string is equal to False' if '' == False else 'Empty string is NOT equal to False') print('Empty list is equal to false' if [] == False else 'Empty list is NOT equal to false') print() print('Zero is equal to False' if not 0 else 'Zero is NOT equal to False') print('None is equal to false' if not None else 'None is NOT equal to false') print('Empty string is equal to False' if not '' else 'Empty string is NOT equal to False') print('Empty list is equal to False' if not [] else 'Empty list is NOT equal to false') ##Results: ## ##Zero is equal to False ##None is NOT equal to false ##Empty string is NOT equal to False ##Empty list is NOT equal to false ## ##Zero is equal to False ##None is equal to false ##Empty string is equal to False ##Empty list is equal to False -- Jim After indictment the bacon smuggler was put on the no-fry list From davea at davea.name Sun Jun 16 03:53:20 2013 From: davea at davea.name (Dave Angel) Date: Sat, 15 Jun 2013 21:53:20 -0400 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: <51BD08AA.8060202@pearwood.info> References: <20130615213407.306cc842@Hof> <51BD08AA.8060202@pearwood.info> Message-ID: <51BD1A90.1030608@davea.name> On 06/15/2013 08:36 PM, Steven D'Aprano wrote: > On 16/06/13 07:55, Alan Gauld wrote: >> On 15/06/13 20:54, Jim Mooney wrote: >> >>> I just like to avoid typing all those odd little-finger characters. >>> The dictionaries are the worst. >> >> I think your making it harder than it is. >> Just use the result as you would expect and it will work. >> >> Don't get hung up over a list versus an iterable. >> Just use it as is, mostly it will just do what you expect. > > > Well, sometimes. > > > for key in sorted(mydict.keys()): > ... > > > works fine. On the other hand: > > keys = mydict.keys() > keys.sort() > for key in keys: > ... > > > does not. > The sort() method doesn't work, but sorted does. keys = mydict.keys() for key in sorted(keys): Or more directly, for key in sorted(mydict.keys()): -- DaveA From davea at davea.name Sun Jun 16 04:03:24 2013 From: davea at davea.name (Dave Angel) Date: Sat, 15 Jun 2013 22:03:24 -0400 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: Message-ID: <51BD1CEC.6010308@davea.name> On 06/15/2013 09:30 PM, Jim Mooney wrote: > ##This is puzzling me. If I check the equality of 0, None, empty > string, and empty list with False, > ##only zero satisfies the equality. But if I use them in a not > statement, they all turn out False. > ##What gives? > > #Using C:\Python33\python.exe on Win 7 in c:\python33\jimprogs > > print('Zero is equal to False' if 0 == False else 'Zero is NOT equal to False') > print('None is equal to false' if None == False else 'None is NOT > equal to false') > print('Empty string is equal to False' if '' == False else 'Empty > string is NOT equal to False') > print('Empty list is equal to false' if [] == False else 'Empty list > is NOT equal to false') > print() > print('Zero is equal to False' if not 0 else 'Zero is NOT equal to False') > print('None is equal to false' if not None else 'None is NOT equal to false') > print('Empty string is equal to False' if not '' else 'Empty string is > NOT equal to False') > print('Empty list is equal to False' if not [] else 'Empty list is NOT > equal to false') > > ##Results: > ## > ##Zero is equal to False > ##None is NOT equal to false > ##Empty string is NOT equal to False > ##Empty list is NOT equal to false > ## > ##Zero is equal to False > ##None is equal to false > ##Empty string is equal to False > ##Empty list is equal to False > Why such a convoluted way of expressing yourself? Especially the second half when the statements are clearly different than what you're testing. False is equivalent to the int 0 for historical reasons, back before there was a separate boolean type. Likewise True is equivalent to the int 1. You shouldn't write any code that counts on it, however. You don't say which of the remaining ones in the first group are surprising. False is not the same as any other type except the special one I already mentioned. As for the second group, applying the not operator will produce exactly True or False, the same way that applying bool() will. The only difference is that if one would produce True, the other will produce False. That's what 'not' means. But it's certainly not doing a value comparison like your literal claims. If the item is truthy, not produces False. And if the item is falsey, not produces True. -- DaveA From cybervigilante at gmail.com Sun Jun 16 04:21:26 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 15 Jun 2013 19:21:26 -0700 Subject: [Tutor] What is the difference between checking false? In-Reply-To: <51BD1CEC.6010308@davea.name> References: <51BD1CEC.6010308@davea.name> Message-ID: On 15 June 2013 19:03, Dave Angel wrote: > Why such a convoluted way of expressing yourself? I was demonstrating the parallelism, but let's just take one so I can unbefuddle meself ;') *** Python 3.3.2 32 bit (Intel)] on win32. *** >>> '' == False False >>> not '' True >>> Why the difference here? -- Jim After indictment the bacon smuggler was put on the no-fry list From eryksun at gmail.com Sun Jun 16 04:23:22 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 15 Jun 2013 22:23:22 -0400 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: Message-ID: On Sat, Jun 15, 2013 at 9:30 PM, Jim Mooney wrote: > This is puzzling me. If I check the equality of 0, None, empty > string, and empty list with False, only zero satisfies the equality. > But if I use them in a not statement, they all turn out False. > What gives? > > #Using C:\Python33\python.exe on Win 7 in c:\python33\jimprogs .... > ##Zero is equal to False > ##None is NOT equal to false > ##Empty string is NOT equal to False > ##Empty list is NOT equal to false > ## > ##Zero is equal to False > ##None is equal to false > ##Empty string is equal to False > ##Empty list is equal to False bool subclasses int, with False == 0 and True == 1. None and empty sequences/mappings aren't *equal* to False. But they are 'falsey' -- i.e. bool(None) is False. The implementation of UNARY_NOT in CPython is based on the function PyObject_IsTrue. This function is hard coded for the singletons True, False, and None -- and otherwise uses either __bool__ (tp_as_number->nb_bool) or __len__ (tp_as_mapping->mp_length or tp_as_sequence->sq_length). A length of 0 is falsey. If neither __bool__ nor __len__ is defined, the object defaults to being truthy: >>> not not object() True >>> not object() False From davea at davea.name Sun Jun 16 04:28:05 2013 From: davea at davea.name (Dave Angel) Date: Sat, 15 Jun 2013 22:28:05 -0400 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: <51BD1CEC.6010308@davea.name> Message-ID: <51BD22B5.8010803@davea.name> On 06/15/2013 10:21 PM, Jim Mooney wrote: > On 15 June 2013 19:03, Dave Angel wrote: >> Why such a convoluted way of expressing yourself? > > I was demonstrating the parallelism, but let's just take one so I can > unbefuddle meself ;') > > *** Python 3.3.2 32 bit (Intel)] on win32. *** >>>> '' == False > False >>>> not '' > True >>>> > > Why the difference here? > There's no contradiction; you're doing two entirely different things. If you want to compare a non-boolean to False or True, expect it'll always be false. They are different types. (except for the int historical nonsense I mentioned earlier). If you want to duplicate what the second expression does, you'll have to convert the str to a boolean, using the bool() function.[1] >>> bool("") == False True [1] Technically it's not a function but a "type" operation, or something. But it quacks like a function, and I can't be bothered, at least not for this discussion. -- DaveA From joel.goldstick at gmail.com Sun Jun 16 04:31:46 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 15 Jun 2013 22:31:46 -0400 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: <51BD1CEC.6010308@davea.name> Message-ID: On Sat, Jun 15, 2013 at 10:21 PM, Jim Mooney wrote: > On 15 June 2013 19:03, Dave Angel wrote: > > Why such a convoluted way of expressing yourself? > > I was demonstrating the parallelism, but let's just take one so I can > unbefuddle meself ;') > > *** Python 3.3.2 32 bit (Intel)] on win32. *** > >>> '' == False > == compares two values to see if they are identical. There are various values that are defined as evaluating to True or False, using what python people call Duck Typing. Just because something 'acts' False like or True like doesn't mean that it is identical to the boolean value True or the boolean false In your first example you are checking equality. Maybe look up python duck typing > False > >>> not '' > True > >>> > > Why the difference here? > > -- > Jim > After indictment the bacon smuggler was put on the no-fry list > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Sun Jun 16 04:36:42 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 15 Jun 2013 19:36:42 -0700 Subject: [Tutor] What is the difference between checking false? In-Reply-To: <51BD22B5.8010803@davea.name> References: <51BD1CEC.6010308@davea.name> <51BD22B5.8010803@davea.name> Message-ID: On 15 June 2013 19:28, Dave Angel wrote: > If you want to compare a non-boolean to False or True, expect it'll always > be false. They are different types. (except for the int historical > nonsense I mentioned earlier). Ah, that clarifies it - type differences - something I can look out for - and throwing in the 1, 0 baloney, which I was hoping to get away from when I decided to do Python instead of Javascript. I may be lazy but I really don't need to substitute 0 for False. -- Jim After indictment the bacon smuggler was put on the no-fry list From eryksun at gmail.com Sun Jun 16 04:45:14 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 15 Jun 2013 22:45:14 -0400 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: Message-ID: On Sat, Jun 15, 2013 at 10:23 PM, eryksun wrote: > This function is hard coded for the singletons True, > False, and None -- and otherwise uses either __bool__ > (tp_as_number->nb_bool) or __len__ (tp_as_mapping->mp_length or > tp_as_sequence->sq_length). A length of 0 is falsey. I forgot to add that 2.x uses the special method __nonzero__ instead of __bool__. This can return either an int or a bool. In Python 3 __bool__ can only return a bool. From cybervigilante at gmail.com Sun Jun 16 05:15:26 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 15 Jun 2013 20:15:26 -0700 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: Message-ID: On 15 June 2013 19:45, eryksun wrote: > On Sat, Jun 15, 2013 at 10:23 PM, eryksun wrote: >> This function is hard coded for the singletons True, >> False, and None -- and otherwise uses either __bool__ >> (tp_as_number->nb_bool) or __len__ (tp_as_mapping->mp_length or >> tp_as_sequence->sq_length). A length of 0 is falsey. I decided to boil it down to what I could remember easily, so this is the result: ## Comparing different types for equality always fails: if '5' != 5: print('oops') # oops if '' == False: print("This will never print.") ## But: if bool('') == False: print("Now they're the same type and this will print") ## Now they're the same type and this will print ## And the Python documentation says 'not' doesn't give a damn about types ## ## "Because not has to invent a value anyway, it does not bother to return a ## value of the same type as its argument, so e.g., not 'foo' yields False, not ''." ## ## Finally, 1 and 0 are oh-so-special standins for True and False, that should have ## been strangled in the cradle. -- Jim After indictment the bacon smuggler was put on the no-fry list From joel.goldstick at gmail.com Sun Jun 16 05:48:06 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 15 Jun 2013 23:48:06 -0400 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: Message-ID: On Sat, Jun 15, 2013 at 11:15 PM, Jim Mooney wrote: > On 15 June 2013 19:45, eryksun wrote: > > On Sat, Jun 15, 2013 at 10:23 PM, eryksun wrote: > >> This function is hard coded for the singletons True, > >> False, and None -- and otherwise uses either __bool__ > >> (tp_as_number->nb_bool) or __len__ (tp_as_mapping->mp_length or > >> tp_as_sequence->sq_length). A length of 0 is falsey. > > I decided to boil it down to what I could remember easily, so this is > the result: > > ## Comparing different types for equality always fails: > > if '5' != 5: > print('oops') > > # oops > > if '' == False: > print("This will never print.") > > ## But: > > if bool('') == False: > print("Now they're the same type and this will print") > > ## Now they're the same type and this will print > > ## And the Python documentation says 'not' doesn't give a damn about types > ## > ## "Because not has to invent a value anyway, it does not bother to return > a > ## value of the same type as its argument, so e.g., not 'foo' yields > False, not ''." > ## > ## Finally, 1 and 0 are oh-so-special standins for True and False, > that should have > ## been strangled in the cradle. > One and zero for True and False may seem not quite right today, but digital computers are based on the fact that circuits can be built that have two states -- on/off or true/false, or 1/0. Computers at their hardware core are complicated state machines where the all the states are either True or False. So really, it made sense to make the mapping between a gate that is in one of two states to be represented by True/False. > > -- > Jim > After indictment the bacon smuggler was put on the no-fry list > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Sun Jun 16 05:53:25 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 15 Jun 2013 20:53:25 -0700 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: Message-ID: On 15 June 2013 20:48, Joel Goldstick wrote: > One and zero for True and False may seem not quite right today, I still think they should be taken out and shot ;') But my simplification plan failed. Equality always fails for different types, and 'not in front of None or any empty object such as empty string, empty list, empty tuple, or empty dict, is always True. But it appears that idea fails for an empty class: class NobodyHome: pass x = NobodyHome() print(not x) # Result is False when I thought this would be True. -- Jim After indictment the bacon smuggler was put on the no-fry list From cybervigilante at gmail.com Sun Jun 16 06:01:57 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 15 Jun 2013 21:01:57 -0700 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: Message-ID: On 15 June 2013 20:48, Joel Goldstick wrote: > > One and zero for True and False may seem not quite right today, but digital > computers are based on the fact that circuits can be built that have two > states -- on/off or true/false, or 1/0. But then, if we're going down to the gate level, why not the quantum level, where they are now building gates that use the square root of Not. (And I thought the square root of minus one was bad ;') -- Jim After indictment the bacon smuggler was put on the no-fry list From davea at davea.name Sun Jun 16 06:41:20 2013 From: davea at davea.name (Dave Angel) Date: Sun, 16 Jun 2013 00:41:20 -0400 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: Message-ID: <51BD41F0.8000908@davea.name> On 06/15/2013 11:53 PM, Jim Mooney wrote: > On 15 June 2013 20:48, Joel Goldstick wrote: > >> One and zero for True and False may seem not quite right today, > > I still think they should be taken out and shot ;') > > But my simplification plan failed. Equality always fails for different > types, and 'not in front of None or any empty object such as empty > string, empty list, empty tuple, or empty dict, is always True. But it > appears that idea fails for an empty class: > > class NobodyHome: pass > x = NobodyHome() > print(not x) # Result is False when I thought this would be True. > The rules you're talking are not somehow mystically enforced by the compiler. They're definitions and conventions that are presumably consistently applied in the library code for each builtin or library type. But if you write your own, you get to make your own rules for if it's truthey or falsey. Saying the class is empty is meaningless. Even a trivial class has many methods that it inherits from object. Anyway, if a class does not define its own truthy/falsey definition, then an instance of that class is always considered truthey. The convention about list, tuple, dict, etc. is referring to collections, that implement a __len__() method. Add such a method to your class, and you too can decide whether a particular instance is truthey or falsey. But since your class isn't a collection, it'd be clearer to define the method __bool__(), which is what's tried first. (In Python 3.x) >>> class NobodyHome: ... def __bool__(self): ... return False #normally, you'd be testing some attribute to decide this ... >>> x = NobodyHome() >>> not x True -- DaveA From cybervigilante at gmail.com Sun Jun 16 07:13:54 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 15 Jun 2013 22:13:54 -0700 Subject: [Tutor] What is the difference between checking false? In-Reply-To: <51BD41F0.8000908@davea.name> References: <51BD41F0.8000908@davea.name> Message-ID: On 15 June 2013 21:41, Dave Angel wrote: >>>> class NobodyHome: > ... def __bool__(self): > ... return False #normally, you'd be testing some attribute to > decide this > > ... >>>> x = NobodyHome() >>>> not x > True > That's a breath of fresh air - talk about freedom ;') Makes me eager to get to classes so I can redefine sets as tagged sets. -- Jim After indictment the bacon smuggler was put on the no-fry list From steve at pearwood.info Sun Jun 16 07:32:38 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Jun 2013 15:32:38 +1000 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: Message-ID: <51BD4DF6.3040807@pearwood.info> On 16/06/13 11:30, Jim Mooney wrote: > ##This is puzzling me. If I check the equality of 0, None, empty > string, and empty list with False, > ##only zero satisfies the equality. But if I use them in a not > statement, they all turn out False. > ##What gives? That's because the tests do different things. Equals tests whether two values have equal value; testing things with `if` tests whether they are true-ish or false-ish. Some languages require that the conditions in an `if` test be actual boolean values True or False, but Python does not. Partly for backwards compatibility, partly by design (but mostly by design), Python tests conditions according to the principle of "duck-typing": "if it quacks like a duck and swims like a duck, it might as well be a duck". Consequently, the Python philosophy is that, as a general rule, if you want to know whether an object is true-ish or false-ish, you should just see if it quacks like True or quacks like False. This question came up a day or so ago, on another list. Here is one of my answers: http://mail.python.org/pipermail/python-list/2013-June/649710.html One advantage of this is that you can do things like: if mylist and mylist[0] == item: ... instead of: if mylist != []: if mylist[0] == item: ... which is how things work in languages with strict true/false flags and no short-circuit testing, like Pascal. -- Steven From steve at pearwood.info Sun Jun 16 07:38:43 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Jun 2013 15:38:43 +1000 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: Message-ID: <51BD4F63.5010006@pearwood.info> On 16/06/13 13:15, Jim Mooney wrote: > ## Comparing different types for equality always fails: > > if '5' != 5: > print('oops') Not always. Counter-examples are most obvious when it comes to numbers: py> from decimal import Decimal py> from fractions import Fraction py> Fraction(1, 2) == Decimal("0.5") True py> 0.75 == Fraction(3)/4 True py> 42 == 42.0 True -- Steven From dotancohen at gmail.com Sun Jun 16 07:40:29 2013 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 16 Jun 2013 08:40:29 +0300 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: <51BC50BC.1030105@davea.name> References: <51BC50BC.1030105@davea.name> Message-ID: On Sat, Jun 15, 2013 at 2:32 PM, Dave Angel wrote: >> Thank you. So would it be clear if I were to say "I prefer >> printf-style formatting over the format method."? >> > > I'd be careful there, since method is an English word as well as a Python > one. So I'd make it clear i was referrring to a method of a class, by > naming the class. > > Something like: > > the format() method of the str class. > Actually, I specifically said 'method' in the OOP-sense of the word. I don't see any ambiguity, as there is no other relevant class that I know of which has a format() method. But I'm here to learn, and I would love nothing more than for you to tell me where the sentence is ambiguous. Thank you! Python is both wide and deep, and this thread has been very enlightening. -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From dotancohen at gmail.com Sun Jun 16 07:41:30 2013 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 16 Jun 2013 08:41:30 +0300 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: <51BC52DA.2020100@pearwood.info> References: <51BB3AEA.8040808@pearwood.info> <51BC52DA.2020100@pearwood.info> Message-ID: On Sat, Jun 15, 2013 at 2:41 PM, Steven D'Aprano wrote: > On 15/06/13 20:18, Dotan Cohen wrote: >> > "I prefer % formatting over str.format method." > > "I prefer percent-formatting over brace-formatting." > > "I prefer C-style string formatting over the newer string format method." > Thank you Steven, that is exactly what I was after! -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From steve at pearwood.info Sun Jun 16 07:46:04 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Jun 2013 15:46:04 +1000 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: <51BD1CEC.6010308@davea.name> Message-ID: <51BD511C.3030403@pearwood.info> On 16/06/13 12:31, Joel Goldstick wrote: > On Sat, Jun 15, 2013 at 10:21 PM, Jim Mooney wrote: > >> On 15 June 2013 19:03, Dave Angel wrote: >>> Why such a convoluted way of expressing yourself? >> >> I was demonstrating the parallelism, but let's just take one so I can >> unbefuddle meself ;') >> >> *** Python 3.3.2 32 bit (Intel)] on win32. *** >>>>> '' == False >> > > == compares two values to see if they are identical. In Python, objects are considered "identical" if and only if they are the same object, not just the same value. == tests two objects to see if they have equal values, while the `is` operator tests to see if they are identical (that is, if they are actually the same object). > There are various values that are defined as evaluating to True or False, > using what python people call Duck Typing. Just because something 'acts' > False like or True like doesn't mean that it is identical to the boolean > value True or the boolean false True and False are guaranteed to be "singletons" (even though there are two of them), that is, there is only one True object and only one False object. However, any number with the value 1 will compare equal to True, and any number with the value of 0 will compare equal to False. Finally, any object that is considered to be "something" or non-empty should be treated as if it were true in a boolean context (e.g. `if obj`, or `while obj`); any object that is considered "nothing" or empty should likewise be considered as if it were false. -- Steven From cybervigilante at gmail.com Sun Jun 16 07:52:34 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 15 Jun 2013 22:52:34 -0700 Subject: [Tutor] What is the difference between checking false? In-Reply-To: <51BD4DF6.3040807@pearwood.info> References: <51BD4DF6.3040807@pearwood.info> Message-ID: On 15 June 2013 22:32, Steven D'Aprano wrote: > http://mail.python.org/pipermail/python-list/2013-June/649710.html A succinct list - worth putting in my Keep file ;') - Jim After indictment the bacon smuggler was put on the no-fry list From steve at pearwood.info Sun Jun 16 07:58:23 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Jun 2013 15:58:23 +1000 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: <51BD1A90.1030608@davea.name> References: <20130615213407.306cc842@Hof> <51BD08AA.8060202@pearwood.info> <51BD1A90.1030608@davea.name> Message-ID: <51BD53FF.7040801@pearwood.info> On 16/06/13 11:53, Dave Angel wrote: > On 06/15/2013 08:36 PM, Steven D'Aprano wrote: >> for key in sorted(mydict.keys()): >> ... >> >> works fine. [...] > The sort() method doesn't work, but sorted does. [...] > for key in sorted(mydict.keys()): Not only that, but sorted works too: for key in sorted(mydict.keys()) *wink* -- Steven From davea at davea.name Sun Jun 16 08:27:31 2013 From: davea at davea.name (Dave Angel) Date: Sun, 16 Jun 2013 02:27:31 -0400 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: References: <51BC50BC.1030105@davea.name> Message-ID: <51BD5AD3.5070801@davea.name> On 06/16/2013 01:40 AM, Dotan Cohen wrote: > On Sat, Jun 15, 2013 at 2:32 PM, Dave Angel wrote: >>> Thank you. So would it be clear if I were to say "I prefer >>> printf-style formatting over the format method."? >>> >> >> I'd be careful there, since method is an English word as well as a Python >> one. So I'd make it clear i was referrring to a method of a class, by >> naming the class. >> >> Something like: >> >> the format() method of the str class. >> > > Actually, I specifically said 'method' in the OOP-sense of the word. I > don't see any ambiguity, as there is no other relevant class that I > know of which has a format() method. But I'm here to learn, and I > would love nothing more than for you to tell me where the sentence is > ambiguous. > You were thinking of the OOP-sense of the word, but you didn't say it. So the listener might choose to figure you meant "method" as in "technique". After all the word style is used in its English meaning, even though Word documents can have styles. You're quite right that once we're thinking in the OOPS-sense, there's no ambiguity. But I figure a few words more were needed to make sure the listener is in sync. And the easiest way to make sure it's clear we mean a class-method is to name the class. If it were being written, the parentheses might be enough. But parentheses are usually silent when speaking. -- DaveA From davea at davea.name Sun Jun 16 08:30:31 2013 From: davea at davea.name (Dave Angel) Date: Sun, 16 Jun 2013 02:30:31 -0400 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: <51BD53FF.7040801@pearwood.info> References: <20130615213407.306cc842@Hof> <51BD08AA.8060202@pearwood.info> <51BD1A90.1030608@davea.name> <51BD53FF.7040801@pearwood.info> Message-ID: <51BD5B87.5080103@davea.name> On 06/16/2013 01:58 AM, Steven D'Aprano wrote: > On 16/06/13 11:53, Dave Angel wrote: >> On 06/15/2013 08:36 PM, Steven D'Aprano wrote: > >>> for key in sorted(mydict.keys()): >>> ... >>> >>> works fine. > [...] >> The sort() method doesn't work, but sorted does. > [...] >> for key in sorted(mydict.keys()): > > Not only that, but sorted works too: > > for key in sorted(mydict.keys()) > > > *wink* > > Whoops, I guess I didn't read the whole thing. Not only that, I didn't read all of it. Sorry, some of it was inadequately read. -- DaveA From roel at roelschroeven.net Sun Jun 16 10:43:16 2013 From: roel at roelschroeven.net (Roel Schroeven) Date: Sun, 16 Jun 2013 10:43:16 +0200 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> Message-ID: Jim Mooney schreef: > On 15 June 2013 14:55, Alan Gauld wrote: > >> I think your making it harder than it is. >> Just use the result as you would expect and it will work. > > I just meant that since I'm learning I'll create a dictionary on the > fly to try something out. All goes well except my IDE will type two > quotes if I type one, then center the cursor in between. the same for > braces, brackets, etc. It's a great convenience. But in a dictionary > I'll get to here: > > {'alpha':'beta' > > Only my cursor is to the Left of the final quote. Then I have to go > hunt the Right Arrow or End key, which is a big pain since I'm far > from a perfect touch typist and they're both far from the home keys. Can't you disable that behavior somewhere in the settings of your IDE? I know IDEs do that to be helpful, but I don't like it and so far I've been able to disable it in all IDEs I've used. -- "People almost invariably arrive at their beliefs not on the basis of proof but on the basis of what they find attractive." -- Pascal Blaise roel at roelschroeven.net From eryksun at gmail.com Sun Jun 16 10:45:40 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 16 Jun 2013 04:45:40 -0400 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: Message-ID: On Sat, Jun 15, 2013 at 11:53 PM, Jim Mooney wrote: > > class NobodyHome: pass > x = NobodyHome() > print(not x) # Result is False when I thought this would be True. Quote: >> If neither __bool__ nor __len__ is defined, the object defaults to being truthy: >> >> >>> not not object() >> True >> >>> not object() >> False From eryksun at gmail.com Sun Jun 16 10:46:57 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 16 Jun 2013 04:46:57 -0400 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: Message-ID: On Sat, Jun 15, 2013 at 11:15 PM, Jim Mooney wrote: > > ## Comparing different types for equality always fails: > > if '5' != 5: > print('oops') It depends on the __eq__ and __ne__ methods defined by the types. int and str have their own implementations of "rich comparisons". But that's a subject for another thread and another time, when you've gotten deeper into implementing your own classes. > Finally, 1 and 0 are oh-so-special standins for True and False, > that should have been strangled in the cradle. As I already said, you can't return an int from __bool__ in 3.x. In 2.x, __nonzero__ can return 0 for False and a "non-zero" int for True -- but only an int (not long, float, etc). From dotancohen at gmail.com Sun Jun 16 12:40:54 2013 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 16 Jun 2013 13:40:54 +0300 Subject: [Tutor] What are these two string-formatting styles called? In-Reply-To: <51BD5AD3.5070801@davea.name> References: <51BC50BC.1030105@davea.name> <51BD5AD3.5070801@davea.name> Message-ID: On Sun, Jun 16, 2013 at 9:27 AM, Dave Angel wrote: > You were thinking of the OOP-sense of the word, but you didn't say it. So > the listener might choose to figure you meant "method" as in "technique". > After all the word style is used in its English meaning, even though Word > documents can have styles. > > You're quite right that once we're thinking in the OOPS-sense, there's no > ambiguity. But I figure a few words more were needed to make sure the > listener is in sync. And the easiest way to make sure it's clear we mean a > class-method is to name the class. If it were being written, the > parentheses might be enough. But parentheses are usually silent when > speaking. > I see, thanks. -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From kwpolska at gmail.com Sun Jun 16 16:06:13 2013 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sun, 16 Jun 2013 16:06:13 +0200 Subject: [Tutor] What is the difference between checking false? In-Reply-To: References: <51BD4DF6.3040807@pearwood.info> Message-ID: On Sun, Jun 16, 2013 at 7:52 AM, Jim Mooney wrote: > On 15 June 2013 22:32, Steven D'Aprano wrote: >> http://mail.python.org/pipermail/python-list/2013-June/649710.html > > A succinct list - worth putting in my Keep file ;') > > - > Jim > After indictment the bacon smuggler was put on the no-fry list > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Another thing worthy putting there may be may be the three ways to do `if` statements to compare stuff: 1. `if x` ? runs bool(x), see list above, can be negated by `if not x` 2. `if x == y` ? tests if they have the same value, negated by `if x != y` or `if not x == y` (not used). 3. `if x is y` ? tests if they are the same object, used for `is None`/`is not None` comparisons and not much else. -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From cfuller at linuxmail.org Tue Jun 11 22:52:33 2013 From: cfuller at linuxmail.org (Chris Fuller) Date: Tue, 11 Jun 2013 15:52:33 -0500 Subject: [Tutor] producing PDF files In-Reply-To: References: Message-ID: <201306111552.33256.cfuller@linuxmail.org> On Tuesday, June 11, 2013, Khalid Al-Ghamdi wrote: > Hi, > > Do you know of a python module for converting text files to PDF format? > > thanks Another one, that I've used extensively, is ReportLab. http://www.reportlab.com/software/opensource/ Cheers From cybervigilante at gmail.com Tue Jun 11 20:00:26 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 11 Jun 2013 11:00:26 -0700 Subject: [Tutor] On a looping input, subsequent inputs are hidden In-Reply-To: <51B71F29.9030907@pearwood.info> References: <51B71F29.9030907@pearwood.info> Message-ID: On 11 June 2013 05:59, Steven D'Aprano wrote: > I'm afraid I don't understand what you mean. Second and subsequent inputs? I > only see one. Hide the input with dots? > > Can you copy and paste an example? That would be a graphic of the input popup and this is a text-only list. Or would an attachment work? Well, the best way to find out is to try. Graphic attached of the second call to input since a non-integer was entered. If it appears, the second input window, when I enter integers, shows little black security-dots, as in web entries of your password, instead of the integers. On the first input, I can see the numbers. Jim -------------- next part -------------- A non-text attachment was scrubbed... Name: dots.PNG Type: image/png Size: 47761 bytes Desc: not available URL: From manigopal.v at gmail.com Wed Jun 12 14:48:32 2013 From: manigopal.v at gmail.com (Manigopal Vepati) Date: Wed, 12 Jun 2013 18:18:32 +0530 Subject: [Tutor] python web related scripts needed Message-ID: Hi, I need scripts for the following . 1) check whether username and password fields are present in Gmail 2) Code to access the system which doesn?t have ip address i am using python 3.3 thanks manigopal -------------- next part -------------- An HTML attachment was scrubbed... URL: From pdw0005 at gmail.com Sat Jun 15 07:22:51 2013 From: pdw0005 at gmail.com (Patrick Williams) Date: Sat, 15 Jun 2013 01:22:51 -0400 Subject: [Tutor] Hi, First question Message-ID: Hi so I am making a bit of code to extract a bit of numbers data from a file and then find the average of that data, however while I can get the code to extract each specific piece of data I need, I can't seem to get the numbers to add separately so I can get a proper average. My sum1 variable seems to only take the last bit of data entered. I was just wondering if anyone knows what I'm doing wrong, the course I'm following hadn't started using regex (or even proper lists) at this point, so there must be a way to do it without. here's the code. the average of the data should be 0.6789 or something, but I get 0.0334343 or something. count=0 lst=list() fname='mbox-short.txt' fhand=open(fname) for line in fhand: if line.startswith('X-DSPAM-Confidence:'): count=count+1 colpos=line.find(':') zpos=line.find('0',colpos) num=float(line[zpos:50]) sum1=0+num avg=float(sum1)/int(count) print 'Count-', count,'--', 'Average-', avg Any help at all is appreciated, and thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jun 16 17:15:26 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 Jun 2013 16:15:26 +0100 Subject: [Tutor] just cleared the moderation queue., sorry for the backlog. Message-ID: FWIW about 6 or7 genuine messages and about a dozen spam... The usual ratio... :-( -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ricaraoz at gmail.com Sun Jun 16 17:25:56 2013 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 16 Jun 2013 12:25:56 -0300 Subject: [Tutor] 2 basic problems In-Reply-To: References: Message-ID: <51BDD904.9090800@gmail.com> El 29/05/13 18:23, charles benoit escribi?: > 1:Python 2.7.4 (default, Apr 19 2013, 18:32:33) > [GCC 4.7.3] on linux2 > Type "copyright", "credits" or "license()" for more information. > >>> 4+4 > 8 > >>> 3+3=4 > SyntaxError: can't assign to operator > >>> 3=1 > SyntaxError: can't assign to literal > > > I thought the last 2 lines should return False > > > 2: > lot=('1'+'6'+'8') > print(lot) > a=open("acc","w") > a.write(lot) > a.close > b=open("acc","r") > b.read() > print (b) > b.close > > > returns > >>> > 168 > > >>> > > I thought I was saving a string to a file and reading and printing the > string. The output looks like a description of the IO textwrapper at > some location. I'm sure this is a syntax/format problem.but this like > the other examples I saw. I ran this using python 2.6.7 on ubuntu > 13.0 Thank you for any help > Python 2.7.3 (default, Aug 1 2012, 05:16:07) [GCC 4.6.3] on linux2 Type "copyright", "credits" or "license()" for more information. ==== No Subprocess ==== >>> 2+2 4 >>> 4+4 8 >>> 4+4=6 SyntaxError: can't assign to operator >>> 4+4 == 6 False >>> From eryksun at gmail.com Sun Jun 16 17:35:26 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 16 Jun 2013 11:35:26 -0400 Subject: [Tutor] On a looping input, subsequent inputs are hidden In-Reply-To: References: <51B71F29.9030907@pearwood.info> Message-ID: On Tue, Jun 11, 2013 at 2:00 PM, Jim Mooney wrote: > On 11 June 2013 05:59, Steven D'Aprano wrote: > >> I'm afraid I don't understand what you mean. Second and subsequent inputs? I >> only see one. Hide the input with dots? >> >> Can you copy and paste an example? > > That would be a graphic of the input popup and this is a text-only > list. Or would an attachment work? > > Well, the best way to find out is to try. Graphic attached of the > second call to input since a non-integer was entered. If it appears, > the second input window, when I enter integers, shows little black > security-dots, as in web entries of your password, instead of the > integers. On the first input, I can see the numbers. In your original description, you said But the Second and subsequent inputs, in Windows, hide the input with dots, while the first shows the input, and I can't figure out why.... But it's just python input, not tkinter. Unless it's a Windows peculiarity. The input Always shows in DOS." I see now. When you said "in Windows", you meant you ran the script in PyScripter. Unlike IDLE, PyScripter chooses to pop up a dialog box for input. No wonder I couldn't reproduce the problem. Also, there is no DOS. If you're running 64-bit Windows you don't even have the NT Virtual DOS Machine (NTVDM) and can't run 16-bit DOS and Win16 apps without installing an emulator. What you keep calling 'DOS' is a console window, running text-mode *Windows* programs such as python.exe and cmd.exe. From rhettnaxel at gmail.com Sun Jun 16 17:40:30 2013 From: rhettnaxel at gmail.com (Alexander) Date: Sun, 16 Jun 2013 11:40:30 -0400 Subject: [Tutor] Hi, First question In-Reply-To: References: Message-ID: On Sat, Jun 15, 2013 at 1:22 AM, Patrick Williams wrote: > Hi so I am making a bit of code to extract a bit of numbers data from a > file and then find the average of that data, however while I can get the > code to extract each specific piece of data I need, I can't seem to get the > numbers to add separately so I can get a proper average. My sum1 variable > seems to only take the last bit of data entered. I was just wondering if > anyone knows what I'm doing wrong, the course I'm following hadn't started > using regex (or even proper lists) at this point, so there must be a way to > do it without. here's the code. the average of the data should be 0.6789 or > something, but I get 0.0334343 or something. > > count=0 > lst=list() > fname='mbox-short.txt' > fhand=open(fname) > for line in fhand: > if line.startswith('X-DSPAM-Confidence:'): > count=count+1 > colpos=line.find(':') > zpos=line.find('0',colpos) > num=float(line[zpos:50]) > sum1=0+num > avg=float(sum1)/int(count) > print 'Count-', count,'--', 'Average-', avg > > Any help at all is appreciated, and thanks in advance. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Please include the "mbox-short.txt" file. Also you should include the output of your code (copy and paste it). -- Alexander -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwpolska at gmail.com Sun Jun 16 17:45:34 2013 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sun, 16 Jun 2013 17:45:34 +0200 Subject: [Tutor] 2 basic problems In-Reply-To: References: Message-ID: On Wed, May 29, 2013 at 11:23 PM, charles benoit wrote: > 1:Python 2.7.4 (default, Apr 19 2013, 18:32:33) > [GCC 4.7.3] on linux2 > Type "copyright", "credits" or "license()" for more information. >>>> 4+4 > 8 >>>> 3+3=4 > SyntaxError: can't assign to operator >>>> 3=1 > SyntaxError: can't assign to literal >> > I thought the last 2 lines should return False `=` is the assignment operator (`a = 2` sets the variable `a` to the value of `2`), whereas `==` is the comparison operator. > 2: > lot=('1'+'6'+'8') > print(lot) > a=open("acc","w") > a.write(lot) > a.close missing `()` here > b=open("acc","r") > b.read() > print (b) 1. There should be no parenthesis here in Python 2. 2. The proper syntax is `print b.read()`. You are reading the text and discarding the return value (you aren?t setting a variable to it or passing it to something else, like print), then printing the information of what the `b` object is. > b.close missing `()` here, too > > > returns prints*, there is no return value >>>> > 168 > >>>> > > I thought I was saving a string to a file and reading and printing the > string. The output looks like a description of the IO textwrapper at some > location. I'm sure this is a syntax/format problem.but this like the other > examples I saw. I ran this using python 2.6.7 on ubuntu 13.0 Thank you for > any help Please use the 2.7.4 interpreter (the same one you used for the first example) instead. Moreover, you could do it all in one step ('w+' stands for ?clear file and allow read/write output?, while f.seek(0) is used to return the pointer back to the beginning of the file): f = open('acc', 'w+') f.write(lot) f.seek(0) print f.read() f.close() Or using the `with` syntax (a.k.a. the context manager syntax): with open('acc', 'w+') as f: f.write(lot) f.seek(0) print f.read() -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From kwpolska at gmail.com Sun Jun 16 17:55:59 2013 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sun, 16 Jun 2013 17:55:59 +0200 Subject: [Tutor] Hi, First question In-Reply-To: References: Message-ID: On Sat, Jun 15, 2013 at 7:22 AM, Patrick Williams wrote: > Hi so I am making a bit of code to extract a bit of numbers data from a file > and then find the average of that data, however while I can get the code to > extract each specific piece of data I need, I can't seem to get the numbers > to add separately so I can get a proper average. My sum1 variable seems to > only take the last bit of data entered. I was just wondering if anyone knows > what I'm doing wrong, the course I'm following hadn't started using regex > (or even proper lists) at this point, so there must be a way to do it > without. here's the code. the average of the data should be 0.6789 or > something, but I get 0.0334343 or something. > > count=0 > lst=list() `lst = []` is the preferred syntax. > fname='mbox-short.txt' > fhand=open(fname) > for line in fhand: > if line.startswith('X-DSPAM-Confidence:'): > count=count+1 > colpos=line.find(':') > zpos=line.find('0',colpos) > num=float(line[zpos:50]) > sum1=0+num > avg=float(sum1)/int(count) > print 'Count-', count,'--', 'Average-', avg > > Any help at all is appreciated, and thanks in advance. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I don?t know what file you used, but the message you sent got this header from Gmail, and the format doesn?t seem to be much different: > X-Spam-Evidence: '*H*': 0.79; '*S*': 0.00; 'separately': 0.09; > 'wrong,': 0.09; 'subject:question': 0.10; 'code.': 0.18; > 'variable': 0.18; 'bit': 0.19; 'advance.': 0.19; 'seems': 0.21; > '8bit%:5': 0.22; 'print': 0.22; 'skip:l 30': 0.24; '\xa0so': 0.24; > [snip 11 more lines] (replaced tabstops with spaces) Can you guess what?s wrong in your code? You are reading only the first line. There are more. How do you handle that? You need to make your algorithm read all the further lines that begin with the indentation your thing uses (it might be the tab character '\t' or some spaces), and stop when it encounters another header. This can be done either by checking if the line begins with the indentation OR by checking match with regexp '[A-Za-z]+: .+' -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html > From steve at alchemy.com Sun Jun 16 18:07:50 2013 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 16 Jun 2013 09:07:50 -0700 Subject: [Tutor] python web related scripts needed In-Reply-To: References: Message-ID: <602A8043-4A2D-4D5E-B8A8-BFE97770077B@alchemy.com> On 12-Jun-2013, at 05:48, Manigopal Vepati wrote: > Hi, > > I need scripts for the following . > > 1) check whether username and password fields are present in Gmail > 2) Code to access the system which doesn?t have ip address > And what have you found as you've started writing those scripts? Anything in particular you've run into that you're puzzled by? This list can be a wonderful resource to assist you as you learn to write your first scripts, but please remember that it is staffed by volunteers who take their valuable personal time to help others learn. We're not here to perform contract programming for you, or to do homework for you, just to help you along the way as you learn to program in Python. When you do get to a point where you need help, you need to be sure to ask meaningful questions and provide as much background information as would be needed for someone to truly understand what you're doing. For example, in the message you sent, it's impossible to know what you're even trying to accomplish because you don't say what you mean by "fields present in Gmail" (I can think of a dozen completely different things that could mean, and you don't give enough information to actually be able to move forward with any of them even were I to guess which of them you intended. I can't even make sense of the second one at all. You don't say what kind of access you're referring to, or what IP address has to do with anything (e.g., are you asking how to look up an IP address in DNS, or that the system isn't on a standard network which uses IP protocols, or what). Assuming that you have your programming goals better developed than is apparent in your email, make a good start at your implementation and then tell us in detail what you get stuck with. And just because we tend to get asked this from time to time, in case what you mean here is to somehow "hack" or illegally access a system you aren't otherwise allowed to access, we won't help you at all with anything like that. Don't bother even asking. > > i am using python 3.3 Ok, that's a very valuable piece of information. Since you're also accessing resources outside your scripts (other machines and mail services), it would also be useful to know the operating system and version of the systems involved. > > thanks > manigopal > _______________________________________________ > 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 breamoreboy at yahoo.co.uk Sun Jun 16 18:14:55 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 16 Jun 2013 17:14:55 +0100 Subject: [Tutor] python web related scripts needed In-Reply-To: References: Message-ID: On 12/06/2013 13:48, Manigopal Vepati wrote: > Hi, > > I need scripts for the following . > > 1) check whether username and password fields are present in Gmail > 2)Code to access the system which doesn?t have ip address > > > i am using python 3.3 > > > thanks > manigopal > Sorry but we don't work in this manner. You show that you've made an attempt to implement something and have run into problems, and we'll help. -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From breamoreboy at yahoo.co.uk Sun Jun 16 18:21:01 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 16 Jun 2013 17:21:01 +0100 Subject: [Tutor] Hi, First question In-Reply-To: References: Message-ID: On 16/06/2013 16:55, Chris ?Kwpolska? Warrick wrote: > On Sat, Jun 15, 2013 at 7:22 AM, Patrick Williams wrote: >> Hi so I am making a bit of code to extract a bit of numbers data from a file >> and then find the average of that data, however while I can get the code to >> extract each specific piece of data I need, I can't seem to get the numbers >> to add separately so I can get a proper average. My sum1 variable seems to >> only take the last bit of data entered. I was just wondering if anyone knows >> what I'm doing wrong, the course I'm following hadn't started using regex >> (or even proper lists) at this point, so there must be a way to do it >> without. here's the code. the average of the data should be 0.6789 or >> something, but I get 0.0334343 or something. >> >> count=0 >> lst=list() > > `lst = []` is the preferred syntax. > >> fname='mbox-short.txt' >> fhand=open(fname) >> for line in fhand: >> if line.startswith('X-DSPAM-Confidence:'): >> count=count+1 >> colpos=line.find(':') >> zpos=line.find('0',colpos) >> num=float(line[zpos:50]) >> sum1=0+num >> avg=float(sum1)/int(count) I'll assume unless someone tells me differently that sum1 does not need reinitialising every time, and that avg needs to be calculated when the loop has finished. >> print 'Count-', count,'--', 'Average-', avg >> >> Any help at all is appreciated, and thanks in advance. >> > > I don?t know what file you used, but the message you sent got this > header from Gmail, and the format doesn?t seem to be much different: > >> X-Spam-Evidence: '*H*': 0.79; '*S*': 0.00; 'separately': 0.09; >> 'wrong,': 0.09; 'subject:question': 0.10; 'code.': 0.18; >> 'variable': 0.18; 'bit': 0.19; 'advance.': 0.19; 'seems': 0.21; >> '8bit%:5': 0.22; 'print': 0.22; 'skip:l 30': 0.24; '\xa0so': 0.24; >> [snip 11 more lines] > (replaced tabstops with spaces) > > Can you guess what?s wrong in your code? > > You are reading only the first line. > What does "for line in fhand:" do then? -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From steve at alchemy.com Sun Jun 16 18:32:33 2013 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 16 Jun 2013 09:32:33 -0700 Subject: [Tutor] Hi, First question In-Reply-To: References: Message-ID: <06707319-2AFF-4602-B005-B099920AD88A@alchemy.com> On 16-Jun-2013, at 09:21, Mark Lawrence wrote: > On 16/06/2013 16:55, Chris ?Kwpolska? Warrick wrote: >> On Sat, Jun 15, 2013 at 7:22 AM, Patrick Williams wrote: >>> Hi so I am making a bit of code to extract a bit of numbers data from a file >>> and then find the average of that data, however while I can get the code to >>> extract each specific piece of data I need, I can't seem to get the numbers >>> to add separately so I can get a proper average. My sum1 variable seems to >>> only take the last bit of data entered. I was just wondering if anyone knows >>> what I'm doing wrong, the course I'm following hadn't started using regex >>> (or even proper lists) at this point, so there must be a way to do it >>> without. here's the code. the average of the data should be 0.6789 or >>> something, but I get 0.0334343 or something. >>> >>> count=0 >>> lst=list() >> >> `lst = []` is the preferred syntax. >> >>> fname='mbox-short.txt' >>> fhand=open(fname) >>> for line in fhand: >>> if line.startswith('X-DSPAM-Confidence:'): >>> count=count+1 >>> colpos=line.find(':') >>> zpos=line.find('0',colpos) >>> num=float(line[zpos:50]) >>> sum1=0+num >>> avg=float(sum1)/int(count) > > I'll assume unless someone tells me differently that sum1 does not need reinitialising every time, and that avg needs to be calculated when the loop has finished. > >>> print 'Count-', count,'--', 'Average-', avg >>> >>> Any help at all is appreciated, and thanks in advance. >>> >> >> I don?t know what file you used, but the message you sent got this >> header from Gmail, and the format doesn?t seem to be much different: >> >>> X-Spam-Evidence: '*H*': 0.79; '*S*': 0.00; 'separately': 0.09; >>> 'wrong,': 0.09; 'subject:question': 0.10; 'code.': 0.18; >>> 'variable': 0.18; 'bit': 0.19; 'advance.': 0.19; 'seems': 0.21; >>> '8bit%:5': 0.22; 'print': 0.22; 'skip:l 30': 0.24; '\xa0so': 0.24; >>> [snip 11 more lines] >> (replaced tabstops with spaces) >> >> Can you guess what?s wrong in your code? >> >> You are reading only the first line. > > > What does "for line in fhand:" do then? I think what that was referring to was the assumption that you're reading mail header lines from that file, and they can be split out over multiple lines (see the example cited above). If that's the case, then "for line in fhand" will iterate over each line in the file, but you're only looking for lines which start with "X-Spam-.." which would only be the FIRST part of the header if it's split out like that. If your file is NOT organized like that, then your situation is different. However, if your files are like that, you're going to randomly miss data if the fields you're looking for don't happen to be on the first line of the multi-line header. Now if you are reading RFC-822 (et al) standard mail messages in those files, there are bits of the Python standard library which will be immensely useful to you in parsing out those headers rather than trying to do it yourself. That's something you're going to find to be the case frequently with Python. > > -- > "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. > > Mark Lawrence > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sun Jun 16 19:09:06 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 Jun 2013 18:09:06 +0100 Subject: [Tutor] 2 basic problems In-Reply-To: References: Message-ID: On 16/06/13 16:45, Chris ?Kwpolska? Warrick wrote: > Moreover, you could do it all in one step ('w+' stands for ?clear file > and allow read/write output?, while f.seek(0) is used to return the > pointer back to the beginning of the file): I'm always very wary of recommending mixed read/write mode to beginners. Its simple in this case but in other scenarios its very easy to lose track of where the cursor is and start overwriting your previously written data! I usually recommend writing the data, closing the file, and then opening for reading. Powerful tools have the capacity to be powerfully bad as well as good... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Jun 16 19:15:14 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 Jun 2013 18:15:14 +0100 Subject: [Tutor] Hi, First question In-Reply-To: References: Message-ID: On 15/06/13 06:22, Patrick Williams wrote: > Hi so I am making a bit of code to extract a bit of numbers data from a > file and then find the average of that data, however while I can get the > code to extract each specific piece of data I need, I can't seem to get > the numbers to add separately so I can get a proper average. My sum1 > variable seems to only take the last bit of data entered. > for line in fhand: > if line.startswith('X-DSPAM-Confidence:'): > count=count+1 > colpos=line.find(':') > zpos=line.find('0',colpos) > num=float(line[zpos:50]) > sum1=0+num Are you sure that last line is right? Its effectively just doing sum1 = num adding zero does nothing interesting. So sum1 ends up at whatever num was at the end of the loop. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sunithanc at gmail.com Sun Jun 16 19:15:59 2013 From: sunithanc at gmail.com (SM) Date: Sun, 16 Jun 2013 13:15:59 -0400 Subject: [Tutor] How to redirect console output to a TextEdit box on a QT Python Gui ? Message-ID: Hi I have implemented a GUI using PyQt4/python3, which allows the user to select a few files as command-line arguments. When I hit "OK" button, my application runs and the output text is displayed on the terminal where I run the python script. I would like to redirect this text to a TextEdit window I have created on the GUI: self.textEdit = QtGui.QTextEdit(Form) self.textEdit.setGeometry(QtCore.QRect(10, 300, 421, 141)) self.textEdit.setObjectName(_fromUtf8("textEdit")) Do you have any suggestions/tips as to how I can accomplish this task? Using some suggestions online, I tried creating a QProcess object and connect the signal to a function which reads the std output. But I don't know how to set the arguments to the call "process.start". self.process = QtCore.QProcess() QtCore.QObject.connect(self.process, QtCore.SIGNAL("readyReadStdout()"), self.readOutput) I know I have to call self.process.start here but am not able to find examples of how to do it. One example online uses "self.process.setArguments", but python3/pyQt4 doesn't seem to know about it. Using the argument directly with process.start is not helping either. Appreciate any pointers. If there are better ways than what I am trying to use, appreciate that as well. Thanks, -SM -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Sun Jun 16 19:20:49 2013 From: timomlists at gmail.com (Timo) Date: Sun, 16 Jun 2013 19:20:49 +0200 Subject: [Tutor] How to find descendants recursively? Message-ID: I have a datafile which is parsed by an external library, I'm having trouble creating a hierarchical structure of the data. This is what I got so far: items = get_items() # returns a generator for item in items: print(item) children = get_children(item) # also returns a generator for child in children: print("--", child) This is fine as it will get the children for each parent item. I can't seem to figure out how to go further and get the chidren of the children and so on. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Sun Jun 16 19:21:00 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 16 Jun 2013 10:21:00 -0700 Subject: [Tutor] The Whole Tree Message-ID: My first impression of Python was that it had dynamic types but didn't mix them. so if I was wrong on equality, is there a general rule of what different types can still be equal? Is it an inheritance thing? Speaking of which, I put "Python class hierarchy" in Google but just got a bunch of specific wheeze. What I want is a list of the whole tree. Is there such, or a way I can generate it? -- Jim Everyone has made bad decisions; it's just that some pretend they haven't. From cybervigilante at gmail.com Sun Jun 16 19:25:38 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 16 Jun 2013 10:25:38 -0700 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: <51BD5B87.5080103@davea.name> References: <20130615213407.306cc842@Hof> <51BD08AA.8060202@pearwood.info> <51BD1A90.1030608@davea.name> <51BD53FF.7040801@pearwood.info> <51BD5B87.5080103@davea.name> Message-ID: On 15 June 2013 23:30, Dave Angel wrote: >>> The sort() method doesn't work, but sorted does. How many times have I read you can't sort a dictionary in Python. Was I just misreading or was that true of older Pythons? -- Jim After indictment the bacon smuggler was put on the no-fry list From cybervigilante at gmail.com Sun Jun 16 19:49:58 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 16 Jun 2013 10:49:58 -0700 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> Message-ID: On 16 June 2013 01:43, Roel Schroeven wrote: > Can't you disable that behavior somewhere in the settings of your IDE? I > know IDEs do that to be helpful, but I don't like it and so far I've been > able to disable it in all IDEs I've used. PyScripter does in Tools > Options > IDE Options > Editor > Auto-complete brackets (which also kills quotes but doesn't tell you.) It looks like a non-fine-grained choice, though. You can't just kill quotes - you have to kill all bracket auto-completion. Which was overkill in my case, so I'll keep my keyboard remapping. The best tool I've seen for that, and for all sorts of automation (including programmatic) is a free windows program called autohotkey. I've only scratched the surface, but it looks like it can do everything but cook eggs. VIM sounds good but I don't think there's a version for Windows. Keeping different programs open is great if you have dual monitors, which I did when I was webmastering. Alas, some $#@ fooled with my computer and wiped out the dual monitor card. But when I fixed his front end I left a bolt off and his wheel went rolling down the highway, so I guess we're even ;') As for the one-week learning curve on VIM, reminds me of that claim for Joomla. Yes, you can set up a site in a few hours after your first install of Joomla, but learning to fix the blowups and problems while people are screaming at you, since it's all public, takes considerably longer. Although an editor that's been around since the stone age probably doesn't blow up. I doubt VIM has a constant stream of upgrades (not always compatible), bug fixes, and security fixes ;') -- Jim After indictment the bacon smuggler was put on the no-fry list From alan.gauld at btinternet.com Sun Jun 16 19:51:48 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 Jun 2013 18:51:48 +0100 Subject: [Tutor] The Whole Tree In-Reply-To: References: Message-ID: On 16/06/13 18:21, Jim Mooney wrote: > My first impression of Python was that it had dynamic types but didn't > mix them. Umm yes, sort of. It depends on how you define some of those terms though. "mix them"??? > so if I was wrong on equality, is there a general rule of > what different types can still be equal? I'm not sure what was wrong with equality? Whether two types can be compared depends on whether the comparison operators for those types work. Its hard to tell in advance, that's why you should use try/except to catch the errors (better to ask forgiveness principle...) > Is it an inheritance thing? That can play a part. But its not the only factor. > Speaking of which, I put "Python class hierarchy" in Google but just > got a bunch of specific wheeze. What I want is a > list of the whole tree. Is there such, Not that I'm aware. Not even for the standard library. As far as I can recall Pythonwin IDE under Windows has a class browser that will show the heirarchy for any given object. But I haven't used it in a long time, I may be mistaken. Your IDE (Wing?) may have a similar feature... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kwpolska at gmail.com Sun Jun 16 19:54:31 2013 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sun, 16 Jun 2013 19:54:31 +0200 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> <51BD08AA.8060202@pearwood.info> <51BD1A90.1030608@davea.name> <51BD53FF.7040801@pearwood.info> <51BD5B87.5080103@davea.name> Message-ID: On Sun, Jun 16, 2013 at 7:25 PM, Jim Mooney wrote: > On 15 June 2013 23:30, Dave Angel wrote: > >>>> The sort() method doesn't work, but sorted does. > > How many times have I read you can't sort a dictionary in Python. Was > I just misreading or was that true of older Pythons? Dicts have no order: >>> {'b': 'c', 'a': 'z'} {'a': 'z', 'b': 'c'} Moreover, the sorted() function sorts the keys only (something that list() does anyway). If you are looking for a way to have dicts with an order of keys (and you don?t need that most of the time), look at collection.OrderedDict. -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From steve at alchemy.com Sun Jun 16 19:59:10 2013 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 16 Jun 2013 10:59:10 -0700 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> Message-ID: <5ED36374-6E31-4C35-9BE5-9FDEC6A83E44@alchemy.com> On 16-Jun-2013, at 10:49, Jim Mooney wrote: > On 16 June 2013 01:43, Roel Schroeven wrote: > >> Can't you disable that behavior somewhere in the settings of your IDE? I >> know IDEs do that to be helpful, but I don't like it and so far I've been >> able to disable it in all IDEs I've used. > > > VIM sounds good but I don't think there's a version for Windows. There's a version of VIM for about everything, including Windows and OS X. > As for the one-week learning curve on VIM, reminds me of that claim > for Joomla. Yes, you can set up a site in a few hours after your first > install of Joomla, but learning to fix the blowups and problems while > people are screaming at you, since it's all public, takes considerably > longer. Although an editor that's been around since the stone age > probably doesn't blow up. I doubt VIM has a constant stream of > upgrades (not always compatible), bug fixes, and security fixes ;') Yeah, at this point it's pretty stable. From alan.gauld at btinternet.com Sun Jun 16 19:56:46 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 Jun 2013 18:56:46 +0100 Subject: [Tutor] How to find descendants recursively? In-Reply-To: References: Message-ID: On 16/06/13 18:20, Timo wrote: > items = get_items() # returns a generator > for item in items: > print(item) > children = get_children(item) # also returns a generator > for child in children: > print("--", child) > > This is fine as it will get the children for each parent item. I can't > seem to figure out how to go further and get the chidren of the children > and so on. Presumably you can call get_children on each child? children = get_children(item) # also returns a generator for child in children: grandchildren = get_children(child) If you don't know how many levels it goes down the normal approach is to use recursion to define a function that get called until the result is empty. If there are too many layers for recursion then you will need to keep a flag to count the layers and create/manage the heirarchy pointer for you. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kwpolska at gmail.com Sun Jun 16 20:02:29 2013 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sun, 16 Jun 2013 20:02:29 +0200 Subject: [Tutor] How to redirect console output to a TextEdit box on a QT Python Gui ? In-Reply-To: References: Message-ID: On Sun, Jun 16, 2013 at 7:15 PM, SM wrote: > Hi > I have implemented a GUI using PyQt4/python3, which allows the user to > select a few files as command-line arguments. When I hit "OK" button, my > application runs and the output text is displayed on the terminal where I > run the python script. I would like to redirect this text to a TextEdit > window I have created on the GUI: > > self.textEdit = QtGui.QTextEdit(Form) > self.textEdit.setGeometry(QtCore.QRect(10, 300, 421, 141)) > self.textEdit.setObjectName(_fromUtf8("textEdit")) > > Do you have any suggestions/tips as to how I can accomplish this task? Using > some suggestions online, I tried creating a QProcess object and connect the > signal to a function which reads the std output. But I don't know how to > set the arguments to the call "process.start". > > self.process = QtCore.QProcess() > QtCore.QObject.connect(self.process, QtCore.SIGNAL("readyReadStdout()"), > self.readOutput) > I know I have to call self.process.start here but am not able to find > examples of how to do it. One example online uses > "self.process.setArguments", but python3/pyQt4 doesn't seem to know about > it. Using the argument directly with process.start is not helping either. > > Appreciate any pointers. If there are better ways than what I am trying to > use, appreciate that as well. If the application you run is a Python script, import it, execute the functions and have the data returned (as opposed to printing it), and then you can do self.textEdit.setText(output_goes_here) If the application isn?t Python, use the (stock aka vanilla) subprocess module. The easiest solution is: import subprocess self.textEdit.setText(subprocess.check_output(('command', 'argument1', 'argument2'))) And you do that in the function that is called when you press OK. Bonus suggestion: do nice layouts instead of setting the coordinates manually. The options you want are in the Form menu of Qt Designer. If you don?t do this, resizing windows is nonsense. -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From cybervigilante at gmail.com Sun Jun 16 20:05:36 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 16 Jun 2013 11:05:36 -0700 Subject: [Tutor] just cleared the moderation queue., sorry for the backlog. In-Reply-To: References: Message-ID: On 16 June 2013 08:15, Alan Gauld wrote: > FWIW about 6 or7 genuine messages and about a dozen spam... > The usual ratio... :-( > I was wondering why my message showed up late. I Already had the answer and it was only moderated because I tried a picture attachment to reply to a query. Only a dozen? You're lucky this is not a Really high volume and more general list. I spend a half hour every week just deleting junk email, unsubscribing from things, blocking or reporting spam, etc. I've "subscribed" to things I've never heard of. But I keep my old webmaster email, which got a lot of traffic. One trick you have to watch out for is a blanket email with a phony unsub link. That's to find out if there's a live person on the other end, rather than a dead box chosen at random from a huge spam-list. When you unsub, they can then try to really get you with a phony letter from your bank or "You won a Prize" or something more devious. Although the appeals from Nigerian princes have dropped way off ;') Jim From steve at pearwood.info Sun Jun 16 20:28:08 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 17 Jun 2013 04:28:08 +1000 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> <51BD08AA.8060202@pearwood.info> <51BD1A90.1030608@davea.name> <51BD53FF.7040801@pearwood.info> <51BD5B87.5080103@davea.name> Message-ID: <51BE03B8.60202@pearwood.info> On 17/06/13 03:25, Jim Mooney wrote: > On 15 June 2013 23:30, Dave Angel wrote: > >>>> The sort() method doesn't work, but sorted does. > > How many times have I read you can't sort a dictionary in Python. Was > I just misreading or was that true of older Pythons? You can't sort a dictionary, because dicts don't have any inherent order. (Unlike paper dictionaries.) That's done for performance reasons. However, if you extract the keys from a dict, you can sort the keys separately. So mydict.sort() fails, since dicts can't be sorted. But: keys = list(mydict.keys()) keys.sort() works fine. And here's something which, at first glance, *appears* to be sorting a dict, but actually isn't: sorted(mydict) => returns a list of mydict's keys, sorted. -- Steven From andipersti at gmail.com Sun Jun 16 20:32:41 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Sun, 16 Jun 2013 20:32:41 +0200 Subject: [Tutor] The Whole Tree In-Reply-To: References: Message-ID: <51BE04C9.9080308@gmail.com> On 16.06.2013 19:21, Jim Mooney wrote: > Speaking of which, I put "Python class hierarchy" in Google but just > got a bunch of specific wheeze. What I want is a > list of the whole tree. Is there such, or a way I can generate it? I'm not sure if that's what you are looking for but the language reference describes the standard type hierarchy: http://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy Bye, Andreas From steve at pearwood.info Sun Jun 16 20:35:10 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 17 Jun 2013 04:35:10 +1000 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: <5ED36374-6E31-4C35-9BE5-9FDEC6A83E44@alchemy.com> References: <20130615213407.306cc842@Hof> <5ED36374-6E31-4C35-9BE5-9FDEC6A83E44@alchemy.com> Message-ID: <51BE055E.2000305@pearwood.info> On 17/06/13 03:59, Steve Willoughby wrote: > > On 16-Jun-2013, at 10:49, Jim Mooney wrote: > >> On 16 June 2013 01:43, Roel Schroeven wrote: >> >>> Can't you disable that behavior somewhere in the settings of your IDE? I >>> know IDEs do that to be helpful, but I don't like it and so far I've been >>> able to disable it in all IDEs I've used. >> >> >> VIM sounds good but I don't think there's a version for Windows. > > There's a version of VIM for about everything, including Windows and OS X. Pfft! VIM. VIM is not the standard editor. There is only one standard editor, ed. That's why it's called an EDitor, not a VIMitor. http://www.gnu.org/fun/jokes/ed-msg.html As for stability, ed hasn't been updated since 1929. There's no need -- how can you improve perfection? -- Steven From steve at alchemy.com Sun Jun 16 20:48:51 2013 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 16 Jun 2013 11:48:51 -0700 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: <51BE055E.2000305@pearwood.info> References: <20130615213407.306cc842@Hof> <5ED36374-6E31-4C35-9BE5-9FDEC6A83E44@alchemy.com> <51BE055E.2000305@pearwood.info> Message-ID: <79CDFC9D-3A30-45C5-ACD9-1EBCF8F9E7EF@alchemy.com> On 16-Jun-2013, at 11:35, Steven D'Aprano wrote: > On 17/06/13 03:59, Steve Willoughby wrote: >> >> On 16-Jun-2013, at 10:49, Jim Mooney wrote: >> >>> On 16 June 2013 01:43, Roel Schroeven wrote: >>> >>>> Can't you disable that behavior somewhere in the settings of your IDE? I >>>> know IDEs do that to be helpful, but I don't like it and so far I've been >>>> able to disable it in all IDEs I've used. >>> >>> >>> VIM sounds good but I don't think there's a version for Windows. >> >> There's a version of VIM for about everything, including Windows and OS X. > > Pfft! VIM. VIM is not the standard editor. There is only one standard editor, ed. That's why it's called an EDitor, not a VIMitor. Pfft. Only for people who can't handle using the Real One True Editor: TECO. http://en.wikipedia.org/wiki/TECO_(text_editor) steve Although I admit back in my MSDOS days I found a copy of ED which was ported there since it was at least infinitely better than EDLIN. And to be fair, VIM grew out of the classic vi which itself grew directly out of ed, so there's a little ed hiding in VIM trying to escape. From joel.goldstick at gmail.com Sun Jun 16 20:55:01 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 16 Jun 2013 14:55:01 -0400 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: <79CDFC9D-3A30-45C5-ACD9-1EBCF8F9E7EF@alchemy.com> References: <20130615213407.306cc842@Hof> <5ED36374-6E31-4C35-9BE5-9FDEC6A83E44@alchemy.com> <51BE055E.2000305@pearwood.info> <79CDFC9D-3A30-45C5-ACD9-1EBCF8F9E7EF@alchemy.com> Message-ID: On Sun, Jun 16, 2013 at 2:48 PM, Steve Willoughby wrote: > > On 16-Jun-2013, at 11:35, Steven D'Aprano wrote: > > > On 17/06/13 03:59, Steve Willoughby wrote: > >> > >> On 16-Jun-2013, at 10:49, Jim Mooney wrote: > >> > >>> On 16 June 2013 01:43, Roel Schroeven wrote: > >>> > >>>> Can't you disable that behavior somewhere in the settings of your > IDE? I > >>>> know IDEs do that to be helpful, but I don't like it and so far I've > been > >>>> able to disable it in all IDEs I've used. > >>> > >>> > >>> VIM sounds good but I don't think there's a version for Windows. > >> > >> There's a version of VIM for about everything, including Windows and OS > X. > > > > Pfft! VIM. VIM is not the standard editor. There is only one standard > editor, ed. That's why it's called an EDitor, not a VIMitor. > > > Pfft. Only for people who can't handle using the Real One True Editor: > TECO. > > http://en.wikipedia.org/wiki/TECO_(text_editor) > I remember teco. It could do anything -- a line editor and text processor all in one. Then I worked on a Data General project and had to use SPEED. I think VIM is somehow a descendent of TECO > > steve > > > Although I admit back in my MSDOS days I found a copy of ED which was > ported there since it was at least infinitely better than EDLIN. > And to be fair, VIM grew out of the classic vi which itself grew directly > out of ed, so there's a little ed hiding in VIM trying to escape. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Jun 16 21:17:24 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 17 Jun 2013 05:17:24 +1000 Subject: [Tutor] The Whole Tree In-Reply-To: References: Message-ID: <51BE0F44.5040403@pearwood.info> On 17/06/13 03:21, Jim Mooney wrote: > My first impression of Python was that it had dynamic types but didn't > mix them. so if I was wrong on equality, is there a general rule of > what different types can still be equal? Is it an inheritance thing? The general rule is, types can define equality whatever way makes sense for themselves. That usually means: * All numeric types are normally considered compatible; that is, if two numbers have the same numeric value, they should compare equal even if they have different types. * Instances of a class and any of its subclasses are expected to compare equal if they have the same value. * Unrelated classes are expected to compare unequal. * By default, objects compare equal only to themselves. * But equality is under the programmer's control with the __eq__ and __ne__ (equal and not-equal) methods. > Speaking of which, I put "Python class hierarchy" in Google but just > got a bunch of specific wheeze. What I want is a > list of the whole tree. Is there such, or a way I can generate it? It's a pretty shallow tree. Off the top of my head, the built-ins look something like this in Python 3: object +-- BaseException +-- a bunch of exception subclasses +-- BuiltinFunctionType (*) +-- bytearray +-- bytes +-- CodeType (*) +-- complex +-- dict +-- float +-- frozenset +-- FunctionType (*) +-- int +-- bool +-- list +-- NoneType (*) +-- range +-- set +-- str +-- tuple +-- type plus some more exotic built-ins, which I haven't shown. Items marked (*) are built-in types, but you need to import them from the types module to get access to them by name. Nearly all other classes and types inherit directly from object, Python doesn't usually go in for the sort of deeply nested hierarchies that Java loves. However, there is a complication: ABCs (Abstract Base Classes). ABCs introduce something of a hierarchy to Python objects, one which is not reflected by the (shallow) inheritance hierarchy shown above. ABCs can be considered relatively advanced, so don't worry about them if you don't wish to. As far as I know, there is no documented tree of *all* Python types in the standard library. It would be big, boring, shallow, and contain an awful lot types which are for internal use only and not useable by the programmer. -- Steven From cybervigilante at gmail.com Sun Jun 16 21:49:32 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 16 Jun 2013 12:49:32 -0700 Subject: [Tutor] The Whole Tree In-Reply-To: <51BE04C9.9080308@gmail.com> References: <51BE04C9.9080308@gmail.com> Message-ID: On 16 June 2013 11:32, Andreas Perstinger wrote: > I'm not sure if that's what you are looking for but the language reference > describes the standard type hierarchy: > http://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy Yes, that's what I meant. I was thinking of an actual visible tree, but it doesn't go that deep, so that wouldn't be of use. Jim From cybervigilante at gmail.com Sun Jun 16 22:26:11 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 16 Jun 2013 13:26:11 -0700 Subject: [Tutor] Getting the real exception clause Message-ID: '''I'm using general Exception to print out what the exception is until I learn them, but it will print out "[Errno 2] No such file or directory" in this case, when the real exception I'd need to use in an except clause is FileNotFoundError. How do I get the exception I need to use in the except clause from the more English-like message? ''' #Using C:\Python33\python.exe on Win 7 in c:\python33\jimprogs try: fh = open('nosuchdirectory/text/truthyfalsey.txt') for line in fh: print(line,end='') fh.close() except Exception as err: print(err) Jim After indictment the bacon smuggler was put on the no-fry list From breamoreboy at yahoo.co.uk Sun Jun 16 22:52:16 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 16 Jun 2013 21:52:16 +0100 Subject: [Tutor] Getting the real exception clause In-Reply-To: References: Message-ID: On 16/06/2013 21:26, Jim Mooney wrote: > '''I'm using general Exception to print out what the exception is > until I learn them, but > it will print out "[Errno 2] No such file or directory" in this case, > when the real > exception I'd need to use in an except clause is FileNotFoundError. > How do I get the > exception I need to use in the except clause from the more English-like message? > ''' > > #Using C:\Python33\python.exe on Win 7 in c:\python33\jimprogs > try: > fh = open('nosuchdirectory/text/truthyfalsey.txt') > for line in fh: > print(line,end='') > fh.close() > except Exception as err: > print(err) > > Jim > After indictment the bacon smuggler was put on the no-fry list Easy, strip out the exception handling you have above. c:\Users\Mark\MyPython>type a.py with open('nosuchdirectory/text/truthyfalsey.txt') as fh: for line in fh: print(line,end='') c:\Users\Mark\MyPython>a Traceback (most recent call last): File "C:\Users\Mark\MyPython\a.py", line 1, in with open('nosuchdirectory/text/truthyfalsey.txt') as fh: FileNotFoundError: [Errno 2] No such file or directory: 'nosuchdirectory/text/truthyfalsey.txt' A slight aside, note I've used the 'with' clause so there's no need to explicity close the file, good ole Python does it for you. -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From python at outofoptions.net Sun Jun 16 23:01:15 2013 From: python at outofoptions.net (python at outofoptions.net) Date: Sun, 16 Jun 2013 17:01:15 -0400 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> Message-ID: <51BE279B.40502@outofoptions.net> On 06/16/2013 01:49 PM, Jim Mooney wrote: > VIM sounds good but I don't think there's a version for Windows. > Keeping different programs open is great if you have dual monitors, > which I did when I was webmastering. Alas, some $#@ fooled with my > computer and wiped out the dual monitor card. But when I fixed his > front end I left a bolt off and his wheel went rolling down the > highway, so I guess we're even ;') As for the one-week learning curve > on VIM, reminds me of that claim for Joomla. Yes, you can set up a > site in a few hours after your first install of Joomla, but learning > to fix the blowups and problems while people are screaming at you, > since it's all public, takes considerably longer. Although an editor > that's been around since the stone age probably doesn't blow up. I > doubt VIM has a constant stream of upgrades (not always compatible), > bug fixes, and security fixes ;') vimtutor gets you a good start rather quickly. From joel.goldstick at gmail.com Sun Jun 16 23:21:04 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 16 Jun 2013 17:21:04 -0400 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: <51BE279B.40502@outofoptions.net> References: <20130615213407.306cc842@Hof> <51BE279B.40502@outofoptions.net> Message-ID: On Sun, Jun 16, 2013 at 5:01 PM, python at outofoptions.net < python at outofoptions.net> wrote: > On 06/16/2013 01:49 PM, Jim Mooney wrote: > >> VIM sounds good but I don't think there's a version for Windows. > > There definitely is a windows version Keeping different programs open is great if you have dual monitors, which I >> did when I was webmastering. Alas, some $#@ fooled with my computer and >> wiped out the dual monitor card. But when I fixed his front end I left a >> bolt off and his wheel went rolling down the highway, so I guess we're even >> ;') As for the one-week learning curve on VIM, reminds me of that claim for >> Joomla. Yes, you can set up a site in a few hours after your first install >> of Joomla, but learning to fix the blowups and problems while people are >> screaming at you, since it's all public, takes considerably longer. >> Although an editor that's been around since the stone age probably doesn't >> blow up. I doubt VIM has a constant stream of upgrades (not always >> compatible), bug fixes, and security fixes ;') >> > > Vim is active. Lots of people really like it so lots of add ons. But you are right about not being able to master it in a week. You can use it on day one, but keep learning more about what it can do for you for -- well maybe forever. The good thing about Vim (well its not installed on Windows) is that it is usually just there on any *nix system and I think Mac too. So even if you don't like it for your primary editor its good to know a little VIM if you have need to log onto various machines > vimtutor gets you a good start rather quickly. > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Jun 17 00:41:13 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 16 Jun 2013 23:41:13 +0100 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> Message-ID: On 16 June 2013 18:49, Jim Mooney wrote: > Although an editor that's been around since the stone age > probably doesn't blow up. I doubt VIM has a constant stream of > upgrades (not always compatible), bug fixes, and security fixes ;') I use Vim pretty much exclusively and work on Linux and Windows. It does have a constant stream of upgrades and fixes but the core functionality hasn't changed in any noticeable way in years. However Vim already has much more functionality than I will ever use; since I only know a small subset of what it can already do I don't really notice new features as they are added. The only time I can remember discovering a new feature in Vim and then actually using it is with "undo branches" and apparently (I just checked) this feature was released in 2006. Typically if I think that I want Vim to have some or other feature I find after a quick search that Vim already has several ways of doing what I want. There is also an active community writing third-party plugins for Vim and this is probably where the bulk of significant new features are developed. Oscar From cybervigilante at gmail.com Mon Jun 17 01:12:13 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 16 Jun 2013 16:12:13 -0700 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> Message-ID: > There is also an active community writing third-party plugins for Vim > and this is probably where the bulk of significant new features are > developed. So as Dr. Frankenstein exclaimed: "It's Alive!" ;') -- Jim After indictment the bacon smuggler was put on the no-fry list From davea at davea.name Mon Jun 17 01:21:36 2013 From: davea at davea.name (Dave Angel) Date: Sun, 16 Jun 2013 19:21:36 -0400 Subject: [Tutor] How to find descendants recursively? In-Reply-To: References: Message-ID: <51BE4880.5070707@davea.name> On 06/16/2013 01:20 PM, Timo wrote: > I have a datafile which is parsed by an external library, I'm having > trouble creating a hierarchical structure of the data. > > This is what I got so far: > > items = get_items() # returns a generator > for item in items: > print(item) > children = get_children(item) # also returns a generator > for child in children: > print("--", child) > > This is fine as it will get the children for each parent item. I can't seem > to figure out how to go further and get the chidren of the children and so > on. > I can't see any way of doing recursion without writing a function. You can always fake it, but if you want the language's help, do it in a function. We don't know your external library. But if the effect is to produce a tree, where any node may have items as children, then recursion is the easiest way to process the whole tree. Some assumptions are important: The tree has reasonable max-depth, like less than 1000. If it's somewhat larger, but has a known limit, you can probably just get away with telling Python to use a larger stacksize. But if the depth could be arbitrarily large, say a million levels, then you need another approach than the language's recursion. Second assumption is that no node appears more than once in the tree. For example, in a Unix directory tree, if a symlink points back up the tree, it can cause troubles. Avoiding these troubles is not hard if you plan ahead, but it's easier if you know it cannot happen. Assuming the tree is well-enough behaved then, we want to define a function, with a name, that will call itself. Each time you descend into a child node, you call the function recursively to process that childlist. Now, eventually you'll probably want to make this recursive function a generator, so you can reuse it for other tree processing of the same kind of tree. But that can wait. First you have to decide how you can test the limit-condition. For example, perhaps your unknown library returns Null from the get_children() call if there are no children. Or perhaps there's another call, like has_children() which returns a bool. Without knowing that, it's hard to structure the rest of the function. But roughly it looks like: after the children= line, simply test your condition and call yourself with children as the argument. children = get_children(item) if children not is None: my_recursive_function(children) You don't need or want to write a loop for child in children, since that same loop is already written (if item in items). You pick your own better name for the function, based on what it does. -- DaveA From oscar.j.benjamin at gmail.com Mon Jun 17 01:30:25 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Jun 2013 00:30:25 +0100 Subject: [Tutor] The Whole Tree In-Reply-To: References: <51BE04C9.9080308@gmail.com> Message-ID: On 16 June 2013 20:49, Jim Mooney wrote: > On 16 June 2013 11:32, Andreas Perstinger wrote: > >> I'm not sure if that's what you are looking for but the language reference >> describes the standard type hierarchy: >> http://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy > > Yes, that's what I meant. I was thinking of an actual visible tree, > but it doesn't go that deep, so that wouldn't be of use. As Steven mentioned Java has a complex inheritance tree for its objects. However the reason for that is that Java is statically typed and the compiler makes guarantees about the compiled code based on the type hierarchy. Having a complex hierarchy gives programmers the flexibility to specify broad sets of types that are acceptable in a particular context. For the most part in Python exactly where the type of an object appears in some class hierarchy doesn't really matter. Consequently there's often not really any point in putting objects into a hierarchy unless they actually share a significant amount of code. Unless someone goes out of their way to actually test the type of an object with isinstance() the class hierarchy can often be considered irrelevant. The exception to this is exception classes. When an exception is caught with try/except the isinstance() function is used for matching. The exception class hierarchy is precisely what determines whether or not an exception is caught. As a result there is something of a tree that you can see here: http://docs.python.org/3.3/library/exceptions.html#exception-hierarchy Otherwise in Python what matters is in many cases is that an object has the right methods or properties. It is common to specify (in documentation) that the input to a function should be e.g. an "iterable", a "sequence" or a "number" rather than explicitly require a set of types or a subtree of a class hierarchy. This specification implicitly designates that the object shall have certain properties but in Python this not enforced (until you attempt to use a missing property). This approach is similar to interfaces in Java or to the type system of Haskell but is fuzzier than both. You can see a representation of the core Haskell type system here: http://www.haskell.org/onlinereport/basic.html#standard-classes As Steven mentioned Python also has an abstract base class hierarchy. This is unrelated to the actual class inheritance hierarchy and is based on objects having the appropriate properties to be an "iterator" etc. The table here describes the hierarchy and associated methods: http://docs.python.org/dev/library/collections.abc.html I was interested to see how that would look as a tree so I constructed a dot file for the graph: $ cat collections.dot digraph G{ Container Hashable Iterable Iterable -> Iterator Callable {Sized Iterable Container} -> Sequence Sequence -> MutableSequence {Sized Iterable Container} -> Set Set -> MutableSet {Sized Iterable Container} -> Mapping Mapping -> MutableMapping Sized -> MappingView {MappingView Set} -> ItemsView {MappingView Set} -> KeysView MappingView -> ValuesView } If you have graphviz installed you can turn this into a png image with: $ dot -Tpng -o collections.png < collections.dot Oscar From alan.gauld at btinternet.com Mon Jun 17 01:35:09 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Jun 2013 00:35:09 +0100 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> <5ED36374-6E31-4C35-9BE5-9FDEC6A83E44@alchemy.com> <51BE055E.2000305@pearwood.info> <79CDFC9D-3A30-45C5-ACD9-1EBCF8F9E7EF@alchemy.com> Message-ID: On 16/06/13 19:55, Joel Goldstick wrote: > I think VIM is somehow a descendent of TECO I think your confusing it with emacs which originally stood for EditingMACroS and was just a set of Teco macros which made it easier to use. Then James Gosling and Richard Stallman got their respective hands on it... :-) Vim is a descendant of vi (by Bill Joy of Sun fame) which is a descendant of ex which is an enhanced (eXtended) version of ed. My first unix box didn't have a vi, it only had ex... And in Uni I did my final year project using SCRED which was the OS/9 clone of vi... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at davea.name Mon Jun 17 01:36:34 2013 From: davea at davea.name (Dave Angel) Date: Sun, 16 Jun 2013 19:36:34 -0400 Subject: [Tutor] The Whole Tree In-Reply-To: References: Message-ID: <51BE4C02.5010900@davea.name> On 06/16/2013 01:21 PM, Jim Mooney wrote: > My first impression of Python was that it had dynamic types but didn't > mix them. so if I was wrong on equality, is there a general rule of > what different types can still be equal? Is it an inheritance thing? > Several other good replies, but I'll give my two cents as well. Python types are either really dynamic, or non-existent, depending on how you define them. In particular names have no types at all, unless you want to count the type of the object the name is currently connected to. And if that's what you mean, then names are extremely dynamic, because a name which was bound to a str a minute ago may be currently bound to a file, and may be soon bound to an iterator. As for whether objects of different types can be equal. The answer is yes, if one or both of them define the special methods __eq__() and __ne__(). If neither of those exist, the objects are unequal. But you may be asking instead which standard library types have those special methods, and how do they behave. In that case, I defer to Steven's answer. -- DaveA From alan.gauld at btinternet.com Mon Jun 17 01:39:40 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Jun 2013 00:39:40 +0100 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> Message-ID: On 17/06/13 00:12, Jim Mooney wrote: >> There is also an active community writing third-party plugins for Vim >> and this is probably where the bulk of significant new features are >> developed. > > So as Dr. Frankenstein exclaimed: "It's Alive!" ;') > Vim as a project is very much alive but to be honest I usually advise not using too many of the add-ons because you then get further away from the original vi which is still the standard editor on any modern Unix box. So if you ever have to login to some non vimified box knowing the original commands is very useful. And once you get your head around them they are incredibly efficient and consistent in how they work. I often guess at how things might work in vim and it just works. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at davea.name Mon Jun 17 01:41:59 2013 From: davea at davea.name (Dave Angel) Date: Sun, 16 Jun 2013 19:41:59 -0400 Subject: [Tutor] Getting the real exception clause In-Reply-To: References: Message-ID: <51BE4D47.3080002@davea.name> On 06/16/2013 04:26 PM, Jim Mooney wrote: > '''I'm using general Exception to print out what the exception is > until I learn them, but > it will print out "[Errno 2] No such file or directory" in this case, > when the real > exception I'd need to use in an except clause is FileNotFoundError. > How do I get the > exception I need to use in the except clause from the more English-like message? > ''' > > #Using C:\Python33\python.exe on Win 7 in c:\python33\jimprogs > try: > fh = open('nosuchdirectory/text/truthyfalsey.txt') > for line in fh: > print(line,end='') > fh.close() > except Exception as err: > print(err) > Mark is correct. The best way to print out the exception type and description is to not use try/except, or at least such a base class as Exception. But if you have some other reason to do it your way, then just look at the type of err. print( type(err), err) -- DaveA From cybervigilante at gmail.com Mon Jun 17 02:04:10 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 16 Jun 2013 17:04:10 -0700 Subject: [Tutor] Getting the real exception clause In-Reply-To: <51BE4D47.3080002@davea.name> References: <51BE4D47.3080002@davea.name> Message-ID: On 16 June 2013 16:41, Dave Angel wrote: > But if you have some other reason to do it your way, then just look at the > type of err. > > print( type(err), err) > Yes, that's what I was looking for. It's just a learning tool to see the exceptions without the ugly BUNG! and red traceback screen I get from my IDE, then having to close the message-box so I can see the interpreter again ;') Jim After indictment the bacon smuggler was put on the no-fry list From davea at davea.name Mon Jun 17 02:12:55 2013 From: davea at davea.name (Dave Angel) Date: Sun, 16 Jun 2013 20:12:55 -0400 Subject: [Tutor] Getting the real exception clause In-Reply-To: References: <51BE4D47.3080002@davea.name> Message-ID: <51BE5487.1040904@davea.name> On 06/16/2013 08:04 PM, Jim Mooney wrote: > On 16 June 2013 16:41, Dave Angel wrote: > >> But if you have some other reason to do it your way, then just look at the >> type of err. >> >> print( type(err), err) >> > Yes, that's what I was looking for. It's just a learning tool to see > the exceptions without the ugly BUNG! and red traceback screen I get > from my IDE, then having to close the message-box so I can see the > interpreter again ;') So let me get this straight. Your IDE is busted and ruins the standard error traceback message. So you catch "exception" and try to recreate the feature as it was intended to work. I'd look closer at the IDE and see if it's configurable to remove ugly features. -- DaveA From cybervigilante at gmail.com Mon Jun 17 02:17:50 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 16 Jun 2013 17:17:50 -0700 Subject: [Tutor] Getting the real exception clause In-Reply-To: <51BE5487.1040904@davea.name> References: <51BE4D47.3080002@davea.name> <51BE5487.1040904@davea.name> Message-ID: > I'd look closer at the IDE and see if it's configurable to remove ugly > features. Well, at least the BUNG! which sounds like a spring flew out of my front end. It's a jarring "feature" ;') Jim From breamoreboy at yahoo.co.uk Mon Jun 17 02:29:24 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 17 Jun 2013 01:29:24 +0100 Subject: [Tutor] Getting the real exception clause In-Reply-To: <51BE5487.1040904@davea.name> References: <51BE4D47.3080002@davea.name> <51BE5487.1040904@davea.name> Message-ID: On 17/06/2013 01:12, Dave Angel wrote: > On 06/16/2013 08:04 PM, Jim Mooney wrote: >> On 16 June 2013 16:41, Dave Angel wrote: >> >>> But if you have some other reason to do it your way, then just look >>> at the >>> type of err. >>> >>> print( type(err), err) >>> >> Yes, that's what I was looking for. It's just a learning tool to see >> the exceptions without the ugly BUNG! and red traceback screen I get >> from my IDE, then having to close the message-box so I can see the >> interpreter again ;') > > So let me get this straight. Your IDE is busted and ruins the standard > error traceback message. So you catch "exception" and try to recreate > the feature as it was intended to work. > > I'd look closer at the IDE and see if it's configurable to remove ugly > features. > Since when is code meant to be run from an IDE? For the simple stuff that the OP is doing, why not use any semi-decent text editor and run the code from the command line? Thinking about it, for years I happily used Mark Hammond's excellent pywin32 stuff to do just this. I only moved to Eclipse and Pydev when I had some heayweight porting of Java code to Python, but that would be a massive overkill for the OP. Just my ?0.02p worth. -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From amitsaha.in at gmail.com Mon Jun 17 03:28:42 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Mon, 17 Jun 2013 11:28:42 +1000 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: <51BE65A6.9080604@gmail.com> References: <51BE65A6.9080604@gmail.com> Message-ID: On Mon, Jun 17, 2013 at 11:25 AM, bob gailer wrote: > On 6/15/2013 5:53 AM, Amit Saha wrote: >> >> Symbolic math? > > What is that? Eg: https://gist.github.com/amitsaha/5787802 -- http://echorand.me From bgailer at gmail.com Mon Jun 17 03:25:58 2013 From: bgailer at gmail.com (bob gailer) Date: Sun, 16 Jun 2013 21:25:58 -0400 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: Message-ID: <51BE65A6.9080604@gmail.com> On 6/15/2013 5:53 AM, Amit Saha wrote: > Symbolic math? What is that? -- Bob Gailer 919-636-4239 Chapel Hill NC From steve at pearwood.info Mon Jun 17 04:14:12 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 17 Jun 2013 12:14:12 +1000 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: <51BE65A6.9080604@gmail.com> References: <51BE65A6.9080604@gmail.com> Message-ID: <51BE70F4.1040008@pearwood.info> On 17/06/13 11:25, bob gailer wrote: > On 6/15/2013 5:53 AM, Amit Saha wrote: >> Symbolic math? > What is that? Algebra, calculus and similar. py> import sympy py> x = sympy.Symbol('x') py> ((x + 2)**3).expand() x**3 + 6*x**2 + 12*x + 8 Where possible, it calculates exact mathematical results: py> sympy.sin(3*sympy.pi/4) 2**(1/2)/2 compared to floating point approximations: py> import math py> math.sin(3*math.pi/4) 0.7071067811865476 -- Steven From massimodisasha at gmail.com Mon Jun 17 04:14:38 2013 From: massimodisasha at gmail.com (epi) Date: Sun, 16 Jun 2013 22:14:38 -0400 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: Message-ID: i guess you'll find this pretty interesting : http://nbviewer.ipython.org/url/edu.scios.ch/sympy/nb_sample_sympy.ipynb sympy latex rendering using the ipython notebook ? Have fun ;) Il giorno 15/giu/2013, alle ore 05:53, Amit Saha ha scritto: > Hello Tutors, > > Would any of you have any teaching (or substantial self learning) > experience with a library for Symbolic math? > > I am currently exploring sympy (http://sympy.org) as part of writing a > book chapter and would like to know if there any better/easier option > out there which can successfully introduce symbolic math to young > programmers. > > Thank you for any suggestions in advance. > > Best, > Amit. > > > -- > http://echorand.me > _______________________________________________ > 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 python at outofoptions.net Mon Jun 17 04:19:47 2013 From: python at outofoptions.net (python at outofoptions.net) Date: Sun, 16 Jun 2013 22:19:47 -0400 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: Message-ID: <51BE7243.8080408@outofoptions.net> On 06/16/2013 10:14 PM, epi wrote: > i guess you'll find this pretty interesting : > > http://nbviewer.ipython.org/url/edu.scios.ch/sympy/nb_sample_sympy.ipynb > > sympy latex rendering using the ipython notebook ... > > Have fun ;) Is this intertwined with Sage? I know Sage is mostly python. http://www.sagemath.org/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From amitsaha.in at gmail.com Mon Jun 17 04:23:59 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Mon, 17 Jun 2013 12:23:59 +1000 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: Message-ID: On Mon, Jun 17, 2013 at 12:14 PM, epi wrote: > i guess you'll find this pretty interesting : > > http://nbviewer.ipython.org/url/edu.scios.ch/sympy/nb_sample_sympy.ipynb > > sympy latex rendering using the ipython notebook ? > > Have fun ;) Thanks, I am aware of that. I was asking for any other beginner friendly alternative to SymPy that folks may be aware of. Best, Amit. -- http://echorand.me From amitsaha.in at gmail.com Mon Jun 17 04:49:57 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Mon, 17 Jun 2013 12:49:57 +1000 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: <51BE65A6.9080604@gmail.com> Message-ID: On Mon, Jun 17, 2013 at 12:47 PM, Jim Mooney wrote: > On 16 June 2013 18:28, Amit Saha wrote: >> On Mon, Jun 17, 2013 at 11:25 AM, bob gailer wrote: >>> On 6/15/2013 5:53 AM, Amit Saha wrote: >>>> >>>> Symbolic math? >>> >>> What is that? >> >> Eg: https://gist.github.com/amitsaha/5787802 > > x wasn't defined, and it didn't look like you needed solve(expr,x, > dict=True) the first time > since it's repeated in pprint, so I ditched it. Then it worked nicely. 'x' was defined earlier, I didn't paste it there :-), and Yes I didn't need the first solve. > > That's a nice little package. Just about self-explanatory, and you > don't need a big, honking GUI or TeX. I think I'll keep it. And works > in 3.3. I think I'll keep it ;') yeah, I am playing with the Python 3 version. Works great so far. > > -- > Jim > After indictment the bacon smuggler was put on the no-fry list -- http://echorand.me From cybervigilante at gmail.com Mon Jun 17 04:47:29 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 16 Jun 2013 19:47:29 -0700 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: <51BE65A6.9080604@gmail.com> Message-ID: On 16 June 2013 18:28, Amit Saha wrote: > On Mon, Jun 17, 2013 at 11:25 AM, bob gailer wrote: >> On 6/15/2013 5:53 AM, Amit Saha wrote: >>> >>> Symbolic math? >> >> What is that? > > Eg: https://gist.github.com/amitsaha/5787802 x wasn't defined, and it didn't look like you needed solve(expr,x, dict=True) the first time since it's repeated in pprint, so I ditched it. Then it worked nicely. That's a nice little package. Just about self-explanatory, and you don't need a big, honking GUI or TeX. I think I'll keep it. And works in 3.3. I think I'll keep it ;') -- Jim After indictment the bacon smuggler was put on the no-fry list From cybervigilante at gmail.com Mon Jun 17 05:16:42 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 16 Jun 2013 20:16:42 -0700 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: <51BE65A6.9080604@gmail.com> Message-ID: > yeah, I am playing with the Python 3 version. Works great so far. I didn't even look at the docs, but I think I got the solve part working. I cut down on typing a bit, though. Typing Symbol all day long could get tedious: from sympy import Symbol as S, solve, pprint a,b,c,x = S('a'),S('b'),S('c'),S('x') pprint(solve(a*x*x + b*x + c, x, dict=True)) ## pretty picture here a,b,c = 3,5,6 ## seeing if it solves stuff the way I think y = solve(a*x*x + b*x + c, x, dict=True) print(y) ## result: [{x: -5/6 - sqrt(47)*I/6}, {x: -5/6 + sqrt(47)*I/6}] ## Oops, looks like I accidentally went complex ;') I certainly like a module where you don't have to search and ponder, and it works about like you expect. It seems very straightforward. -- Jim After indictment the bacon smuggler was put on the no-fry list From amitsaha.in at gmail.com Mon Jun 17 05:18:34 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Mon, 17 Jun 2013 13:18:34 +1000 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: <51BE65A6.9080604@gmail.com> Message-ID: On Mon, Jun 17, 2013 at 1:16 PM, Jim Mooney wrote: >> yeah, I am playing with the Python 3 version. Works great so far. > > I didn't even look at the docs, but I think I got the solve part > working. I cut down on typing a bit, though. Typing Symbol all day > long could get tedious: > > from sympy import Symbol as S, solve, pprint > a,b,c,x = S('a'),S('b'),S('c'),S('x') > pprint(solve(a*x*x + b*x + c, x, dict=True)) > > ## pretty picture here > > a,b,c = 3,5,6 ## seeing if it solves stuff the way I think > > y = solve(a*x*x + b*x + c, x, dict=True) > > print(y) > > ## result: [{x: -5/6 - sqrt(47)*I/6}, {x: -5/6 + sqrt(47)*I/6}] > ## Oops, looks like I accidentally went complex ;') > > I certainly like a module where you don't have to search and ponder, > and it works about like you expect. It seems very straightforward. This is a new tutorial the SymPy guys are working on: http://docs.sympy.org/tutorial/tutorial/index.html I certainly found it much more coherent and it clarified a few doubts I was having. -- http://echorand.me From cybervigilante at gmail.com Mon Jun 17 05:25:15 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 16 Jun 2013 20:25:15 -0700 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: <51BE65A6.9080604@gmail.com> Message-ID: On 16 June 2013 20:18, Amit Saha wrote: > > This is a new tutorial the SymPy guys are working on: > http://docs.sympy.org/tutorial/tutorial/index.html Thanks. A lot of math bored me but I see it has matrices, and I really liked linear algebra for some odd reason. I might fool with it again since this package is just basics and not some Huge graphical overkill. Jim From amitsaha.in at gmail.com Mon Jun 17 05:29:15 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Mon, 17 Jun 2013 13:29:15 +1000 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: <51BE65A6.9080604@gmail.com> Message-ID: On Mon, Jun 17, 2013 at 1:25 PM, Jim Mooney wrote: > On 16 June 2013 20:18, Amit Saha wrote: >> >> This is a new tutorial the SymPy guys are working on: >> http://docs.sympy.org/tutorial/tutorial/index.html > > Thanks. A lot of math bored me but I see it has matrices, and I really > liked linear algebra for some odd reason. I might fool with it again > since this package is just basics and not some Huge graphical > overkill. Indeed, it's quite fun. Also, check out https://github.com/sympy/sympy/wiki/Idioms-and-Antipatterns -- http://echorand.me From amitsaha.in at gmail.com Mon Jun 17 05:44:07 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Mon, 17 Jun 2013 13:44:07 +1000 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: <51BE65A6.9080604@gmail.com> Message-ID: On Mon, Jun 17, 2013 at 1:25 PM, Jim Mooney wrote: > On 16 June 2013 20:18, Amit Saha wrote: >> >> This is a new tutorial the SymPy guys are working on: >> http://docs.sympy.org/tutorial/tutorial/index.html > > Thanks. A lot of math bored me but I see it has matrices, and I really > liked linear algebra for some odd reason. I might fool with it again > since this package is just basics and not some Huge graphical > overkill. I agree with that sentiment of "some Huge graphical overkill". -- http://echorand.me From eryksun at gmail.com Mon Jun 17 06:52:50 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 17 Jun 2013 00:52:50 -0400 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> Message-ID: On Sun, Jun 16, 2013 at 4:43 AM, Roel Schroeven wrote: > Jim Mooney schreef: >> I'll get to here: >> >> {'alpha':'beta' >> >> Only my cursor is to the Left of the final quote. Then I have to go >> hunt the Right Arrow or End key In PyScripter you can just type the closing quote/brace over the auto-inserted one. From eryksun at gmail.com Mon Jun 17 07:02:15 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 17 Jun 2013 01:02:15 -0400 Subject: [Tutor] The Whole Tree In-Reply-To: <51BE0F44.5040403@pearwood.info> References: <51BE0F44.5040403@pearwood.info> Message-ID: On Sun, Jun 16, 2013 at 3:17 PM, Steven D'Aprano wrote: > > plus some more exotic built-ins, which I haven't shown. Some types that didn't make it into Steven's list: zip map filter enumerate reversed memoryview slice ellipsis, type(...) super classmethod staticmethod property I wouldn't call 'em exotic. OK, maybe ellipsis. Regarding abstract base classes, once you've gotten the hang of the data model, read the docs for abc and numbers in addition to the already-mentioned collections.abc: http://docs.python.org/3/library/abc http://docs.python.org/3/library/numbers For example, sorted(numbers.Integral.__abstractmethods__) is the list of methods that have to be implemented. Else the interpreter will just complain that it "Can't instantiate abstract class Integral with abstract methods ....". From howewriter2000 at yahoo.com Mon Jun 17 12:00:44 2013 From: howewriter2000 at yahoo.com (jessica peters) Date: Mon, 17 Jun 2013 03:00:44 -0700 (PDT) Subject: [Tutor] sound implementation problems In-Reply-To: <1371216392.71978.YahooMailNeo@web125306.mail.ne1.yahoo.com> References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> <1371207490.21701.YahooMailNeo@web125303.mail.ne1.yahoo.com> <1371211121.97516.YahooMailNeo@web125306.mail.ne1.yahoo.com> <1371216392.71978.YahooMailNeo@web125306.mail.ne1.yahoo.com> Message-ID: <1371463244.21892.YahooMailNeo@web125306.mail.ne1.yahoo.com> Resubmitting this because my list permissions got disabled (not totally sure why), so I've been off it since Friday. ? my website: http://jahowe.com ----- Forwarded Message ----- From: jessica peters To: Francois Dion Sent: Friday, June 14, 2013 9:26 AM Subject: Re: [Tutor] sound implementation problems It comes from?http://www.freestockmusic.com/. ?I should note I was looking for .wav files, because I was having issues getting .mp3 files to read either, and I remembered that the "Hello World" stuff had worked with .wav files. Not sure what you mean by what the comp says about the file itself while it's playing; it opens fine in Windows Media Player, no error messages or anything at all. ? my website: http://jahowe.com ________________________________ From: Francois Dion To: jessica peters Sent: Friday, June 14, 2013 9:15 AM Subject: Re: [Tutor] sound implementation problems In the header of a WAV file are a bunch of identifiers. One is the WAVE data format (32 bit, 16 bit signed, 12 bit u-law, 8 bit, ADPCM etc). For some reason, 0x4x correspond to a format that is not supported by pygame. That's unusual. Is the .wav file you are using somewhere on the net? I could check it out. If you open it in a sound editor, what does it say about the format? On Fri, Jun 14, 2013 at 7:58 AM, jessica peters wrote: That was a good point; I'd forgotten about having to have stuff all in same directory. ?So I moved the files so they'd be there, and now have another error: > > >>>Traceback (most recent call last): >>> ? File "Horsemen_soundtest.py", line 5, in (module) >>> ? ? snd = pygame.mixer.Sound("bach-cello-suite-1.wav") >>>pygame.error: Unknown WAVE data format: 0x4x >>>C:\Documents and settings\jessica howe\Desktop\GAME DESIGN\JA HOWE GAMES\WIP gam >>>es\FOUR HORSEMEN) > > >Ideas why it now says the format of the WAVE file's wrong? ?I'm pretty sure it should be called .wav but don't know what the numbers are for. > > >? >my website: http://jahowe.com > > > >________________________________ > From: Francois Dion >To: jessica peters >Sent: Friday, June 14, 2013 7:31 AM > >Subject: Re: [Tutor] sound implementation problems > > > >On Fri, Jun 14, 2013 at 6:58 AM, jessica peters wrote: > >Thanks for the info. ?My comp will play sound normally, both from online and from the training chapter stuff I did when I was working with "Hello World", so I know it's supposed to work. >> >> >>I tried the suggestion and got this error: >> >> >>>>Traceback (most recent call last): >>>> ? ?File "Horsemen_soundtest.py", line 5, in (module) >>>> ? ? ? snd = pygame.mixer.Sound("bach-cello-suite-1.wav") >>>>pygame.error: Mix_LoadWAV_RW with NULL src >>>>C:\Documents and settings\jessica howe\Desktop\GAME DESIGN\Python\Python study ga >>>>ames\study game files) >> >> >>I'm getting a different error message at least! ?But I'm not sure why this one. ?It looks like the mixer is having difficulty loading. > > >Now we are getting somewhere. Pygame is not finding the .wav file where it's looking. Specify an absolute path. Are the script and .wav files in the same directory? > >? >?Oh yeah, why do I need to put in the get_busy code twice the same way? > > > > >As for the get_busy(), it serves the same purpose as the boolean value you had set up in your initial code you posted (musicPlaying = True). You only need to call it when you want to know if the sound is still playing (it'll return a 1) or it finished (it'll return a 0, and you can cue the next ambiance music). > > > >Francois >-- >www.pyptug.org? -? raspberry-python.blogspot.com? -? @f_dion > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Jun 17 16:00:13 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Jun 2013 15:00:13 +0100 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: <51BE7243.8080408@outofoptions.net> References: <51BE7243.8080408@outofoptions.net> Message-ID: Can you use plain-text instead of html please? I've just had to manually fix the quoting below. On 17 June 2013 03:19, python at outofoptions.net wrote: > On 06/16/2013 10:14 PM, epi wrote: >> >> i guess you'll find this pretty interesting : >> >> http://nbviewer.ipython.org/url/edu.scios.ch/sympy/nb_sample_sympy.ipynb >> >> sympy latex rendering using the ipython notebook ? > > Is this intertwined with Sage? I know Sage is mostly python. > http://www.sagemath.org/ The sage library includes sympy. Essentially sympy is a Python library that can be used from within Python code. It has a number of different interfaces. You can use it programmatically (by importing it in a Python script), in an interactive IPython console (isympy), or graphically via the browser (sympy notebooks). Sage brings together an array of different open-source mathematical libraries in an attempt to create a full graphical environment for mathematical work in the vein of Mathematica or Maple. In other words, sage is more like an application where sympy is more like a library. Oscar From oscar.j.benjamin at gmail.com Mon Jun 17 16:07:42 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Jun 2013 15:07:42 +0100 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: <51BE65A6.9080604@gmail.com> Message-ID: On 17 June 2013 04:16, Jim Mooney wrote: >> yeah, I am playing with the Python 3 version. Works great so far. > > I didn't even look at the docs, but I think I got the solve part > working. I cut down on typing a bit, though. Typing Symbol all day > long could get tedious: > > from sympy import Symbol as S, solve, pprint > a,b,c,x = S('a'),S('b'),S('c'),S('x') Use the symbols convenience function. e.g. (in isympy): In [1]: from sympy import symbols In [2]: a, b, c, x = symbols('a b c x') In [3]: a Out[3]: a In [4]: Force, Mass, Acceleration = symbols('Force Mass Acceleration') In [5]: Force Out[5]: Force In [6]: alpha, beta, gammas = symbols('alpha beta gamma') In [7]: alpha Out[7]: alpha On Linux that last line would show the actual Greek letter ? but this is Windows and sympy knows that I'm using a rubbish console. Oscar From python at outofoptions.net Mon Jun 17 16:17:21 2013 From: python at outofoptions.net (python at outofoptions.net) Date: Mon, 17 Jun 2013 10:17:21 -0400 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: <51BE7243.8080408@outofoptions.net> Message-ID: <51BF1A71.6020402@outofoptions.net> On 06/17/2013 10:00 AM, Oscar Benjamin wrote: > Can you use plain-text instead of html please? I've just had to > manually fix the quoting below. > Sorry. At some point I guess Thunderbird decided HTML should be default and switched all my account settings and made new ones default to HTML. (Or package developers, hard to say. Thanks for the heads up) > Sage brings together an array of different open-source mathematical > libraries in an attempt to create a full graphical environment for > mathematical work in the vein of Mathematica or Maple. In other words, > sage is more like an application where sympy is more like a library. > > Thanks. I've followed/used SAGE on and off (mainly off) over the years. From oscar.j.benjamin at gmail.com Mon Jun 17 17:13:49 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 17 Jun 2013 16:13:49 +0100 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: Message-ID: On 15 June 2013 10:53, Amit Saha wrote: > Would any of you have any teaching (or substantial self learning) > experience with a library for Symbolic math? I have taught using Maple. I haven't with Sympy but I do use it myself. > I am currently exploring sympy (http://sympy.org) as part of writing a > book chapter and would like to know if there any better/easier option > out there which can successfully introduce symbolic math to young > programmers. In terms of free software sympy/sage are probably the best options. I guess that my preference for teaching symbolic computation would be to begin with isympy (sympy mode in the IPython console). I think that this is initially better than the notebook modes of sympy, Maple, etc. because it is clear what is input and what is output and what functions are being called. That way you can gain a sense of the nuts and bolts for how symbolic computation works without getting confused by the "magic" of most of these systems. Later most people would probably find it more practical to use the isympy notebooks or sage for serious work. If you use isympy with the -a flag then missing symbols are automatically created solving the inconvenience that Jim referred to. Also if you have a decent console you can pass '-p unicode' to get all the Greek letters (this is automatic on e.g. Ubuntu but not on Windows): $ isympy -p unicode -a IPython console for SymPy 0.7.2 (Python 2.7.5-32-bit) (ground types: python) These commands were executed: >>> from __future__ import division >>> from sympy import * >>> x, y, z, t = symbols('x y z t') >>> k, m, n = symbols('k m n', integer=True) >>> f, g, h = symbols('f g h', cls=Function) Documentation can be found at http://www.sympy.org In [1]: alpha + kappa Out[1]: ? + ? Unfortunately the auto-symbols feature doesn't work so well when a particular symbol is unexpectedly defined e.g. the beta function: In [2]: alpha + beta --------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () ----> 1 alpha + beta TypeError: unsupported operand type(s) for +: 'Symbol' and 'function' Otherwise I think that sympy has a good feature set. Some examples: Get the general formula for the sum of i**2 with i from 1 to n: In [1]: summation(i**2, (i, 1, n)) Out[1]: 3 2 n n n -- + -- + - 3 2 6 Get the sum of 2^(-i) with i from 0 to infinity: In [3]: summation(2**-i, (i, 0, oo)) Out[3]: 2 Quickly compute the derivative of some hairy function: In [5]: (x ** 2 * exp(x) * (sin(omega*x + phi))).diff(x) Out[5]: 2 x 2 x x omega*x *e *cos(omega*x + phi) + x *e *sin(omega*x + phi) + 2*x*e *sin(omega*x + phi) If you have matplotlib installed then it can quickly plot things for you. Otherwise it falls back to a great ascii poltting library: In [11]: plot(x**2) 100 | | . . | . . | . . | . . | . . | . . | . 50.0165 | --------.--------------------------------------..------ | . . | . . | . . | .. .. | . . | .. .. | .. .. | .. .. 0.03305 | .............. -10 0 10 Out[11]: Plot object containing: [0]: cartesian line: x**2 for x over (-10.0, 10.0) Sympy is good for simple interactive work. It is also suitable for complex problems but some of the interfaces are a little clunky when you start needing to manipulate things programmatically. Here's a non-trivial script that I used to compute the Butcher table for the 4th-order Gauss-Legendre method: #!/usr/bin/env python # # Compute the Butcher table for the Gauss-Legendre 4th order scheme from sympy import * c1, c2, a1, a2, b1, b2, k1, k2, xn, h = symbols('c1 c2 a1 a2 b1 b2 k1 k2 xn h') # Interpolation points # Roots of the Legendre polynomial (transformed) p1 = Rational(1, 2) - Rational(1, 6)*sqrt(3) p2 = Rational(1, 2) + Rational(1, 6)*sqrt(3) # Imagine that we are integrating the differential equation dxdt = x # In that case the solution to the implicit problem for the stages is given by # eq1 and eq2 below. eq1 = h * (xn + a1*k1 +a2*k2) - k1 eq2 = h * (xn + b1*k1 +b2*k2) - k2 # Lets solve the implicit problem to get k1 and k2 in terms of the table # coefficients. soln = solve([eq1, eq2], [k1, k2]) # True solution of the differential equation xnp1 = xn * exp(h) # Estimate that we get from our integration step xnp1bar = (xn + c1*soln[k1] + c2*soln[k2]) # The relative error between the true solution and estimate E = ((xnp1bar - xnp1) / xnp1) # Utility function to extract the terms from the Maclaurin series below # Must be an easier way to do this. def get_terms(expr, var): def prep(expr): expr = expr.subs(a2, p1 - a1).subs(b2, p2 - b1) expr = collect(cancel(expand(expr)), h) return expr results = {} order = -1 while order < 5: coeff, order = expr.leadterm(h) results[var**order] = prep(coeff) expr = cancel(expr - coeff * var ** order) return results # We'll expand the error as a Maclaurin series and try to cancel the first # three terms. Eh = get_terms(series(E, h, n=6), h) # Solve for the values of c, a1 and b1 that cancel the first three terms of # the series expansion. c_sol = solve([Eh[h**2], 1-c1-c2], [c1, c2]) for v in h**3, h**4: Eh[v] = cancel(expand(Eh[v].subs(c1, c_sol[c1]).subs(c2, c_sol[c2]))) (a_sol, b_sol), = solve([Eh[h**3], Eh[h**4]], [a1, b1]) # Construct as a Matrix for pretty-printing table = Matrix([ [p1 , a_sol, p1 - a_sol], [p2 , b_sol, p2 - b_sol], [nan, c_sol[c1], c_sol[c2]], ]) print('Butcher Table for Gauss-Legendre 4th order') pprint(table) The output (after ~5 seconds) is: $ python gl4.py Butcher Table for Gauss-Legendre 4th order [ ___ ___ ] [ \/ 3 1 \/ 3 1] [- ----- + - 1/4 - ----- + -] [ 6 2 6 4] [ ] [ ___ ___ ] [ \/ 3 1 1 \/ 3 ] [ ----- + - - + ----- 1/4 ] [ 6 2 4 6 ] [ ] [ nan 1/2 1/2 ] Compare this with the second table here: http://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_method Oscar From md123 at nycap.rr.com Mon Jun 17 19:36:05 2013 From: md123 at nycap.rr.com (Matt D) Date: Mon, 17 Jun 2013 13:36:05 -0400 Subject: [Tutor] Need help appending data to a logfile Message-ID: <51BF4905.6010801@nycap.rr.com> Hey, I wrote some simple code to write data to a logfile and it works pretty well (thanks guys). Now my problem is that every time i run the program the old logfile.txt is overwritten. I need to be able to stop and start the program without overwriting, or losing, the old data. here is the relavent code: # central part of the program # lays out the GUI panel # omitted lots for our purposes here Class panel(wx.Panel): # open a file named "logfile.txt" in "w" writing mode. # this will create the file if it doesn't exist. self.logfile = open('logfile.txt', 'w') # Updates the TextCtrl field values # and logs TextCtrl field values def update(self, field_values): #logger code--------------- #first write the CURRENT date/time self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", gmtime())))) # loop through each of the TextCtrl objects for k,v in self.fields.items(): #get the value of the current TextCtrl field f = field_values.get(k, None) if f: #output the value with trailing comma self.logfile.write('%s,'%(str(f))) self.logfile.write('\n') #end logger code ---------------- In addition to not deleting the old data, it would be awesome to have some sort of wxPython widget that would give the user the ability to 'save as', or name and save the file, from the GUI panel. Thanks! -- Matt D ------------ From davea at davea.name Mon Jun 17 20:17:25 2013 From: davea at davea.name (Dave Angel) Date: Mon, 17 Jun 2013 14:17:25 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51BF4905.6010801@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> Message-ID: <51BF52B5.1050902@davea.name> On 06/17/2013 01:36 PM, Matt D wrote: > Hey, > I wrote some simple code to write data to a logfile and it works pretty > well (thanks guys). Now my problem is that every time i run the program > the old logfile.txt is overwritten. I need to be able to stop and start > the program without overwriting, or losing, the old data. here is the > relavent code: > > # central part of the program > # lays out the GUI panel > # omitted lots for our purposes here > Class panel(wx.Panel): > > # open a file named "logfile.txt" in "w" writing mode. > # this will create the file if it doesn't exist. > self.logfile = open('logfile.txt', 'w') > > # Updates the TextCtrl field values > # and logs TextCtrl field values > def update(self, field_values): > > #logger code--------------- > #first write the CURRENT date/time > self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", > gmtime())))) > # loop through each of the TextCtrl objects > for k,v in self.fields.items(): > #get the value of the current TextCtrl field > f = field_values.get(k, None) > if f: > #output the value with trailing comma > self.logfile.write('%s,'%(str(f))) > self.logfile.write('\n') > #end logger code ---------------- > > In addition to not deleting the old data, it would be awesome to have > some sort of wxPython widget that would give the user the ability to > 'save as', or name and save the file, from the GUI panel. > Thanks! > Clearly you didn't absorb or act on much of the advice from the last time. So this time I'll just give you a brief hint. Don't use write mode when opening the file. Find the docs on open(), and see what other choices there are. -- DaveA From __peter__ at web.de Mon Jun 17 20:30:20 2013 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Jun 2013 20:30:20 +0200 Subject: [Tutor] Need help appending data to a logfile References: <51BF4905.6010801@nycap.rr.com> Message-ID: Matt D wrote: > Hey, > I wrote some simple code to write data to a logfile and it works pretty > well (thanks guys). Now my problem is that every time i run the program > the old logfile.txt is overwritten. The help() function in the interactive interpreter is a good tool hunt for help on features of functions and classes. For example: >>> help(open) Help on built-in function open in module __builtin__: open(...) open(name[, mode[, buffering]]) -> file object Open a file using the file() type, returns a file object. This is the preferred way to open a file. See file.__doc__ for further information. >>> help(file) Help on class file in module __builtin__: class file(object) | file(name[, mode[, buffering]]) -> file object | | Open a file. The mode can be 'r', 'w' or 'a' for reading (default), | writing or appending. The file will be created if it doesn't exist [...] > I need to be able to stop and start > the program without overwriting, or losing, the old data. here is the > relavent code: > > # central part of the program > # lays out the GUI panel > # omitted lots for our purposes here > Class panel(wx.Panel): > > # open a file named "logfile.txt" in "w" writing mode. > # this will create the file if it doesn't exist. > self.logfile = open('logfile.txt', 'w') > > # Updates the TextCtrl field values > # and logs TextCtrl field values > def update(self, field_values): > > #logger code--------------- > #first write the CURRENT date/time > self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", > gmtime())))) > # loop through each of the TextCtrl objects > for k,v in self.fields.items(): > #get the value of the current TextCtrl field > f = field_values.get(k, None) > if f: > #output the value with trailing comma > self.logfile.write('%s,'%(str(f))) > self.logfile.write('\n') > #end logger code ---------------- > > In addition to not deleting the old data, it would be awesome to have > some sort of wxPython widget that would give the user the ability to > 'save as', or name and save the file, from the GUI panel. This last request is a bit vague, and I'm not a wxPython user myself -- but the wx.FileSelector() function seems like a good start. Unfortunately the documentation I found is for the underlying C++ library: May layman's translation into wxPython: >>> import wx >>> app = wx.App() >>> wx.FileSelector("Save logfile as", flags=wx.FD_SAVE) [snip spurious warnings] u'/foo/bar.baz' # use that result for the actual saving. From cybervigilante at gmail.com Mon Jun 17 21:02:08 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 17 Jun 2013 12:02:08 -0700 Subject: [Tutor] Is there a programmatic use for keys() and values() In-Reply-To: References: <20130615213407.306cc842@Hof> Message-ID: On 16 June 2013 21:52, eryksun wrote: > In PyScripter you can just type the closing quote/brace over the > auto-inserted one. Ah, the light dawns. One of those things I'd never find in the docs for PyScripter, unless I stopped learning Python and read them all - if that's in the docs. Now I can remap CapsLock to something else ;') -- Jim After indictment the bacon smuggler was put on the no-fry list From cybervigilante at gmail.com Mon Jun 17 21:34:05 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 17 Jun 2013 12:34:05 -0700 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: <51BF1A71.6020402@outofoptions.net> References: <51BE7243.8080408@outofoptions.net> <51BF1A71.6020402@outofoptions.net> Message-ID: > Sorry. At some point I guess Thunderbird decided HTML should be default and > switched all my account settings and made new ones default to HTML. This is a peeve of mine with a Lot of programs. Gmail has the new "convenience" of setting your format to the last format used, so I sometimes forget to reset it to text, when I'd like a Default to text. I only want to set rich text on a per-message basis, if I have a picture to include. If a program offers a new "convenience" it should also offer to un-convenience the convenience and simply use a default ;') -- Jim After indictment the bacon smuggler was put on the no-fry list From cybervigilante at gmail.com Mon Jun 17 21:53:14 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 17 Jun 2013 12:53:14 -0700 Subject: [Tutor] The Whole Tree In-Reply-To: References: <51BE0F44.5040403@pearwood.info> Message-ID: On 16 June 2013 22:02, eryksun wrote: > http://docs.python.org/3/library/abc > http://docs.python.org/3/library/numbers Thanks. My left eye burns when I stare at the monitor too long, so I think I'll print out the Data Model and those for bathroom reading. I can be the Potty Progammer ;') Jim From cybervigilante at gmail.com Mon Jun 17 23:17:24 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 17 Jun 2013 14:17:24 -0700 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> Message-ID: On 17 June 2013 11:30, Peter Otten <__peter__ at web.de> wrote: > The help() function in the interactive interpreter is a good tool hunt for > help on features of functions and classes. For example: I tripped on Python help a couple of times, since I'm used to easy-living GUI help, so here is a bit of help on help. From the Python command line it may be help(open), for instance, but only for builtins -- things that don't need dot syntax. For methods, like str.find(), that need dot syntax, it's help(str.find) not help(find); or you can use your own defined string name, such as help(your_big_string.find). Basically, Python help must be fed an object. It's not like a GUI searchable help file. And for a method you don't use the method call, so it's help(str.find) not help(str.find()) I'm embarrassed to say that tripped me up a couple of times, due to habit. For instance, you get help for open but not for close. Since you open with a file handle such as fh = open('yourfile'), you must use fh.close(), since close is a method of fh, and not a builtin. Since python follows your lead and see the object fh, you can get help with help(fh.close) as you named it, but not for help(close). I'm not sure of the generic name Python wants for file, that would work like help(str.find). I'll have to go find that. I tried 'file' but that ain't it. And if you want to be obtuse, just to see that python help Always wants an object, even if you don't see it: import builtins help(builtins.open) works to get the supercalifragilisticexpialidocoius genormous help file for open, which tells you more things about open than you could possibly want to know unless you are really Hardcore ;') But it is not recommended as your primary method. -- Jim After indictment the bacon smuggler was put on the no-fry list From davea at davea.name Mon Jun 17 23:43:27 2013 From: davea at davea.name (Dave Angel) Date: Mon, 17 Jun 2013 17:43:27 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> Message-ID: <51BF82FF.5010207@davea.name> On 06/17/2013 05:17 PM, Jim Mooney wrote: > On 17 June 2013 11:30, Peter Otten <__peter__ at web.de> wrote: > >> The help() function in the interactive interpreter is a good tool hunt for >> help on features of functions and classes. For example: > > I tripped on Python help a couple of times, since I'm used to > easy-living GUI help, so here is a bit of help on help. From the > Python command line it may be help(open), for instance, but only for > builtins -- things that don't need dot syntax. For methods, like > str.find(), that need dot syntax, it's help(str.find) not help(find); > or you can use your own defined string name, such as > help(your_big_string.find). Basically, Python help must be fed an > object. It's not like a GUI searchable help file. > > And for a method you don't use the method call, so it's help(str.find) > not help(str.find()) I'm embarrassed to say that tripped me up a > couple of times, due to habit. You can use the call version, if you want help on the return type. Of course, you want to watch out for side effects; don't do this unless you really want the method to be called. > > For instance, you get help for open but not for close. Since you open > with a file handle such as fh = open('yourfile'), you must use > fh.close(), since close is a method of fh, and not a builtin. Since > python follows your lead and see the object fh, you can get help with > help(fh.close) as you named it, but not for help(close). I'm not sure > of the generic name Python wants for file, that would work like > help(str.find). I'll have to go find that. I tried 'file' but that > ain't it. In Python 2.x help(file.close) In Python 3.x, help(_io.TextIOWrapper.close) or help(sys.stdin.close) But that 3.3 help text isn't right. In 2.x, it starts: Help on method_descriptor: close(...) close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to.... But in 3.3, it says: Help on built-in function close: close(...) with no more explanation. > > And if you want to be obtuse, just to see that python help Always > wants an object, even if you don't see it: > > import builtins > help(builtins.open) works to get the > supercalifragilisticexpialidocoius genormous help file for open, which > tells you more things about open than you could possibly want to know > unless you are really Hardcore ;') > > But it is not recommended as your primary method. > -- DaveA From cybervigilante at gmail.com Tue Jun 18 00:39:05 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 17 Jun 2013 15:39:05 -0700 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51BF82FF.5010207@davea.name> References: <51BF4905.6010801@nycap.rr.com> <51BF82FF.5010207@davea.name> Message-ID: > But in 3.3, it says: > Help on built-in function close: > > close(...) > > with no more explanation. Hmm, I thought close in 3.3 was a method of the file handle, not a builtin function. Have I missed something? I assume all builtin functions do not need an object dot prefix, and close needs the file handle. Nope. close() is not in the built-in function list: http://docs.python.org/3/library/functions.html We've caught them in a boo-boo ;') Jim From breamoreboy at yahoo.co.uk Tue Jun 18 01:04:54 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 18 Jun 2013 00:04:54 +0100 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF82FF.5010207@davea.name> Message-ID: On 17/06/2013 23:39, Jim Mooney wrote: >> But in 3.3, it says: >> Help on built-in function close: >> >> close(...) >> >> with no more explanation. > > Hmm, I thought close in 3.3 was a method of the file handle, not a > builtin function. Have I > missed something? I assume all builtin functions do not need an object > dot prefix, and close needs the file handle. > > Nope. close() is not in the built-in function list: > http://docs.python.org/3/library/functions.html > > We've caught them in a boo-boo ;') > > Jim You now have an opportunity to expand your knowledge of the Python infrastructure by raising your first bug report to get this fixed. I look forward to seeing your effort on the bug tracker mailing list. -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From cybervigilante at gmail.com Tue Jun 18 02:07:25 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 17 Jun 2013 17:07:25 -0700 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF82FF.5010207@davea.name> Message-ID: On 17 June 2013 16:04, Mark Lawrence wrote: > > You now have an opportunity to expand your knowledge of the Python > infrastructure by raising your first bug report to get this fixed. I look > forward to seeing your effort on the bug tracker mailing list. Well, although I would like to see my name in lights, I didn't discover it, Dave did, so that would be dishonest ;') Jim From davea at davea.name Tue Jun 18 02:57:57 2013 From: davea at davea.name (Dave Angel) Date: Mon, 17 Jun 2013 20:57:57 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF82FF.5010207@davea.name> Message-ID: <51BFB095.8040303@davea.name> On 06/17/2013 08:07 PM, Jim Mooney wrote: > On 17 June 2013 16:04, Mark Lawrence wrote: > >> >> You now have an opportunity to expand your knowledge of the Python >> infrastructure by raising your first bug report to get this fixed. I look >> forward to seeing your effort on the bug tracker mailing list. > > Well, although I would like to see my name in lights, I didn't > discover it, Dave did, so that would be dishonest ;') > http://bugs.python.org/issue18249 filed at 8:55 pm -- DaveA From eryksun at gmail.com Tue Jun 18 03:20:23 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 17 Jun 2013 21:20:23 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51BF82FF.5010207@davea.name> References: <51BF4905.6010801@nycap.rr.com> <51BF82FF.5010207@davea.name> Message-ID: On Mon, Jun 17, 2013 at 5:43 PM, Dave Angel wrote: > But in 3.3, it says: > Help on built-in function close: > > close(...) > > with no more explanation. The category "built-in function" here doesn't mean it's in the builtins namespace. It means it's a function or method from an extension module (in this case the _io module). >>> type(sys.stdin.close) >>> inspect.isbuiltin(sys.stdin.close) True As to the docstring, IOBase.close has a docstring: >>> print(io.IOBase.close.__doc__) Flush and close the IO object. This method has no effect if the file is already closed. RawIOBase, BufferedIOBase, and TextIOBase inherit this method. But the close() method for the following concrete implementations is missing a docstring: TextIOWrapper BufferedReader BufferedWriter BufferedRandom BufferedRWPair TextIOWrapper.close calls textiowrapper_close in Modules/_io/textio.c. The Buffered* types use buffered_close in Modules/_io/bufferedio.c. Otherwise the other concrete implementations have docstrings. Raw FileIO: >>> print(io.FileIO.close.__doc__) close() -> None. Close the file. A closed file cannot be used for further I/O operations. close() may be called more than once without error. Changes the fileno to -1. For example: >>> (sys.stdin.buffer.raw.close.__doc__ == ... io.FileIO.close.__doc__) True Raw SocketIO: >>> print(socket.SocketIO.close.__doc__) Close the SocketIO object. This doesn't close the underlying socket, except if all references to it have disappeared. StringIO (in-memory TextIO): >>> print(io.StringIO.close.__doc__) Close the IO object. Attempting any further operation after the object is closed will raise a ValueError. This method has no effect if the file is already closed. BytesIO (in-memory BufferedIO): >>> print(io.BytesIO.close.__doc__) close() -> None. Disable all I/O operations. From cybervigilante at gmail.com Tue Jun 18 04:18:43 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 17 Jun 2013 19:18:43 -0700 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51BFB095.8040303@davea.name> References: <51BF4905.6010801@nycap.rr.com> <51BF82FF.5010207@davea.name> <51BFB095.8040303@davea.name> Message-ID: On 17 June 2013 17:57, Dave Angel wrote: >> Well, although I would like to see my name in lights, I didn't >> discover it, Dave did, so that would be dishonest ;') >> > > http://bugs.python.org/issue18249 > filed at 8:55 pm Looks like you've got a quibble on that. But the point is, it doesn't fulfill the Common definition of a built-in function, and so will confuse most readers, as it did me. As for citing C language, this is Python. You have to stop somewhere. Some of the documentation is cipherable, but some is written by folks who appear to think everyone else is them and knows what they know, in which case why write it at all? It's not written at a consistent level. -- Jim After indictment the bacon smuggler was put on the no-fry list From steve at pearwood.info Tue Jun 18 04:52:37 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 18 Jun 2013 12:52:37 +1000 Subject: [Tutor] Python and Symbolic Math for beginners In-Reply-To: References: Message-ID: <20130618025237.GA5585@ando> On Mon, Jun 17, 2013 at 04:13:49PM +0100, Oscar Benjamin wrote: > On 15 June 2013 10:53, Amit Saha wrote: > > Would any of you have any teaching (or substantial self learning) > > experience with a library for Symbolic math? > > I have taught using Maple. I haven't with Sympy but I do use it myself. [...] Fantastic post, thanks Oscar! -- Steven From fomcl at yahoo.com Tue Jun 18 10:27:32 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 18 Jun 2013 01:27:32 -0700 (PDT) Subject: [Tutor] regex grouping/capturing In-Reply-To: <51BB0B52.6070804@gmail.com> References: <1371136176.25009.YahooMailNeo@web163804.mail.gq1.yahoo.com> <51BA0ABE.9010702@gmail.com> <1371199693.55970.YahooMailNeo@web163802.mail.gq1.yahoo.com> <51BB0B52.6070804@gmail.com> Message-ID: <1371544052.42064.YahooMailNeo@web163804.mail.gq1.yahoo.com> ----- Original Message ----- > From: Andreas Perstinger > To: "tutor at python.org" > Cc: > Sent: Friday, June 14, 2013 2:23 PM > Subject: Re: [Tutor] regex grouping/capturing > > On 14.06.2013 10:48, Albert-Jan Roskam wrote: >> I am trying to create a pygments? regex lexer. > > Well, writing a lexer is a little bit more complex than your original > example suggested. Hi Andreas, sorry for the late reply. It is true that creating a lexer is not that simple. I oversimplified my original example indeed. ? ? > I'm not sure if a single regex can capture this. > But looking at the pygments docs I think you need something along the > lines of (adapt the token names to your need): > > class ExampleLexer(RegexLexer): > ? ? tokens = { > ? ? ? ? 'root': [ > ? ? ? ? ? ? (r'\s+', Text), > ? ? ? ? ? ? (r'set', Keyword), > ? ? ? ? ? ? (r'workspace|header', Name), > ? ? ? ? ? ? (r'\S+', Text), > ? ? ? ? ] > ? ? } > > Does this help? In my original regex example I used groups because I wanted to use pygments.lexer.bygroups (see below) to disentangle commands, subcommands, keywords, values. Finding a command is relatively easy, but the other three elements are not. A command is always preceded by newline and a dot. A subcommand is preceded by a forward slash. A value is *optionally* preceded by an equals sign. A keyword precedes a value. Each command has its own subset of subcommands, keywords, values (e.g. a 'median' keyword is valid only in an 'aggregate' command, not in, say, a 'set' command. I have an xml representation of each of the 1000+ commands. My plan is to parse these and regexify them (one regex per command, all to be stored in a dictionary/shelve). Oh, and if that's not challenging enough: regexes in pygment lexers may not contain nested groups (not sure if that also applies to non-capturing groups). I think I have to get the xml part right first and than see if this can be done. Thanks again Andreas! from pygments.lexer import RegexLexer, bygroups from pygments.token import * class IniLexer(RegexLexer): name = 'INI' aliases = ['ini', 'cfg'] filenames = ['*.ini', '*.cfg'] tokens = { 'root': [ (r'\s+', Text), (r';.*?$', Comment), (r'\[.*?\]$', Keyword), (r'(.*?)(\s*)(=)(\s*)(.*?)$', bygroups(Name.Attribute, Text, Operator, Text, String)) ] } From oscar.j.benjamin at gmail.com Tue Jun 18 12:42:44 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 18 Jun 2013 11:42:44 +0100 Subject: [Tutor] regex grouping/capturing In-Reply-To: <1371544052.42064.YahooMailNeo@web163804.mail.gq1.yahoo.com> References: <1371136176.25009.YahooMailNeo@web163804.mail.gq1.yahoo.com> <51BA0ABE.9010702@gmail.com> <1371199693.55970.YahooMailNeo@web163802.mail.gq1.yahoo.com> <51BB0B52.6070804@gmail.com> <1371544052.42064.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: On 18 June 2013 09:27, Albert-Jan Roskam wrote: > from pygments.lexer import RegexLexer, bygroups from pygments.token import * class IniLexer(RegexLexer): name = 'INI' aliases = ['ini', 'cfg'] filenames = ['*.ini', '*.cfg'] tokens = { 'root': [ (r'\s+', Text), (r';.*?$', Comment), (r'\[.*?\]$', Keyword), (r'(.*?)(\s*)(=)(\s*)(.*?)$', bygroups(Name.Attribute, Text, Operator, Text, String)) ] } I'm not sure how you sent this email but I'm assuming it wasn't supposed to look like it does above. Did you compose/send this as plain-text or html? Oscar From fomcl at yahoo.com Tue Jun 18 12:56:48 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 18 Jun 2013 03:56:48 -0700 (PDT) Subject: [Tutor] regex grouping/capturing In-Reply-To: References: <1371136176.25009.YahooMailNeo@web163804.mail.gq1.yahoo.com> <51BA0ABE.9010702@gmail.com> <1371199693.55970.YahooMailNeo@web163802.mail.gq1.yahoo.com> <51BB0B52.6070804@gmail.com> <1371544052.42064.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: <1371553008.79035.YahooMailNeo@web163801.mail.gq1.yahoo.com> ----- Original Message ----- > From: Oscar Benjamin > To: Tutor at python.org > Cc: > Sent: Tuesday, June 18, 2013 12:42 PM > Subject: Re: [Tutor] regex grouping/capturing > > On 18 June 2013 09:27, Albert-Jan Roskam wrote: >>??from pygments.lexer import RegexLexer, bygroups from pygments.token import > * class IniLexer(RegexLexer): name = 'INI' aliases = ['ini', > 'cfg'] filenames = ['*.ini', '*.cfg'] tokens = { > 'root': [ (r'\s+', Text), (r';.*?$', Comment), > (r'\[.*?\]$', Keyword), > (r'(.*?)(\s*)(=)(\s*)(.*?)$', bygroups(Name.Attribute, Text, > Operator, Text, String)) ] } > > I'm not sure how you sent this email but I'm assuming it wasn't > supposed to look like it does above. Did you compose/send this as > plain-text or html? yikes! Sorry about that. It seems that even in plain-text mode copy-pasted text gets mangled by yahoo. That happens *after* sending the mail. Here is the correctly indented code (website-->notepad-->yahoo): from pygments.lexer import RegexLexer, bygroups from pygments.token import * class IniLexer(RegexLexer): ??? name = 'INI' ??? aliases = ['ini', 'cfg'] ??? filenames = ['*.ini', '*.cfg'] ??? tokens = { ??????? 'root': [ ??????????? (r'\s+', Text), ??????????? (r';.*?$', Comment), ??????????? (r'\[.*?\]$', Keyword), ??????????? (r'(.*?)(\s*)(=)(\s*)(.*?)$', ???????????? bygroups(Name.Attribute, Text, Operator, Text, String)) ??????? ] ??? } From ramit.prasad at jpmorgan.com Tue Jun 18 17:57:39 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 18 Jun 2013 15:57:39 +0000 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51B91F21.7090401@nycap.rr.com> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B28759.60201@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> <51B8E8F9.2030206@nycap.rr.com> <51B8EF53.7030201@davea.name> <51B9165E.3080305@nycap.rr.com> <51B91A42.9030903@davea.name> <51B91F21.7090401@nycap.rr.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474184A145E@SCACMX008.exchad.jpmchase.net> Matt D wrote: > > There are other ways a script might change the current directory. For > > example, some naive scripts use os.chdir() > > > > But how is it you don't know what the current directory was when the > > code ran? A simply pwd can tell you, if your prompt doesn't already > > reveal it. > > > > > hey i found the logfile. just took a few minutes of looking round. the > file is logged all out of order so i have some work to do on that > formatting issue. if you have a sec can you take a look at my code please? > > def update(self, field_values): > > # logger code--------------- > # first write the CURRENT date/time > self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", gmtime())))) > # loop through each of the TextCtrl objects > for k,v in self.fields.items(): > # get the value of the current TextCtrl field > f = field_values.get(k, None) > if f: > #output the value with trailing comma > self.logfile.write('%s,'%(str(f))) > self.logfile.write('\n') > #end logger code ---------------- > > #if the field 'duid' == 'hdu', then clear all the fields > if field_values['duid'] == 'hdu': > self.clear() > #loop through all TextCtrl fields storing the key/value pairs in k, v > for k,v in self.fields.items(): > # get the pickle value for this text control > f = field_values.get(k, None) > # if the value is empty then set the new value > if f: > v.SetValue(f) > > > When i open the .csv file the fields are all out of order. what i want > is have them all in one row beginning with the date/time. and idea? > Thanks! Everything Dave Angel said applies. You can sort the keys by doing and sorting the keys and then logging. That should ensure field order. for k in sorted(self.fields): v = self.fields[k] Also note, that unless you do self.logfile.close() it is not guaranteed that the data is being written to file. I prefer to use the following idiom for Python 2.6+ (might be in 2.5, but not sure offhand when it was added). with open('filename.txt', 'a') as f: # write data ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From md123 at nycap.rr.com Tue Jun 18 18:45:33 2013 From: md123 at nycap.rr.com (Matt D) Date: Tue, 18 Jun 2013 12:45:33 -0400 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474184A145E@SCACMX008.exchad.jpmchase.net> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B28759.60201@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> <51B8E8F9.2030206@nycap.rr.com> <51B8EF53.7030201@davea.name> <51B9165E.3080305@nycap.rr.com> <51B91A42.9030903@davea.name> <51B91F21.7090401@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184A145E@SCACMX008.exchad.jpmchase.net> Message-ID: <51C08EAD.5030507@nycap.rr.com> > Everything Dave Angel said applies. > > You can sort the keys by doing and sorting the keys and then logging. > That should ensure field order. > > for k in sorted(self.fields): > v = self.fields[k] > > > Also note, that unless you do self.logfile.close() it is not guaranteed > that the data is being written to file. I prefer to use the following > idiom for Python 2.6+ (might be in 2.5, but not sure offhand when it was added). > > with open('filename.txt', 'a') as f: > # write data > > Thanks! Now with some experience using this logger i have found that the items, while they may not be in an ideal order, are nonetheless always in the same order starting with date/time. In the interest of getting this thing working ASAP the current ordering is acceptable for now; at some later time I may try to arrange into some other desired order. I am testing the 'a' append mode now. hoping this will allow for not overwriting existing data. Where in the program do I put the: self.logfile.close() Is there someway to trigger this from the UI? or even when the program is stopped? From cybervigilante at gmail.com Wed Jun 19 03:41:01 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 18 Jun 2013 18:41:01 -0700 Subject: [Tutor] unstring Message-ID: Is there a way to unstring something? That is str(object) will give me a string, but what if I want the original object back, for some purpose, without a lot of foofaraw? -- Jim After indictment the bacon smuggler was put on the no-fry list From davea at davea.name Wed Jun 19 04:02:23 2013 From: davea at davea.name (Dave Angel) Date: Tue, 18 Jun 2013 22:02:23 -0400 Subject: [Tutor] unstring In-Reply-To: References: Message-ID: <51C1112F.5040309@davea.name> On 06/18/2013 09:41 PM, Jim Mooney wrote: > Is there a way to unstring something? That is str(object) will give me > a string, but what if I want the original object back, for some > purpose, without a lot of foofaraw? > In general, definitely not. A class can define just about anything in its __str__() method, though it'd be polite for it to return a str. But there's no promise that you can do anything in particular to the str to even recover the type of the original object, never mind the value. For example, in Python 3.3 >>> class Bar: ... def __str__(self): ... return "42" ... >>> x = Bar() >>> str(x) '42' >>> str(42) '42' -- DaveA From marc.tompkins at gmail.com Wed Jun 19 04:06:03 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 18 Jun 2013 19:06:03 -0700 Subject: [Tutor] unstring In-Reply-To: References: Message-ID: On Tue, Jun 18, 2013 at 6:41 PM, Jim Mooney wrote: > Is there a way to unstring something? That is str(object) will give me > a string, but what if I want the original object back, for some > purpose, without a lot of foofaraw? > Unless you're storing them in a dictionary and the string is the key - no... unless the original object is simpler than a string - an int, for example. I believe there's a general law of physics and/or informatics at work here... -------------- next part -------------- An HTML attachment was scrubbed... URL: From zachary.ware+pytut at gmail.com Wed Jun 19 04:06:38 2013 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Tue, 18 Jun 2013 21:06:38 -0500 Subject: [Tutor] unstring In-Reply-To: References: Message-ID: Jim Mooney wrote: >Is there a way to unstring something? That is str(object) will give me >a string, but what if I want the original object back, for some >purpose, without a lot of foofaraw? Only by keeping the original reference to the object. str(object) produces a new object that has absolutely no relation to the original. From steve at pearwood.info Wed Jun 19 04:41:07 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 19 Jun 2013 12:41:07 +1000 Subject: [Tutor] unstring In-Reply-To: References: Message-ID: <20130619024107.GA9709@ando> On Tue, Jun 18, 2013 at 06:41:01PM -0700, Jim Mooney wrote: > Is there a way to unstring something? That is str(object) will give me > a string, but what if I want the original object back, for some > purpose, without a lot of foofaraw? The short answer is, "no". The slightly longer answer is, "sometimes". The accurate answer is, "it depends on what the object is, whether you insist on a human-readable string, and whether or not you like living dangerously". If you know what sort of object the string is supposed to represent, then often (but not always) you can convert it like this: x = 23456 s = str(s) y = int(s) after which, x should equal y. This will work for ints, and will probably work for floats[1]. On the other hand, this does not work for (say) list, tuple or other similar types of object: s = str([None, 42, 'abc']) list(s) returns something very different from what you started with. (Try it and see.) Many objects -- but not all -- have the property that if you call eval() on their repr(), you get the same value back again: s = repr([None, 42, 'abc']) eval(s) ought to return the same list as you started with. But: - this is not guaranteed for all objects; - it's also unsafe. If the string you call eval on comes from an untrusted source, they can do *anything they like* on your computer. Imagine if you are taking a string from somewhere, which you assumed was generated using repr(), but somebody can fool you to accept this string instead: "[None, 42, 'abc'] and __import__('os').system('echo Got You Now, sucker!')" Try eval()'ing the above string. Now imagine something more malicious. So, my advice is, *** don't use eval on untrusted strings *** Another option is to use ast.literal_eval, which is much, much more limited and consequently is safer. py> ast.literal_eval("[None, 42, 'abc']") [None, 42, 'abc'] To summarise, some but not all objects can be round-tripped to and from human-readable strings, like those produced by str() and repr(). Some of them can even be done so safely, without eval(). As an alternative, if you give up the requirement that the string be human-readable, you can *serialise* the object. Not all objects can be serialised, but most can. You can use: - marshal - pickle - json - yaml # not in the standard library - and others but they all have pros and cons. For instance, pickle can handle nearly anything, but it has the same vulnerability as eval(), it can evaluated arbitrary code. json and yaml are pretty close to human-readable, even human-editable, but they can't handle arbitrary objects. py> import pickle py> x = [None, 42, 'abc'] py> pickle.dumps(x) b'\x80\x03]q\x00(NK*X\x03\x00\x00\x00abcq\x01e.' Not exactly human-readable, but guaranteed[2] to round-trip: py> pickle.loads(pickle.dumps(x)) == x True If these are of interest, I suggest starting by reading the docs, then coming back with any questions. [1] I think it will always work, but floats are just tricky enough that I am not willing to promise it. [2] Guarantee void on planet Earth. -- Steven From cybervigilante at gmail.com Wed Jun 19 07:17:17 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 18 Jun 2013 22:17:17 -0700 Subject: [Tutor] unstring In-Reply-To: <20130619024107.GA9709@ando> References: <20130619024107.GA9709@ando> Message-ID: On 18 June 2013 19:41, Steven D'Aprano wrote: > As an alternative, if you give up the requirement that the string be > human-readable, you can *serialise* the object. Not all objects can be > serialised, but most can. You can use: > > - marshal > - pickle I had a feeling it would be nearly impossible unless it involved unpickling instead of unstringing ;') I solved the problem another way. I type dicts on the fly to use as a learning tool, but find it annoying, so I wrote a small snippet/module combo to split a single string of space-separated tokens, then print them as a dictionary, so I could just copy that into my program, and not type all those nasty quotes and colons (I'm the ultimate lazy typist). Only splitting makes all strings, so I wanted the original types back. But then I found the alternate way of defining a dict: D = dict(name='bob', age=50) That doesn't bother me so much - fewer quotes and no colons - so I threw my module to the winds. Still, I'm learning a lot of Python trying to use Python to find lazy ways to do things ;') -- Jim Scorn that fancy food - put bread in your head! From cybervigilante at gmail.com Wed Jun 19 07:26:18 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 18 Jun 2013 22:26:18 -0700 Subject: [Tutor] unstring In-Reply-To: References: Message-ID: > I believe there's a general law of physics and/or informatics at work > here... That sounds right to me - it's some form of perpetual motion ;') And I can see other difficulties. unstring the "5" in x = "5" and that would work, but unstring x = "Bob" and Python thinks Bob is a nonexistent variable name and shouts at you. -- Jim Scorn that fancy food - put bread in your head! From cybervigilante at gmail.com Wed Jun 19 07:34:23 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 18 Jun 2013 22:34:23 -0700 Subject: [Tutor] unstring In-Reply-To: <20130619024107.GA9709@ando> References: <20130619024107.GA9709@ando> Message-ID: On 18 June 2013 19:41, Steven D'Aprano wrote: > On Tue, Jun 18, 2013 at 06:41:01PM -0700, Jim Mooney wrote: >> Is there a way to unstring something? That is str(object) will give me >> a string, but what if I want the original object back, for some >> purpose, without a lot of foofaraw? > > The short answer is, "no". It just occurred to me that a sort key can sort by changing the input to return a string, but the actual list member is not changed to a string, so maybe there's a fudge there. -- Jim Scorn that fancy food - put bread in your head! From steve at pearwood.info Wed Jun 19 07:58:29 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 19 Jun 2013 15:58:29 +1000 Subject: [Tutor] unstring In-Reply-To: References: <20130619024107.GA9709@ando> Message-ID: <20130619055829.GB9709@ando> On Tue, Jun 18, 2013 at 10:34:23PM -0700, Jim Mooney wrote: > On 18 June 2013 19:41, Steven D'Aprano wrote: > > On Tue, Jun 18, 2013 at 06:41:01PM -0700, Jim Mooney wrote: > >> Is there a way to unstring something? That is str(object) will give me > >> a string, but what if I want the original object back, for some > >> purpose, without a lot of foofaraw? > > > > The short answer is, "no". > > It just occurred to me that a sort key can sort by changing the input > to return a string, but the actual list member is not changed to a > string, so maybe there's a fudge there. Nope, sorting with a key function uses the "DSU" (Decorate Sort Undecorate) idiom. Up until a few versions back (2.3 or 2.4, I think), you used to have to do this by hand: # sort numbers in dictionary order, not numeric L = list(range(25)) L = [(str(item), item) for item in L] # decorate L.sort() L = [t[1] for t in L] # undecorate print(L) Python's sort now does this for you: L.sort(key=str) sorted(L, key=str) but the way it's done under the hood is pretty much identical. -- Steven From jacklittlemc at yahoo.com Wed Jun 19 08:50:55 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Tue, 18 Jun 2013 23:50:55 -0700 (PDT) Subject: [Tutor] EXE Problem Message-ID: <1371624655.61616.YahooMailNeo@web124504.mail.ne1.yahoo.com> I compiled a program in python, but the second I open it, there is a flash of the error, but then the cmd window closes. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Wed Jun 19 09:10:38 2013 From: davea at davea.name (Dave Angel) Date: Wed, 19 Jun 2013 03:10:38 -0400 Subject: [Tutor] EXE Problem In-Reply-To: <1371624655.61616.YahooMailNeo@web124504.mail.ne1.yahoo.com> References: <1371624655.61616.YahooMailNeo@web124504.mail.ne1.yahoo.com> Message-ID: <51C1596E.7080106@davea.name> On 06/19/2013 02:50 AM, Jack Little wrote: > I compiled a program in python, but the second I open it, there is a flash of the error, but then the cmd window closes. > It compiles when you run it, so it's not clear what extra step you're describing here. Quite a bit of missing information here, so let's do some guessing. You're running some version of Windows? You're running Python 3.3 ? You're launching what you think is a useful program, directly from Explorer, using double-click, or with right-click-OpenWith ?? Python programs don't have an EXE extension, so perhaps you're not actually double clicking on the right thing. Or perhaps you've neglected to change Windows brain-dead default of NOT showing file extensions in Explorer. When a non-GUI program starts from Explorer, Windows helpfully creates a command window, then helpfully destroys it before you can read the results if any. If you know your program is correct, and you just want to see the output, you'll need to put some form of pause at the end of your program. This could be a sleep(3) if you're a speed reader, or it could be just an input() statement. But if the program is flawed, such as a syntax error, you might never reach the pause. So you might as well get used to the following: Run your program at a cmd prompt, inside a "DOS Box", or "Command Window", or one of several other names used in various Windows versions. It's actually a shell, but Windows doesn't use that term. -- DaveA From howewriter2000 at yahoo.com Wed Jun 19 14:17:55 2013 From: howewriter2000 at yahoo.com (jessica peters) Date: Wed, 19 Jun 2013 05:17:55 -0700 (PDT) Subject: [Tutor] jessica peters Message-ID: <1371644275.92422.YahooMailNeo@web125306.mail.ne1.yahoo.com> http://piranhadvertising.com/yi/eem/lbabm/kfghr/skhnig/uaozl.html jessica peters dtf/div> -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Wed Jun 19 18:41:52 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 19 Jun 2013 09:41:52 -0700 Subject: [Tutor] EXE Problem In-Reply-To: <1371624655.61616.YahooMailNeo@web124504.mail.ne1.yahoo.com> References: <1371624655.61616.YahooMailNeo@web124504.mail.ne1.yahoo.com> Message-ID: On 18 June 2013 23:50, Jack Little wrote: > I compiled a program in python, but the second I open it, there is a flash > of the error, but then the cmd window closes. > I suspicion someone as new to Python, since I am, who is using Windows and getting the annoying Windows Flash ;') So in Detail: Go to the Windows entry box on lower left > type cmd for the DOS box > hit Enter > type python followed by the full path to your program. For instance, I would type: python c:/python33/jimprogs/sympystuff.py and hit Enter to see the printout of a program that illustrates a quadratic equation. Note that after you type python, the input file is to the python interpreter, which Doesn't need those nasty Windows backslashes, so you should use forward slashes. I have no idea why Bill Gates thought backslashes were kewl - maybe he has a really long right little finger. Or he was trying to pretend DOS was a better variant of Unix (hahahahahahahahahaha) Then you should see the result, or your syntax errors. Which you already did if you put pause at the bottom of your program. But this eliminates the need to keep doing that. After you see that, exit() from python back to the DOS box, then simply type python, and you get the interactive python interpreter, where you can fool around with basic python. You also get to see your syntax errors realtime, rather than the annoying DOS Flash. If you're not familiar with DOS, check out basic DOS commands on Google - you may need them. Us old fogeys, and hardcore programmers, know DOS, but I don't assume others do in a GUI-world But putting input() right after your program is easiest. As for sleep, as Dave mentioned, in case you didn't get to module imports, create a simple program like this: import time time.sleep(3) Or if you want to see more than a blank screen and wonder if sleep is working: import time print('time to go to sleep') time.sleep(5) print('darn alarm clock') One can later use IDLE or Wing 101 for more complex programs (google them), but it really is good to know how to use DOS first. And if you're not using Windows, all this typing will be useful to someone else. But Bayesian inference tells me you most likely are ;') Jim Sci-fi novel in one line: Congratulations miss, you have twins - but one is dark matter. From cybervigilante at gmail.com Wed Jun 19 18:44:35 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 19 Jun 2013 09:44:35 -0700 Subject: [Tutor] jessica peters In-Reply-To: <1371644275.92422.YahooMailNeo@web125306.mail.ne1.yahoo.com> References: <1371644275.92422.YahooMailNeo@web125306.mail.ne1.yahoo.com> Message-ID: Just remember - the first three letters in Diet is DIE I'll stick with my cheeseburgers ;') Jim On 19 June 2013 05:17, jessica peters wrote: > http://piranhadvertising.com/yi/eem/lbabm/kfghr/skhnig/uaozl.html > > jessica peters > dtf > /div> From cybervigilante at gmail.com Wed Jun 19 19:43:06 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 19 Jun 2013 10:43:06 -0700 Subject: [Tutor] Opinion - help could use more examples Message-ID: Here's a peeve of mine about Python help - it often has zero examples. I printed help(zip) to see what it does and got this: Return a zip object whose .__next__() method returns a tuple where | the i-th element comes from the i-th iterable argument. The .__next__() | method continues until the shortest iterable in the argument sequence | is exhausted and then it raises StopIteration. Not understandable right off, IMHO, unless you're already hardcore. Okay, I figured it out by running it with some iterables, so I didn't have to google around looking for examples. It would have saved time if there was just one example of what you would get from running next() on a zip or number lists a few times, since it's a simple concept. I'm coming from Jquery, which is chock full of examples, so everyone from bankers to pimps (if there is a difference) can use it. I think the name is confusing zip with compacting, too. Although to be fair. choosing_nth_item_from_parallel_sequences_until_there_is_no_match_on_n() might be too much typing compared to zip() ;') -- Jim Sci-fi novel in one line: Congratulations miss, you have twins - but one is dark matter. From kwpolska at gmail.com Wed Jun 19 20:02:47 2013 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Wed, 19 Jun 2013 20:02:47 +0200 Subject: [Tutor] Opinion - help could use more examples In-Reply-To: References: Message-ID: On Wed, Jun 19, 2013 at 7:43 PM, Jim Mooney wrote: > Here's a peeve of mine about Python help - it often has zero examples. > I printed help(zip) to see what it does and got this: > > Return a zip object whose .__next__() method returns a tuple where > | the i-th element comes from the i-th iterable argument. The .__next__() > | method continues until the shortest iterable in the argument sequence > | is exhausted and then it raises StopIteration. > > Not understandable right off, IMHO, unless you're already hardcore. > Okay, I figured it out by running it with some iterables, so I didn't > have to google around looking for examples. It would have saved time > if there was just one example of what you would get from running > next() on a zip or number lists a few times, since it's a simple > concept. I'm coming from Jquery, which is chock full of examples, so > everyone from bankers to pimps (if there is a difference) can use it. > I think the name is confusing zip with compacting, too. > > Although to be fair. > choosing_nth_item_from_parallel_sequences_until_there_is_no_match_on_n() > might be too much typing compared to zip() ;') A short explanation might be Iterate on arguments, if all return something yield whatever we got, otherwise stop iterating. But anyways, instead of using the built-in docs, refer to the human-friendly documentation available on the web: http://docs.python.org/3/library/functions.html?highlight=zip#zip Downloads for those docs, if you believe this would be more convenient for you, are available at http://docs.python.org/2/download.html and http://docs.python.org/3/download.html (for Python 2 and 3 respectively) -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From cybervigilante at gmail.com Wed Jun 19 20:11:48 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 19 Jun 2013 11:11:48 -0700 Subject: [Tutor] Opinion - help could use more examples In-Reply-To: References: Message-ID: On 19 June 2013 11:02, Chris ?Kwpolska? Warrick wrote: > But anyways, instead of using the built-in docs, refer to the > human-friendly documentation available on the web: > http://docs.python.org/3/library/functions.html?highlight=zip#zip True, but usually built-in is quicker, although I wish I could get rid of all the __garbola__ and get right to the methods ;') As for downloadable help, I have a chm file, and the Search is terrible. It will turn up Everything that has any text with the world 'zip' in it, including Zippy the Clown ;') Using Index is a bit better but still finds garbage you must sift through. So builtin help would be preferable if it were just a bit less concise and had some examples. It's only an opinion. The gods of Python may do otherwise as they choose. Jim > -- Jim Sci-fi novel in one line: Congratulations miss, you have twins - but one is dark matter. From ramit.prasad at jpmorgan.com Wed Jun 19 20:13:51 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 19 Jun 2013 18:13:51 +0000 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474184A819D@SCACMX008.exchad.jpmchase.net> Peter Otten wrote: > Matt D wrote: > > > Hey, > > I wrote some simple code to write data to a logfile and it works pretty > > well (thanks guys). Now my problem is that every time i run the program > > the old logfile.txt is overwritten. > > The help() function in the interactive interpreter is a good tool hunt for > help on features of functions and classes. For example: > > >>> help(open) > Help on built-in function open in module __builtin__: > > open(...) > open(name[, mode[, buffering]]) -> file object > > Open a file using the file() type, returns a file object. This is the > preferred way to open a file. See file.__doc__ for further information. > > >>> help(file) > Help on class file in module __builtin__: > > class file(object) > | file(name[, mode[, buffering]]) -> file object > | > | Open a file. The mode can be 'r', 'w' or 'a' for reading (default), > | writing or appending. The file will be created if it doesn't exist > [...] > > > > I need to be able to stop and start > > the program without overwriting, or losing, the old data. here is the > > relavent code: > > > > # central part of the program > > # lays out the GUI panel > > # omitted lots for our purposes here > > Class panel(wx.Panel): > > > > # open a file named "logfile.txt" in "w" writing mode. > > # this will create the file if it doesn't exist. > > self.logfile = open('logfile.txt', 'w') > > > > # Updates the TextCtrl field values > > # and logs TextCtrl field values > > def update(self, field_values): > > > > #logger code--------------- > > #first write the CURRENT date/time > > self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", > > gmtime())))) > > # loop through each of the TextCtrl objects > > for k,v in self.fields.items(): > > #get the value of the current TextCtrl field > > f = field_values.get(k, None) > > if f: > > #output the value with trailing comma > > self.logfile.write('%s,'%(str(f))) > > self.logfile.write('\n') > > #end logger code ---------------- > > > > In addition to not deleting the old data, it would be awesome to have > > some sort of wxPython widget that would give the user the ability to > > 'save as', or name and save the file, from the GUI panel. > > This last request is a bit vague, and I'm not a wxPython user myself -- but > the wx.FileSelector() function seems like a good start. > > Unfortunately the documentation I found is for the underlying C++ library: > > I think he wanted: http://www.wxpython.org/docs/api/wx.FileDialog-class.html > > May layman's translation into wxPython: > > >>> import wx > >>> app = wx.App() > >>> wx.FileSelector("Save logfile as", flags=wx.FD_SAVE) > [snip spurious warnings] > u'/foo/bar.baz' # use that result for the actual saving. If you want to do this, you need to run the wx.App() line only once per application run. You also need to store all the text that you were writing to file in a list because you cannot write to file and then decide the name later. You must know location first and then write data. Data is not guaranteed to be written until the file is closed as it can stay in-memory until a buffer is full and then gets written to file. Closing a file should flush the buffer contents to file. Dave Angel is correct. Look at the documentation for open() or just store the data in memory and only write when a user selects a save button/menu. ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Wed Jun 19 20:25:53 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 19 Jun 2013 18:25:53 +0000 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <51C08EAD.5030507@nycap.rr.com> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B28759.60201@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> <51B8E8F9.2030206@nycap.rr.com> <51B8EF53.7030201@davea.name> <51B9165E.3080305@nycap.rr.com> <51B91A42.9030903@davea.name> <51B91F21.7090401@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184A145E@SCACMX008.exchad.jpmchase.net> <51C08EAD.5030507@nycap.rr.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474184A8261@SCACMX008.exchad.jpmchase.net> Matt D wrote: > > > > > > Also note, that unless you do self.logfile.close() it is not guaranteed > > that the data is being written to file. I prefer to use the following > > idiom for Python 2.6+ (might be in 2.5, but not sure offhand when it was added). > > > > with open('filename.txt', 'a') as f: > > # write data > > > > > Thanks! > Now with some experience using this logger i have found that the items, > while they may not be in an ideal order, are nonetheless always in the > same order starting with date/time. In the interest of getting this > thing working ASAP the current ordering is acceptable for now; at some > later time I may try to arrange into some other desired order. > > I am testing the 'a' append mode now. hoping this will allow for not > overwriting existing data. > > Where in the program do I put the: > self.logfile.close() > Is there someway to trigger this from the UI? or even when the program > is stopped? A common way to trigger UI actions is a button whose callback calls that. Or you can bind in an event hook for closing the window. in __init__ add this line - self.Bind(wx.EVT_CLOSE, self.onExit) def onExit(self, event): '''Run when closing''' self.logfile.close() self.Destroy() # Continue closing the app otherwise # you will not be able to close it via UI Although, exiting the program will probably close the file for you.... If you are using append mode ('a') you can just do the following which will append and close the file for you. with open(filename, 'a' ) as logfile: logfile.write( data_string ) Make sure you add a newline ('\n') to what you write otherwise all your output will be on one line with no spaces for x in xrange(15): with open( filename, 'a' ) as f: f.write( str(x) ) ========filename================= 01234567891011121314 ================================= ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From kwpolska at gmail.com Wed Jun 19 20:36:47 2013 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Wed, 19 Jun 2013 20:36:47 +0200 Subject: [Tutor] Opinion - help could use more examples In-Reply-To: References: Message-ID: On Wed, Jun 19, 2013 at 8:11 PM, Jim Mooney wrote: > As for downloadable help, I have a chm file, and the Search is terrible. Get the sane html format, where the search is more useful. -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From sunithanc at gmail.com Wed Jun 19 22:03:32 2013 From: sunithanc at gmail.com (SM) Date: Wed, 19 Jun 2013 16:03:32 -0400 Subject: [Tutor] How to redirect console output to a TextEdit box on a QT Python Gui ? In-Reply-To: References: Message-ID: Hello Chris, Thanks for your response. I have a follow-up question, if you don't mind, to understand your answer better. I am running a python3 script. So first part of your answer applies here: *"If the application you run is a Python script, import it, execute the functions and have the data returned (as opposed to printing it), and then you can do self.textEdit.setText(output_* *goes_here)"* My python script prints a lot of text at various stages. There are "print" statements spread across multiple python files. So when you say "have the data returned" and "output_goes_here" as the argument of setText, I am a bit confused as to how I can redirect multiple print statements to the setText call. Can you please clarify? Thanks! Sm On Sun, Jun 16, 2013 at 2:02 PM, Chris ?Kwpolska? Warrick < kwpolska at gmail.com> wrote: > On Sun, Jun 16, 2013 at 7:15 PM, SM wrote: > > Hi > > I have implemented a GUI using PyQt4/python3, which allows the user to > > select a few files as command-line arguments. When I hit "OK" button, my > > application runs and the output text is displayed on the terminal where I > > run the python script. I would like to redirect this text to a TextEdit > > window I have created on the GUI: > > > > self.textEdit = QtGui.QTextEdit(Form) > > self.textEdit.setGeometry(QtCore.QRect(10, 300, 421, 141)) > > self.textEdit.setObjectName(_fromUtf8("textEdit")) > > > > Do you have any suggestions/tips as to how I can accomplish this task? > Using > > some suggestions online, I tried creating a QProcess object and connect > the > > signal to a function which reads the std output. But I don't know how to > > set the arguments to the call "process.start". > > > > self.process = QtCore.QProcess() > > QtCore.QObject.connect(self.process, QtCore.SIGNAL("readyReadStdout()"), > > self.readOutput) > > I know I have to call self.process.start here but am not able to find > > examples of how to do it. One example online uses > > "self.process.setArguments", but python3/pyQt4 doesn't seem to know about > > it. Using the argument directly with process.start is not helping either. > > > > Appreciate any pointers. If there are better ways than what I am trying > to > > use, appreciate that as well. > > If the application you run is a Python script, import it, execute the > functions and have the data returned (as opposed to printing it), and > then you can do self.textEdit.setText(output_goes_here) > > If the application isn?t Python, use the (stock aka vanilla) > subprocess module. The easiest solution is: > > import subprocess > self.textEdit.setText(subprocess.check_output(('command', > 'argument1', 'argument2'))) > > And you do that in the function that is called when you press OK. > > Bonus suggestion: do nice layouts instead of setting the coordinates > manually. The options you want are in the Form menu of Qt Designer. > If you don?t do this, resizing windows is nonsense. > > -- > Kwpolska | GPG KEY: 5EAAEA16 > stop html mail | always bottom-post > http://asciiribbon.org | http://caliburn.nl/topposting.html > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Wed Jun 19 22:44:06 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 19 Jun 2013 20:44:06 +0000 Subject: [Tutor] How to redirect console output to a TextEdit box on a QT Python Gui ? In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474184A9618@SCACMX008.exchad.jpmchase.net> SM wrote: > Hello Chris, Thanks for your response. I have a follow-up question, if you don't mind, to understand > your answer better. > I am running a python3 script. So? first part of your answer applies here: > > "If the application you run is a Python script, import it, execute the > functions and have the data returned (as opposed to printing it), and > then you can do self.textEdit.setText(output_ > goes_here)" > My python script prints a lot of text at various stages. There are "print" statements spread across > multiple python files.? So when you say "have the data returned" and "output_goes_here" as the > argument of setText, I am a bit confused as to how I can redirect multiple print statements to the > setText call. Can you please clarify? > > Thanks! > Sm Usually your logic functions should not print (except for debugging). It should return data which you can then wrap in a UI which prints or displays on GUI. He does not mean to actually redirect output but instead do each "stage" and then print/display the appropriate text *after* the task is done. Instead of trying to redirect output you can try logging to file and having the GUI read that file and print what is appropriate. You can also try to replace stdout with an in-memory buffer which you aggregate and then display after the stage (or at any point) like this (untested). self.oldstdout = sys.stdout sys.stdout = cStringIO.StringIO() # Do processing stages # And later self.textEdit.setText( sys.stdout.getvalue() ) # Replace stdout if needed sys.stdout = self.oldstdout ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From cybervigilante at gmail.com Wed Jun 19 23:01:46 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 19 Jun 2013 14:01:46 -0700 Subject: [Tutor] Opinion - help could use more examples In-Reply-To: References: Message-ID: On 19 June 2013 11:36, Chris ?Kwpolska? Warrick wrote: > > Get the sane html format, where the search is more useful. That was actually "help"ful ;') A lot better organized and you can see things better than the tiny chm left-window font. Msoft sure fell down on chm help. No wonder Google is kicking their butt. I'm big on being able to see things. Programmers preach usability, then I see endless websites that have gone with the new black-is-back style of spidery gray text on a medium gray background that only Superman could see. Arghhh! I'll be so glad when black is out of style except for Goth kids, who do look kinda kewl ;') Jim A pride of lions, a gaggle of geese, a pack of wolves, and a sewer of bankers. From alan.gauld at btinternet.com Thu Jun 20 00:58:28 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Jun 2013 23:58:28 +0100 Subject: [Tutor] EXE Problem In-Reply-To: References: <1371624655.61616.YahooMailNeo@web124504.mail.ne1.yahoo.com> Message-ID: On 19/06/13 17:41, Jim Mooney wrote: > you should use forward slashes. I have no idea why Bill Gates thought > backslashes were kewl Because MS DOS was copying CP/M which didn't have directory paths (it was used with 180K floppy disks that stored everything at the top level) but did have command options that were indicated by a forward slash DIR /S was a sorted directory listing etc. So MS DOS inherited / as an options marker which precluded it's later use as a path separator... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Jun 20 01:08:15 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Jun 2013 00:08:15 +0100 Subject: [Tutor] Opinion - help could use more examples In-Reply-To: References: Message-ID: On 19/06/13 18:43, Jim Mooney wrote: > Here's a peeve of mine about Python help - it often has zero examples. Remember the help text is being generated from the inline doc strings in the code so it depends on what people include in their docstrings. Also it is intended to be concise because you should only be using it at the >>> prompt where you can easily type in your own examples and see how it works. The detailed documentation is (or should be) in the online docs. > concept. I'm coming from Jquery, which is chock full of examples, but JQuery doesn't have an interpreter prompt so you can experiment easily like Python (I think I may have seen someones implementation of a test prompt for JQ but I may be hallucinating!) The Python >>> prompt is not an afterthought, it's been a fundamental part of the Python learning/discovery process since day one. It is similar in that respect to the workspace in Smalltalk where arbitrary bits of code can be evaluated and tested. You are expected to experiment. > I think the name is confusing zip with compacting, too. Not sure what you mean by that. It zips two collections together like a zip fastener. It's got nothing to do with Winzip etc. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Jun 20 01:12:15 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Jun 2013 00:12:15 +0100 Subject: [Tutor] Opinion - help could use more examples In-Reply-To: References: Message-ID: On 19/06/13 22:01, Jim Mooney wrote: > endless websites that have gone with the new black-is-back style of > spidery gray text on a medium gray background that only Superman could > see. I second that, I find an increasing number of web sites unreadable with my ageing eyes because they use shades of the same colour. The contrast is simply too low. And why credit card designers insist on using silver lettering against a white (or light grey) background defeats me - I've been reduced to shining lights at an angle to generate shadows with one of my cards. Let's return to contrasting shades and colours for legibility please... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jeanpierreda at gmail.com Thu Jun 20 02:21:47 2013 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Wed, 19 Jun 2013 20:21:47 -0400 Subject: [Tutor] Opinion - help could use more examples In-Reply-To: References: Message-ID: On Wed, Jun 19, 2013 at 1:43 PM, Jim Mooney wrote: > Here's a peeve of mine about Python help - it often has zero examples. > I printed help(zip) to see what it does and got this: > --snip-- > > Not understandable right off, IMHO, unless you're already hardcore. help() is outright harmful to people that don't already know what they're doing -- it omits things like advice to do with security, including neglecting to declare that functions are not safe and can execute arbitrary Python code, that sort of thing, but also the more common case of just minor security "footnotes" that are nonetheless important for every user to know. Definitely use the HTML docs. -- Devin From cybervigilante at gmail.com Thu Jun 20 02:25:56 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 19 Jun 2013 17:25:56 -0700 Subject: [Tutor] Opinion - help could use more examples In-Reply-To: References: Message-ID: On 19 June 2013 16:12, Alan Gauld wrote: > > I second that, I find an increasing number of web sites unreadable > with my ageing eyes because they use shades of the same colour. > The contrast is simply too low. The strange thing is, every good, recent webmastering book has this big push for Usability, which I would assume includes visibility - but it appears to be totally forgotten in the lust for gray on gray to look kewl ;') Jim From cybervigilante at gmail.com Thu Jun 20 02:36:11 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 19 Jun 2013 17:36:11 -0700 Subject: [Tutor] Opinion - help could use more examples In-Reply-To: References: Message-ID: On 19 June 2013 16:08, Alan Gauld wrote: > Remember the help text is being generated from the inline doc strings in the > code so it depends on what people include in their docstrings. > Also it is intended to be concise because you should only be using it at the >>>> prompt where you can easily type in your own examples and see how it > works. > > The detailed documentation is (or should be) in the online docs. True - I have now installed the real html, which is highly visible and easier, into pyscripter, with hotkeys, and I'll delete that awful chm help with its tiny font. Now I have Full help for 3.3 and 2.7 a hotkey away - I can even see 2.7 and 3.3 help side by side in the browser, to see differences ;') I have a slow and sometimes intermittent connection, so I like things installed. My thought, though, is that since Python is often a first language, have two-tier help - offer a learner help Lhelp(), that omits the __garbola__ and uses the space saved for simple examples. With a proviso on top to go to real help or the docs once you get past the elementary phase. Just a thought. Or encourage docstring writers that an example now and then is Not in bad taste ;') JIm A pride of lions, a gaggle of geese, a pack of wolves, a sewer of bankers. From davea at davea.name Thu Jun 20 04:02:23 2013 From: davea at davea.name (Dave Angel) Date: Wed, 19 Jun 2013 22:02:23 -0400 Subject: [Tutor] EXE Problem In-Reply-To: References: <1371624655.61616.YahooMailNeo@web124504.mail.ne1.yahoo.com> Message-ID: <51C262AF.8050201@davea.name> On 06/19/2013 06:58 PM, Alan Gauld wrote: > On 19/06/13 17:41, Jim Mooney wrote: > >> you should use forward slashes. I have no idea why Bill Gates thought >> backslashes were kewl > > Because MS DOS was copying CP/M which didn't have directory paths > (it was used with 180K floppy disks that stored everything at the top > level) but did have command options that were indicated by a > forward slash > > DIR /S > > was a sorted directory listing etc. > > So MS DOS inherited / as an options marker which precluded > it's later use as a path separator... > > MSDOS 2, which introduced subdirectories, also had a function to change the "switch character". You could change it to "-" for example, and use "/" for a subdirectory delimiter. But most programs (including many of Microsoft's own) ignored the feature, The operating system itself always supported both "/" and "\", but not some utilities like maybe DIR. Also in those days, the head of the MSDOS architecture considered himself in competition with the head of XENIX (Unix) architecture. So he resisted things that might have helped compatibility. -- DaveA From davea at davea.name Thu Jun 20 04:09:49 2013 From: davea at davea.name (Dave Angel) Date: Wed, 19 Jun 2013 22:09:49 -0400 Subject: [Tutor] EXE Problem In-Reply-To: References: <1371624655.61616.YahooMailNeo@web124504.mail.ne1.yahoo.com> Message-ID: <51C2646D.6080701@davea.name> On 06/19/2013 06:58 PM, Alan Gauld wrote: > On 19/06/13 17:41, Jim Mooney wrote: > >> you should use forward slashes. I have no idea why Bill Gates thought >> backslashes were kewl > > Because MS DOS was copying CP/M which didn't have directory paths > (it was used with 180K floppy disks that stored everything at the top > level) but did have command options that were indicated by a > forward slash > > DIR /S > > was a sorted directory listing etc. > This is straining my memory of Windows, but I think /S meant "subdirectory" so a listing will include subdirectories of the specified starting point. The /od switch would sort by date, (I think), and the /P switch would paginate the output (like the earliest primitive forms of 'more'). -- DaveA From steve at pearwood.info Thu Jun 20 04:32:21 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 20 Jun 2013 12:32:21 +1000 Subject: [Tutor] sound implementation problems In-Reply-To: <1371463244.21892.YahooMailNeo@web125306.mail.ne1.yahoo.com> References: <1371144100.7421.YahooMailNeo@web125306.mail.ne1.yahoo.com> <1371207490.21701.YahooMailNeo@web125303.mail.ne1.yahoo.com> <1371211121.97516.YahooMailNeo@web125306.mail.ne1.yahoo.com> <1371216392.71978.YahooMailNeo@web125306.mail.ne1.yahoo.com> <1371463244.21892.YahooMailNeo@web125306.mail.ne1.yahoo.com> Message-ID: <51C269B5.1010906@pearwood.info> Hi Jessica, On 17/06/13 20:00, jessica peters wrote: [snip a bunch of stuff] >>>> Traceback (most recent call last): >>>> File "Horsemen_soundtest.py", line 5, in (module) >>>> snd = pygame.mixer.Sound("bach-cello-suite-1.wav") >>>> pygame.error: Unknown WAVE data format: 0x4x >>>> C:\Documents and settings\jessica howe\Desktop\GAME DESIGN\JA HOWE GAMES\WIP gam >>>> es\FOUR HORSEMEN) Although .wav files are relatively simple, there are slight differences in the internal format. It may be that pygame has restrictions on what sort of WAVs it can play. If you run Linux, you can try calling: file bach-cello-suite-1.wav from the Linux command prompt to get further information about the file, such as whether it is stereo or mono, the bit rate, etc. If you are using Windows, which I see you are, I can do this for you, if you give me a URL where I can download that specific WAV file. You say you downloaded it from http://www.freestockmusic.com/ if you can provide the exact page you got it from, I will grab the file and give you the details. Then you can ask the pygame people if there are restrictions on the types of WAV files it can play. -- Steven From steve at pearwood.info Thu Jun 20 04:38:30 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 20 Jun 2013 12:38:30 +1000 Subject: [Tutor] Opinion - help could use more examples In-Reply-To: References: Message-ID: <51C26B26.1030604@pearwood.info> On 20/06/13 10:21, Devin Jeanpierre wrote: > On Wed, Jun 19, 2013 at 1:43 PM, Jim Mooney wrote: >> Here's a peeve of mine about Python help - it often has zero examples. >> I printed help(zip) to see what it does and got this: >> > --snip-- >> >> Not understandable right off, IMHO, unless you're already hardcore. > > help() is outright harmful to people that don't already know what > they're doing -- it omits things like advice to do with security, > including neglecting to declare that functions are not safe and can > execute arbitrary Python code, *blink* The help documentation is not aimed at people who are such utter beginners to programming that they don't know that calling a function calls the function and therefore executes code. Documentation always assumes *some* background knowledge. Even if you start your documentation with: "The computer is the machine with a screen on your desk. Plug it into the wall socket, turn the power on, then turn the computer on by pushing the On/Off switch." it still assumes that the reader knows what a screen is, a desk, the wall socket, etc. You can't explain *everything*, where would you start? I think it is perfectly acceptable for the Python documentation to assume that anyone reading it will understand that calling a function executes code. -- Steven From md123 at nycap.rr.com Thu Jun 20 05:25:45 2013 From: md123 at nycap.rr.com (Matt D) Date: Wed, 19 Jun 2013 23:25:45 -0400 Subject: [Tutor] Need Help Modifying a wxPython GUI (scrolling display and logging) In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474184A8261@SCACMX008.exchad.jpmchase.net> References: <51ACA1AA.6020500@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418438EB1@SCACMX008.exchad.jpmchase.net> <51AF4716.4050208@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF4741844668D@SCACMX008.exchad.jpmchase.net> <51B28759.60201@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF47418479CBC@SCACMX008.exchad.jpmchase.net> <51B8E8F9.2030206@nycap.rr.com> <51B8EF53.7030201@davea.name> <51B9165E.3080305@nycap.rr.com> <51B91A42.9030903@davea.name> <51B91F21.7090401@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184A145E@SCACMX008.exchad.jpmchase.net> <51C08EAD.5030507@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184A8261@SCACMX008.exchad.jpmchase.net> Message-ID: <51C27639.9060105@nycap.rr.com> > A common way to trigger UI actions is a button whose callback calls that. > Or you can bind in an event hook for closing the window. > > in __init__ add this line - > self.Bind(wx.EVT_CLOSE, self.onExit) > > > def onExit(self, event): > '''Run when closing''' > self.logfile.close() > self.Destroy() # Continue closing the app otherwise > # you will not be able to close it via UI > > > Although, exiting the program will probably close the file for you.... > > > If you are using append mode ('a') you can just do the following > which will append and close the file for you. > with open(filename, 'a' ) as logfile: > logfile.write( data_string ) > > > Make sure you add a newline ('\n') to what you write otherwise all > your output will be on one line with no spaces > > for x in xrange(15): > with open( filename, 'a' ) as f: > f.write( str(x) ) > > ========filename================= > 01234567891011121314 > ================================= > Hey thanks, Currently my data is written like this: 2013-06-19 10:09:53,Unknown,(0x270),Plain,HDU,0x265932377fd55dd000,00x1,Standard MFID (pre-2001),0x666a, 2013-06-19 10:34:43,Unknown,(0x270),Plain,HDU,0xb616ddc0dc3f7d6c00,0xfff,Standard MFID (pre-2001),0x666a, And so on and so on, the new line is only at the end of the '0x666a' in the logfile but here the indentation is forced by my email formatting. so this is good for now. Thanks for the help. But I need to be able to open a text file of choice to write the logfile to. so now i put a button on my panel with the following: btn = wx.Button(self, -1, "Click me") sizer.Add(btn, pos=(7,2)) For some reason i cant not for the life of me figure out how to bind the click event to wxFileDialog. Like if i try: btn.Bind(wx.EVT_BUTTON, self.openfile) I get the AttributeError: object has no attribute 'openfile' Or if i put something like: def openfile(self, event): dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.*", wx.OPEN) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() mypath = os.path.basename(path) self.SetStatusText("You selected: %s" % mypath) dlg.Destroy() or anything like it the whole layout of the panel gets destroyed. I have been looking for examples and readying the http://zetcode.com/wxpython/events/ and reading many others but i am having lots of trouble grasping this. The examples are always in a 'wxFrame' or part of an 'app' so the differences from mine (wxPanel) confuse me. THanks! From alan.gauld at btinternet.com Thu Jun 20 09:01:52 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Jun 2013 08:01:52 +0100 Subject: [Tutor] Opinion - help could use more examples In-Reply-To: <51C26B26.1030604@pearwood.info> References: <51C26B26.1030604@pearwood.info> Message-ID: On 20/06/13 03:38, Steven D'Aprano wrote: > On 20/06/13 10:21, Devin Jeanpierre wrote: >> they're doing -- it omits things like advice to do with security, >> including neglecting to declare that functions are not safe and can >> execute arbitrary Python code, > I think it is perfectly acceptable for the Python documentation to > assume that anyone reading it will understand that calling a function > executes code. I took it that Devin was referring to specific functions such as v2.x input() that execute or evaluate the input parameters as arbitrary code. I don't think he meant the fact that functions in general execute code. eg. Help on input() says: Help on built-in function input in module __builtin__: input(...) input([prompt]) -> value Equivalent to eval(raw_input(prompt)). (END) There is no explicit mention that it is insecure or that it will execute it's input argument as code other than the reference to eval() which a beginner might not understand. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From md123 at nycap.rr.com Thu Jun 20 13:43:30 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 20 Jun 2013 07:43:30 -0400 Subject: [Tutor] Best Code testing practice? Message-ID: <51C2EAE2.9090209@nycap.rr.com> Hey guys! Is there a fast way test some piece of code? I would like to be able to look at the GUI I am making with out changing the file in dir 'baz' and running the actual program (which is quite extensive). Like if I could just have a .py file with only the smallest amount of code possible to make the GUI run, and I could run the .py file from the interpreter to make the GUI run, this would be beautiful. This allow me to easily/quickly experiment with code and test my code. Do we need an IDE for this sort of thing or can we just use the interpreter? OMG i was up till 3am trying to find some way to do this. Thanks! -- Matt D ------------ From alan.gauld at btinternet.com Thu Jun 20 14:52:43 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Jun 2013 13:52:43 +0100 Subject: [Tutor] Best Code testing practice? In-Reply-To: <51C2EAE2.9090209@nycap.rr.com> References: <51C2EAE2.9090209@nycap.rr.com> Message-ID: On 20/06/13 12:43, Matt D wrote: > Is there a fast way test some piece of code? There are several testing frameworks for testing Python code. nose is one example. But... > look at the GUI I am making with out changing the file in dir 'baz' In general your GUI should not be tied into one particular file or folder structure. You should be able to specify that either in a config file that you read when the GUI starts or as command line arguments. That way you can separate your test data from your real production data. > running the actual program (which is quite extensive). Hopefully you have separated the presentation logic (the GUI components) from the processing logic? If so testing the processing logic is fairly easy using one of the aforementioned frameworks. Testing the GUI itself is more tricky and usually requires using some kind of robot to mimic what a user does by sending dummy event messages into the GUI toolkit. > just have a .py file with only the smallest amount of code possible to > make the GUI run, and I could run the .py file from the interpreter to > make the GUI run, this would be beautiful. That depends on how you built the app. If the GUI is encapsulated as an an object then you can usually import the GUI code and instantiate the object. But if you have hard coded links from the GUI event handlers to your processing logic and from there to the real data/files then its going to be difficult. > Do we need an IDE for this sort of thing Almost certainly not, although it may help. You never *need* an IDE for python, they are only there to help. The bottom line is that if your application architecture has been well designed to separate the GUI and processing and you have decoupled the data from the logic then testing should be straightforward. If its all one big organic mashup then you have a tough time ahead. It may be easier to re-architect the application and then test it than to struggle to bolt on tests retrospectively. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From md123 at nycap.rr.com Thu Jun 20 16:32:29 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 20 Jun 2013 10:32:29 -0400 Subject: [Tutor] Best Code testing practice? In-Reply-To: References: <51C2EAE2.9090209@nycap.rr.com> Message-ID: <51C3127D.5060309@nycap.rr.com> On 06/20/2013 08:52 AM, Alan Gauld wrote: > On 20/06/13 12:43, Matt D wrote: > >> Is there a fast way test some piece of code? > > There are several testing frameworks for testing Python code. > nose is one example. > But... > >> look at the GUI I am making with out changing the file in dir 'baz' > > In general your GUI should not be tied into one particular file or > folder structure. You should be able to specify that either in a config > file that you read when the GUI starts or as command line arguments. > > That way you can separate your test data from your real production > data. > >> running the actual program (which is quite extensive). > > Hopefully you have separated the presentation logic (the GUI > components) from the processing logic? If so testing the processing > logic is fairly easy using one of the aforementioned frameworks. Testing > the GUI itself is more tricky and usually requires > using some kind of robot to mimic what a user does by sending > dummy event messages into the GUI toolkit. > >> just have a .py file with only the smallest amount of code possible to >> make the GUI run, and I could run the .py file from the interpreter to >> make the GUI run, this would be beautiful. > > That depends on how you built the app. If the GUI is encapsulated > as an an object then you can usually import the GUI code and instantiate > the object. But if you have hard coded links from the GUI event handlers > to your processing logic and from there to the real data/files then its > going to be difficult. > >> Do we need an IDE for this sort of thing > > Almost certainly not, although it may help. > You never *need* an IDE for python, they are only there to help. > > The bottom line is that if your application architecture > has been well designed to separate the GUI and processing > and you have decoupled the data from the logic then testing > should be straightforward. If its all one big organic mashup > then you have a tough time ahead. It may be easier to > re-architect the application and then test it than to > struggle to bolt on tests retrospectively. > all i really want to do is test the the GUI code. i am working on a 'tab' in a notebook of 7 tabs, which is itself part of a large python program which gets all of its computations done in C++. The code for 'tab', or wxPanel really, i am using is in one file. But i dont need to get into all that at this point. all i want to be able to do is make a small sample app that mimics the one tab i am working on and be able to run it to see if the lay out and dialogs are correct. Thanks! From oscar.j.benjamin at gmail.com Thu Jun 20 16:49:53 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 20 Jun 2013 15:49:53 +0100 Subject: [Tutor] Best Code testing practice? In-Reply-To: <51C3127D.5060309@nycap.rr.com> References: <51C2EAE2.9090209@nycap.rr.com> <51C3127D.5060309@nycap.rr.com> Message-ID: On 20 June 2013 15:32, Matt D wrote: > all i really want to do is test the the GUI code. i am working on a > 'tab' in a notebook of 7 tabs, which is itself part of a large python > program which gets all of its computations done in C++. The code for > 'tab', or wxPanel really, i am using is in one file. > But i dont need to get into all that at this point. all i want to be > able to do is make a small sample app that mimics the one tab i am > working on and be able to run it to see if the lay out and dialogs are > correct. Then make a small app that has just one tab (or has six dummy tabs if necessary). When this app runs it should use the same function from your main application to lay out the widgets but but it shouldn't bind the (same) event handlers. Oscar From md123 at nycap.rr.com Thu Jun 20 17:11:48 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 20 Jun 2013 11:11:48 -0400 Subject: [Tutor] Best Code testing practice? In-Reply-To: References: <51C2EAE2.9090209@nycap.rr.com> <51C3127D.5060309@nycap.rr.com> Message-ID: <51C31BB4.4050005@nycap.rr.com> On 06/20/2013 10:49 AM, Oscar Benjamin wrote: > On 20 June 2013 15:32, Matt D wrote: >> all i really want to do is test the the GUI code. i am working on a >> 'tab' in a notebook of 7 tabs, which is itself part of a large python >> program which gets all of its computations done in C++. The code for >> 'tab', or wxPanel really, i am using is in one file. >> But i dont need to get into all that at this point. all i want to be >> able to do is make a small sample app that mimics the one tab i am >> working on and be able to run it to see if the lay out and dialogs are >> correct. > > Then make a small app that has just one tab (or has six dummy tabs if > necessary). When this app runs it should use the same function from > your main application to lay out the widgets but but it shouldn't bind > the (same) event handlers. > right make a small sample app. exactly. im sorry if im dense or whatever and obviously i am super new to this process. but i can write the scripts in gedit and then what? how do i run that file and make the gui start? should i be doing something like this?: >>> execfile('filename.py') From alan.gauld at btinternet.com Thu Jun 20 18:01:34 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Jun 2013 17:01:34 +0100 Subject: [Tutor] Best Code testing practice? In-Reply-To: <51C31BB4.4050005@nycap.rr.com> References: <51C2EAE2.9090209@nycap.rr.com> <51C3127D.5060309@nycap.rr.com> <51C31BB4.4050005@nycap.rr.com> Message-ID: On 20/06/13 16:11, Matt D wrote: > right make a small sample app. exactly. im sorry if im dense or > whatever and obviously i am super new to this process. but i can write > the scripts in gedit and then what? how do i run that file and make the > gui start? should i be doing something like this?: > >>>> execfile('filename.py') Probably not. You could just run the GUI directly: python guifile.py Then just play with it. If you define the eventhandlers to print messages you can see which method is getting called by each widget etc. But you won;t be using the >>> prompt. If you really want to drive it from the interpreter - maybe to examine status fields etc - then the best thing is to make the GUI a class and then import your file and create an instance of it. You can then send messages to the object to exercise its behaviour. # file testGUI.py class MyGUI def __init__(self): self.buildGUI() def eventHandler_1(self): # do something in response to event1 # maybe print a message or log the GUI data in a file def eventHandler_2(self): # same for event 2 etc... def buildGUI(self): # build your GUI here including your tab. # bind any widgets to use the event handlers defined above Now, in the interpreter: >>> import testGUI >>> app = testGUI.MyGUI() # GUI should appear for you to play with >>> app.eventHandler_1() # test the event handlers independent of GUI >>> print app.myVariable # check a GUI variable value Does that help? PS. Not sure how this will come through. Thunderbird has changed font colour half way through and I can't figure out how to change it back - which makes me suspicious! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Thu Jun 20 18:25:22 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 20 Jun 2013 17:25:22 +0100 Subject: [Tutor] Best Code testing practice? In-Reply-To: <51C2EAE2.9090209@nycap.rr.com> References: <51C2EAE2.9090209@nycap.rr.com> Message-ID: On 20/06/2013 12:43, Matt D wrote: > Hey guys! > Is there a fast way test some piece of code? I would like to be able to > look at the GUI I am making with out changing the file in dir 'baz' and > running the actual program (which is quite extensive). Like if I could > just have a .py file with only the smallest amount of code possible to > make the GUI run, and I could run the .py file from the interpreter to > make the GUI run, this would be beautiful. This allow me to > easily/quickly experiment with code and test my code. Do we need an IDE > for this sort of thing or can we just use the interpreter? OMG i was up > till 3am trying to find some way to do this. > Thanks! > I suspect that you'd get better answers on a GUI specific mailing list, like one for wxPython, but I note that you've already asked pretty much the same question there. -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From bicofino at gmail.com Thu Jun 20 20:29:35 2013 From: bicofino at gmail.com (Danilo Chilene) Date: Thu, 20 Jun 2013 15:29:35 -0300 Subject: [Tutor] Playing with XML Message-ID: Hello, Below is my code: #!/bin/env python # -*- coding: utf-8 -*- import requests from lxml import etree url = 'http://192.168.0.1/webservice.svc?wsdl' headers = {'Content-Type': 'text/xml;charset=UTF-8', 'SOAPAction': ' http://tempuri.org/ITService/SignIn'} xml = ''' 123 123 123 omg ''' response = requests.post(url, data=xml, headers=headers).text print response doc = etree.parse(response) The content of variable response is a big XML with some values that I want. Part of variable response: --------------------------------------------------------------------------------------------------------------------- trueremoveDuplicatedFlightstrueuseWeakPassword --------------------------------------------------------------------------------------------------------------------- Below the return of doc = etree.parse(response) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3630: ordinal not in range(128) The type of response is unicode. The whole idea is sign in on this webservice and get a Security token and then run another XML on the same script. Any ideas to transform this unicode on XML and parse it? Best Regards, Danilo -------------- next part -------------- An HTML attachment was scrubbed... URL: From md123 at nycap.rr.com Thu Jun 20 23:19:33 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 20 Jun 2013 17:19:33 -0400 Subject: [Tutor] Writing logfile data to a user opened file Message-ID: <51C371E5.7060101@nycap.rr.com> Hey guys! So now my UI panel works well with this: # Open file button click event binded to openfile btn = wx.Button(self, -1, "Click me") sizer.Add(btn, pos=(7,2)) btn.Bind(wx.EVT_BUTTON, self.openFile) #set the panel layout self.SetSizer(sizer) #makes the gui system fit all the controls onto the panel7 self.Layout() self.Fit() EVT_DATA_EVENT(self, self.display_data) #self.watcher = traffic_watcher_thread(self.msgq, self) # openfile defined to start FileDialog def openFile(self, evt): with wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.*", wx.OPEN) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() mypath = os.path.basename(path) So as you guys taught me to do I was opening 'logfile' this way: self.logfile = open('logfile.txt', 'a') And the logger code: #logger code--------------- # first new line self.logfile.write('\n') # date and time self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", localtime())))) # loop through each of the TextCtrl objects for k,v in self.fields.items(): # get the value of the current TextCtrl field f = field_values.get(k, None) if f: # output the value with trailing comma self.logfile.write('%s,'%(str(f))) #end logger code ---------------- And that is working well. Now I am trying to think of a way to get what is in the logfile.txt into the file that is opened by the user via the UI. Getting stuck trying to come up with an idea!? maybe something in python like 'user_opened_file = logfile' or 'write logfile to user_opened_file'? I am not able to find standard way to do this. Cheers! -- Matt D ------------ From sunithanc at gmail.com Fri Jun 21 04:59:44 2013 From: sunithanc at gmail.com (SM) Date: Thu, 20 Jun 2013 22:59:44 -0400 Subject: [Tutor] How to redirect console output to a TextEdit box on a QT Python Gui ? In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474184A9618@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF474184A9618@SCACMX008.exchad.jpmchase.net> Message-ID: Thanks, much, Ramit. On Wed, Jun 19, 2013 at 4:44 PM, Prasad, Ramit wrote: > SM wrote: > > Hello Chris, Thanks for your response. I have a follow-up question, if > you don't mind, to understand > > your answer better. > > I am running a python3 script. So first part of your answer applies > here: > > > > "If the application you run is a Python script, import it, execute the > > functions and have the data returned (as opposed to printing it), and > > then you can do self.textEdit.setText(output_ > > goes_here)" > > My python script prints a lot of text at various stages. There are > "print" statements spread across > > multiple python files. So when you say "have the data returned" and > "output_goes_here" as the > > argument of setText, I am a bit confused as to how I can redirect > multiple print statements to the > > setText call. Can you please clarify? > > > > Thanks! > > Sm > > Usually your logic functions should not print (except for debugging). It > should return > data which you can then wrap in a UI which prints or displays on GUI. He > does not mean to > actually redirect output but instead do each "stage" and then > print/display the appropriate > text *after* the task is done. > > Instead of trying to redirect output you can try logging to file and > having the GUI read that file > and print what is appropriate. > > You can also try to replace stdout with an in-memory buffer which you > aggregate and then display after > the stage (or at any point) like this (untested). > > self.oldstdout = sys.stdout > sys.stdout = cStringIO.StringIO() > # Do processing stages > # And later > self.textEdit.setText( sys.stdout.getvalue() ) > # Replace stdout if needed > sys.stdout = self.oldstdout > > > ~Ramit > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From arijit.ukil at tcs.com Fri Jun 21 08:21:30 2013 From: arijit.ukil at tcs.com (Arijit Ukil) Date: Fri, 21 Jun 2013 11:51:30 +0530 Subject: [Tutor] Data persistence problem Message-ID: I have following random number generation function def rand_int (): rand_num = int(math.ceil (random.random()*1000)) return rand_num I like to make the value of rand_num (return of rand_int) static/ unchanged after first call even if it is called multiple times. If x= rand_int () returns 45 at the first call, x should retain 45 even in multiple calls. Pls help. Regards, Arijit Ukil Tata Consultancy Services Mailto: arijit.ukil at tcs.com Website: http://www.tcs.com ____________________________________________ Experience certainty. IT Services Business Solutions Consulting ____________________________________________ =====-----=====-----===== Notice: The information contained in this e-mail message and/or attachments to it may contain confidential or privileged information. If you are not the intended recipient, any dissemination, use, review, distribution, printing or copying of the information contained in this e-mail message and/or attachments to it are strictly prohibited. If you have received this communication in error, please notify us by reply e-mail or telephone and immediately and permanently delete the message and any attachments. Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jun 21 09:06:58 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Jun 2013 08:06:58 +0100 Subject: [Tutor] Data persistence problem In-Reply-To: References: Message-ID: On 21/06/13 07:21, Arijit Ukil wrote: > I have following random number generation function > > def*rand_int* (): > rand_num = int(math.ceil (random.random()*1000)) > returnrand_num > > I like to make the value of rand_num (return of rand_int) static/ > unchanged after first call even if it is called multiple times. The simple solution is to store the value in a global variable. rand_num = None def rand_int(): global rand_num if not rand_num: rand_num = int(math.ceil (random.random()*1000)) return rand_num Or if you really don't like globals you could create a generator function: def rand_int(): rand_num = int(math.ceil (random.random()*1000)) while True: yield rand_num Incidentally, any reason why you don't use the random.randint() function rather than the int(ceil(...) stuff? HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Fri Jun 21 10:48:27 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Jun 2013 10:48:27 +0200 Subject: [Tutor] Playing with XML References: Message-ID: Danilo Chilene wrote: > Hello, > > Below is my code: > > #!/bin/env python > # -*- coding: utf-8 -*- > import requests > from lxml import etree > > url = 'http://192.168.0.1/webservice.svc?wsdl' > headers = {'Content-Type': 'text/xml;charset=UTF-8', 'SOAPAction': ' > http://tempuri.org/ITService/SignIn'} > xml = ''' xmlns:tem="http://tempuri.org/"> > > > > > 123 > 123 > 123 > omg > > > > ''' > > response = requests.post(url, data=xml, headers=headers).text > print response > > doc = etree.parse(response) > > > The content of variable response is a big XML with some values that I > want. > > Part of variable response: > --------------------------------------------------------------------------------------------------------------------- > xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> xmlns="http://tempuri.org/"> xmlns:i="http://www.w3.org/2001/XMLSchema-instance">true xmlns="http://schemas.datacontract.org/2004/07/Framework.BaseEnvelopes" > xmlns:b="http://schemas.datacontract.org/2004/07/Framework"/> xmlns:b="http://schemas.microsoft.com/2003/10/Serialization/Arrays > ">removeDuplicatedFlightstrueuseWeakPassword > --------------------------------------------------------------------------------------------------------------------- > > Below the return of doc = etree.parse(response) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3630: > ordinal not in range(128) > The type of response is unicode. > > > The whole idea is sign in on this webservice and get a Security token and > then run another XML on the same script. > > Any ideas to transform this unicode on XML and parse it? Read carefully: >>> help(lxml.etree.parse) Help on built-in function parse in module lxml.etree: parse(...) parse(source, parser=None, base_url=None) Return an ElementTree object loaded with source elements. If no parser is provided as second argument, the default parser is used. The ``source`` can be any of the following: - a file name/path - a file object - a file-like object - a URL using the HTTP or FTP protocol To parse from a string, use the ``fromstring()`` function instead. Note that it is generally faster to parse from a file path or URL than from an open file object or file-like object. Transparent decompression from gzip compressed sources is supported (unless explicitly disabled in libxml2). The ``base_url`` keyword allows setting a URL for the document when parsing from a file-like object. This is needed when looking up external entities (DTD, XInclude, ...) with relative paths. A quick test confirms that fromstring() accepts unicode: >>> lxml.etree.fromstring(u"???") >>> print _.text ??? If response is a file-like object the following will work, too: #untested response = requests.post(url, data=xml, headers=headers) doc = etree.parse(response) From oscar.j.benjamin at gmail.com Fri Jun 21 11:49:43 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 21 Jun 2013 10:49:43 +0100 Subject: [Tutor] Best Code testing practice? In-Reply-To: <51C31BB4.4050005@nycap.rr.com> References: <51C2EAE2.9090209@nycap.rr.com> <51C3127D.5060309@nycap.rr.com> <51C31BB4.4050005@nycap.rr.com> Message-ID: On 20 June 2013 16:11, Matt D wrote: >> Then make a small app that has just one tab (or has six dummy tabs if >> necessary). When this app runs it should use the same function from >> your main application to lay out the widgets but but it shouldn't bind >> the (same) event handlers. >> > right make a small sample app. exactly. im sorry if im dense or > whatever and obviously i am super new to this process. but i can write > the scripts in gedit and then what? how do i run that file and make the > gui start? should i be doing something like this?: > >>>> execfile('filename.py') You still haven't specified what GUI library you're using or described your code layout so what I'll say below is very generic. In my mind it looks very vaguely like this: # file: myapp.py def layout(tab): tab.add_widget() # blah blah blah if __name__ == "__main__": app = App() frame = Frame(app) tabs = frame.add_tabs(7) layout(tabs[0]) # Add widgets to the tab bindevents(tabs[0]) # blah blah blah show() When you run the above script with 'python myapp.py' is runs like normal. Then you have another script: # file: test_myapp.py from myapp import layout if __name__ == "__main__": app = App() frame = Frame(app) tabs = frame.add_tabs(1) layout(tabs[0]) # Add widgets to the tab # don't bind anything here show() Now when you run 'python test_myapp.py' it opens up the dummy app. The same layout() function is used by the real app and the dummy app so the dummy app gives you a way of checking that it works. Oscar From wolfgang.maier at biologie.uni-freiburg.de Fri Jun 21 12:47:56 2013 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Fri, 21 Jun 2013 10:47:56 +0000 (UTC) Subject: [Tutor] Data persistence problem References: Message-ID: Alan Gauld btinternet.com> writes: > > On 21/06/13 07:21, Arijit Ukil wrote: > > I have following random number generation function > > > > def*rand_int* (): > > rand_num = int(math.ceil (random.random()*1000)) > > returnrand_num > > > > I like to make the value of rand_num (return of rand_int) static/ > > unchanged after first call even if it is called multiple times. > > The simple solution is to store the value in a global variable. > > rand_num = None > > def rand_int(): > global rand_num > if not rand_num: > rand_num = int(math.ceil (random.random()*1000)) > return rand_num > > Or if you really don't like globals you could create > a generator function: > > def rand_int(): > rand_num = int(math.ceil (random.random()*1000)) > while True: > yield rand_num > > Incidentally, any reason why you don't use the random.randint() function > rather than the int(ceil(...) stuff? > > HTH a more general solution for random number generation is to use random.seed() with a fixed argument: def rand_int (seed=None): random.seed(seed) rand_num = int(math.ceil (random.random()*1000)) return rand_num then call this with the same argument to obtain the same number. But as Alan said using random.seed and random.randint is a much simpler choice. Wolfgang From __peter__ at web.de Fri Jun 21 13:10:16 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Jun 2013 13:10:16 +0200 Subject: [Tutor] Data persistence problem References: Message-ID: Alan Gauld wrote: > rand_num = None > > def rand_int(): > global rand_num > if not rand_num: This will not recognize the (unlikely but possible) case that random.random() returns 0.0. So you better check for None explicitly if rand_num is None: > rand_num = int(math.ceil (random.random()*1000)) > return rand_num From davea at davea.name Fri Jun 21 14:24:42 2013 From: davea at davea.name (Dave Angel) Date: Fri, 21 Jun 2013 08:24:42 -0400 Subject: [Tutor] Data persistence problem In-Reply-To: References: Message-ID: <51C4460A.3050105@davea.name> On 06/21/2013 02:21 AM, Arijit Ukil wrote: > I have following random number generation function > > def rand_int (): > rand_num = int(math.ceil (random.random()*1000)) > return rand_num > > I like to make the value of rand_num (return of rand_int) static/ > unchanged after first call even if it is called multiple times. If x= > rand_int () returns 45 at the first call, x should retain 45 even in > multiple calls. > Pls help. > You do realize that this will return the values 1 through 1000 each with a probability of just under 0.1%, and return the value 0 extremely rarely? I'd assume you really meant for it to exclude the value of 0 (or else make it a lot more likely). def rand_int(precalc_value=random.randint(1,1000)): return precalc_value As long as you don't call it with a keyword of precalc_value, it'll retain that initial value each time it's called. And if you wanted the value of zero to also be equally likely (with a probability of 1/1001) def rand_int(precalc_value=random.randint(0,1000)): return precalc_value -- DaveA From kwpolska at gmail.com Fri Jun 21 15:47:58 2013 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Fri, 21 Jun 2013 15:47:58 +0200 Subject: [Tutor] How to redirect console output to a TextEdit box on a QT Python Gui ? In-Reply-To: References: <5B80DD153D7D744689F57F4FB69AF474184A9618@SCACMX008.exchad.jpmchase.net> Message-ID: On Fri, Jun 21, 2013 at 4:59 AM, SM wrote: >> # Replace stdout if needed >> sys.stdout = self.oldstdout It?s better to do it no matter what. Otherwise, hell might break loose. -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From wolfgang.maier at biologie.uni-freiburg.de Fri Jun 21 16:32:21 2013 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Fri, 21 Jun 2013 14:32:21 +0000 (UTC) Subject: [Tutor] Data persistence problem References: Message-ID: Arijit Ukil tcs.com> writes: > > I have following random number generation > function > def > rand_int (): > ? ? rand_num = int(math.ceil > (random.random()*1000)) > ? ? return > rand_num > I like to make the value of rand_num > (return of rand_int) static/ unchanged after first call even if it is called > multiple times. If x= ?rand_int () returns 45 at the first call, x > should retain 45 even in multiple calls. Sifting through the random module documentation a bit: def rand_int(update=False): if update: dummy = random.random() oldstate=random.getstate() rand_num = random.randint(0,1000) random.setstate(oldstate) return rand_num This will return a constant number when called with a False value for update (the default), but will switch to returning a new number when called with a True value once. >>> rand_int() 644 >>> rand_int() 644 >>> rand_int(True) 120 >>> rand_int() 120 >>> rand_int() 120 Best, Wolfgang From ramit.prasad at jpmorgan.com Fri Jun 21 17:52:28 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 21 Jun 2013 15:52:28 +0000 Subject: [Tutor] Writing logfile data to a user opened file In-Reply-To: <51C371E5.7060101@nycap.rr.com> References: <51C371E5.7060101@nycap.rr.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474184C4BBD@SCACMX008.exchad.jpmchase.net> Matt D wrote: > Hey guys! > So now my UI panel works well with this: > > # Open file button click event binded to openfile > btn = wx.Button(self, -1, "Click me") > sizer.Add(btn, pos=(7,2)) > btn.Bind(wx.EVT_BUTTON, self.openFile) > > #set the panel layout > self.SetSizer(sizer) > #makes the gui system fit all the controls onto the panel7 > self.Layout() > self.Fit() > > EVT_DATA_EVENT(self, self.display_data) > #self.watcher = traffic_watcher_thread(self.msgq, self) > > # openfile defined to start FileDialog > def openFile(self, evt): > with wx.FileDialog(self, "Choose a file", os.getcwd(), "", > "*.*", wx.OPEN) as dlg: > if dlg.ShowModal() == wx.ID_OK: > path = dlg.GetPath() > mypath = os.path.basename(path) > > > So as you guys taught me to do I was opening 'logfile' this way: > > self.logfile = open('logfile.txt', 'a') > The point of using append mode is that you can close the file and then re-open it. > And the logger code: > > #logger code--------------- > # first new line > self.logfile.write('\n') > # date and time > self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", localtime())))) > # loop through each of the TextCtrl objects > for k,v in self.fields.items(): > # get the value of the current TextCtrl field > f = field_values.get(k, None) > if f: > # output the value with trailing comma > self.logfile.write('%s,'%(str(f))) > #end logger code ---------------- # first new line with open( filename, 'a' ) as f: #self.logfile.write('\n') # Just add this directly to the end of each line # date and time self.logfile.write('%s,'%( strftime("%Y-%m-%d %H:%M:%S", localtime()))) # loop through each of the TextCtrl objects for k,v in self.fields.items(): # get the value of the current TextCtrl field f = field_values.get(k, None) if f: # output the value with trailing comma self.logfile.write('%s,'%(str(f))) self.logfile.write('\n') # File is now automatically closed Although, I would be tempted to just use the csv module (untested in append mode) and list context. #import csv (at the top of the module) with open( filename, 'ab' ) as f: # open as binary to avoid blank rows writer = csv.writer(f) data = [ str(field_values.get(key)) for key in sorted(self.fields) if field_values.get(key) ] # keep fields in same order # insert date to beginning data.insert(0, strftime("%Y-%m-%d %H:%M:%S", localtime())) writer.writerow(data) # now file is automatically closed > > And that is working well. > Now I am trying to think of a way to get what is in the logfile.txt into > the file that is opened by the user via the UI. Getting stuck trying to > come up with an idea!? maybe something in python like 'user_opened_file > = logfile' or 'write logfile to user_opened_file'? I am not able to > find standard way to do this. > Cheers! > > -- > Matt D > ------------ When you open a file the data should be written to that. If you want to move existing data from logfile.txt into user opened file then you need to read logfile.txt and then write it to the user opened file. To make your life simpler, either pass in the file path or open the file save dialog on __init__. ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From cybervigilante at gmail.com Fri Jun 21 19:44:19 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 21 Jun 2013 10:44:19 -0700 Subject: [Tutor] Data persistence problem In-Reply-To: References: Message-ID: On 21 June 2013 00:06, Alan Gauld wrote: > Or if you really don't like globals you could create > a generator function: Similar problem, by coincidence. Except I need a generator in a function to increment a variable each time the function is called, instead of giving it the same value every time. So far I have a next(gen) as a parameter into the function but that's exactly not what I want - since I need to increment three different numbers that will persist in the function. I tried a few examples I saw but I keep getting the same number, so I'm doing something wrong -- Jim A pride of lions, a gaggle of geese, a pack of wolves, a sewer of bankers. From ramit.prasad at jpmorgan.com Fri Jun 21 20:07:47 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 21 Jun 2013 18:07:47 +0000 Subject: [Tutor] Best Code testing practice? In-Reply-To: <51C2EAE2.9090209@nycap.rr.com> References: <51C2EAE2.9090209@nycap.rr.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474184C5058@SCACMX008.exchad.jpmchase.net> Matt D wrote: > Sent: Thursday, June 20, 2013 6:44 AM > To: tutor at python.org > Subject: [Tutor] Best Code testing practice? > > Hey guys! > Is there a fast way test some piece of code? I would like to be able to > look at the GUI I am making with out changing the file in dir 'baz' and > running the actual program (which is quite extensive). Like if I could > just have a .py file with only the smallest amount of code possible to > make the GUI run, and I could run the .py file from the interpreter to > make the GUI run, this would be beautiful. This allow me to > easily/quickly experiment with code and test my code. Do we need an IDE > for this sort of thing or can we just use the interpreter? OMG i was up > till 3am trying to find some way to do this. > Thanks! > -- > Matt D > ------------ Have you heard of the MVC model? The idea is that you separate the business logic from the "view" or UI. The "controller" contains all the business logic (or work actually being done). Note the below is half pseudo-code just to give you an example. I have neither tested the code nor expect it to actually run. ========================================= # File myapp/ui.py class UI(wx.Frame): def __init__( self, controller, *args, **kwargs ): self.controller = controller super(wx.Frame, self).__init__(*args, **kwargs) def updateData(self): data = self.controller.get_data() self.display_data(data) # File myapp/test.py class TestController(object): def __init__( self, *args, *kwargs ): #accept same options of real controller pass # Don't need real data def get_date(self): ''' return hard coded test data or generate test data''' return [ 1,2,34,4,5 ] if __name__ == "__main__": app = wx.App() # or whatever the setup for wx should be. from myapp.ui import UI UI(TestController()) # file myapp/main.py from myapp.ui import UI from myapp.controller import Controller if __name__ == "__main__": # setup wx f = UI(Controller()) f.Fit() # or Show() or whatever ========================================= python myapp/test.py python myapp/main.py Now you can test your changes to business logic and your user interface separately. You can even look into automated testing. ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From md123 at nycap.rr.com Fri Jun 21 20:17:40 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 21 Jun 2013 14:17:40 -0400 Subject: [Tutor] Best Code testing practice? In-Reply-To: References: <51C2EAE2.9090209@nycap.rr.com> Message-ID: <51C498C4.10507@nycap.rr.com> > > I suspect that you'd get better answers on a GUI specific mailing list, > like one for wxPython, but I note that you've already asked pretty much > the same question there. > Hey guys! Have decided that it is probably going to be better for my purposes to simply crack open a terminal, cd into the appropriate directory, and do the 'python test_code.py' or whatever the file name is from the command line. I feel it is better for me to learn how to write code in gedit before i use an IDE. Thanks guys! From md123 at nycap.rr.com Fri Jun 21 21:12:55 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 21 Jun 2013 15:12:55 -0400 Subject: [Tutor] Writing logfile data to a user opened file In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474184C4BBD@SCACMX008.exchad.jpmchase.net> References: <51C371E5.7060101@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184C4BBD@SCACMX008.exchad.jpmchase.net> Message-ID: <51C4A5B7.4030209@nycap.rr.com> > > When you open a file the data should be written to that. If you want to > move existing data from logfile.txt into user opened file then you need > to read logfile.txt and then write it to the user opened file. To make > your life simpler, either pass in the file path or open the file save > dialog on __init__. > > > ~Ramit > I got so frustrated try to figure a way to use the logfile.txt that I changed how i log. first i name an array: class TrafficPane(wx.Panel): # Initializer # the class constructor def __init__(self, parent, msgq): wx.Panel.__init__(self, parent) self.msgq = msgq #create the array to put the traffic data in self.log_array = [] Then this is how the array gets into the file the user chooses: # openfile defined to start FileDialog def openFile(self, evt): with wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.txt*", wx.OPEN) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() #mypath = os.path.basename(path) mypath = os.path.abspath(path) f = open(mypath, "rw+") f.writelines(self.log_array) And this is how i get the TextCtrl values into the array: def update(self, field_values): next_line = "" #logger code--------------- # first new line #self.logfile.write('\n') # date and time #self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", localtime())))) next_line += (str(strftime("%Y-%m-%d %H:%M:%S", localtime()))) # loop through each of the TextCtrl objects for k,v in self.fields.items(): # get the value of the current TextCtrl field f = field_values.get(k, None) if f: # output the value with trailing comma #self.logfile.write('%s,'%(str(f))) next_line += (str(f) + ',') log_array.append(next_line) #end logger code---------- Its running right now. I haven't had the opportunity to test if it works so im keeping my fingers crossed. From ramit.prasad at jpmorgan.com Fri Jun 21 22:44:23 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 21 Jun 2013 20:44:23 +0000 Subject: [Tutor] Writing logfile data to a user opened file In-Reply-To: <51C4A5B7.4030209@nycap.rr.com> References: <51C371E5.7060101@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184C4BBD@SCACMX008.exchad.jpmchase.net> <51C4A5B7.4030209@nycap.rr.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474184C54E8@SCACMX008.exchad.jpmchase.net> Matt D wrote: > [Ramit P wrote:] > > When you open a file the data should be written to that. If you want to > > move existing data from logfile.txt into user opened file then you need > > to read logfile.txt and then write it to the user opened file. To make > > your life simpler, either pass in the file path or open the file save > > dialog on __init__. > > > > > > ~Ramit > > > I got so frustrated try to figure a way to use the logfile.txt that I > changed how i log. first i name an array: > > class TrafficPane(wx.Panel): > # Initializer > # the class constructor > def __init__(self, parent, msgq): > wx.Panel.__init__(self, parent) > self.msgq = msgq > #create the array to put the traffic data in > self.log_array = [] > > Then this is how the array gets into the file the user chooses: > > # openfile defined to start FileDialog > def openFile(self, evt): > with wx.FileDialog(self, "Choose a file", os.getcwd(), "", > "*.txt*", wx.OPEN) as dlg: > if dlg.ShowModal() == wx.ID_OK: > path = dlg.GetPath() > #mypath = os.path.basename(path) > mypath = os.path.abspath(path) > f = open(mypath, "rw+") Why are you opening the file in "rw+"? > f.writelines(self.log_array) You should really switch to the "with open() as f:" idiom I keep showing you. This will automatically close the file for you. Also note that your file is only getting written once. You should probably clear log_array and change the file mode back to append. > > And this is how i get the TextCtrl values into the array: > > def update(self, field_values): > next_line = "" > #logger code--------------- > # first new line > #self.logfile.write('\n') > # date and time > #self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", > localtime())))) > next_line += (str(strftime("%Y-%m-%d %H:%M:%S", localtime()))) > # loop through each of the TextCtrl objects > for k,v in self.fields.items(): > # get the value of the current TextCtrl field > f = field_values.get(k, None) > if f: > # output the value with trailing comma > #self.logfile.write('%s,'%(str(f))) > next_line += (str(f) + ',') > log_array.append(next_line) > #end logger code---------- > > Its running right now. I haven't had the opportunity to test if it > works so im keeping my fingers crossed. This is an inefficient string concatenation. It can take large amounts of memory and time. next_line += (str(f) + ',') You can use str.join or use the csv module (which I recommend as it will escape the delimeter (eg. commas ) if it shows up in the data ). I have sent an example of the csv module already. Also note that your order of the dictionary is not guaranteed so your data may end up out of order after each run. 'hi', 1 , 5423 4255, 'hi', 2 # instead of 1, 'hi', 5423 2, 'hi', 4255 # A str.join example next_line = [] for key in sorted( self.fields ): f = field_values.get(k, None) if f: next_line.append(str(f)) line = ', '.join(next_line) log_array.append(line) ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Fri Jun 21 23:59:07 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 21 Jun 2013 22:59:07 +0100 (BST) Subject: [Tutor] Data persistence problem In-Reply-To: References: Message-ID: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> > ... I need to increment three different numbers that will > persist in the function. I tried a few examples I saw but I keep > getting the same number, so I'm doing something wrong Give us a clue, show us your code! ? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jun 22 00:34:05 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Jun 2013 23:34:05 +0100 Subject: [Tutor] Best Code testing practice? In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474184C5058@SCACMX008.exchad.jpmchase.net> References: <51C2EAE2.9090209@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184C5058@SCACMX008.exchad.jpmchase.net> Message-ID: On 21/06/13 19:07, Prasad, Ramit wrote: > Have you heard of the MVC model? The idea is that you separate the > business logic from the "view" or UI. The "controller" contains > all the business logic (or work actually being done). Being slightly picky but the business logic should sit mainly in the Models. (ie the rules around how the data is manipulated, the algorithms etc) It's the scenario flow (or worklflow) that should sit in the controller. ie The controller sequences the scenario or use case by orchestrating the actions of the Models which in turn reflect their state changes in their associated views (GUI screens/panels). In the original (Smalltalk) MVC pattern the Controller manages user input but in later variants this is often a function of the Views which then delegate to the associated controller. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cybervigilante at gmail.com Sat Jun 22 01:00:43 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 21 Jun 2013 16:00:43 -0700 Subject: [Tutor] Data persistence problem In-Reply-To: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: On 21 June 2013 14:59, ALAN GAULD wrote: > > Give us a clue, show us your code! I was hoping you wouldn't say that since it's another of my insane Lazy Typer programs to avoid typing, which are no doubt considered frivolous. Although I'm learning a lot doing them ;') Okay, I have a snippet that posts the below text in automatically. I can use it to make any number of dicts, lists, or sets, from just tokens in a single string, and they are printed out as the different types, named and and numbered so they have different program names. That way I don't have to type in quotes, commas, colons, and so forth. Once the interpreter prints them out, I just select all and paste them into my program, replacing what's below. Kind of a manual meta-programming ;') ============= pasted in snippet ================ ## Output sequence will be all strings. The first type in the 2nd parameter list will be the ## default due to 'or" short circuiting, so you can just delete to get what you want. ## You MUST have an even number of tokens for a dict or you'll get an exception. from maker import makeseq makeseq("Replace me, even number of tokens for dict", dict or list or set) ============= end snippet ==================== >From this I can create any number of numbered dicts, lists or sets (The 'or' short circuit means I get dicts as default, and only have to delete from the front to get the others - dicts are default since they're the most annoying to type - now That's lazy.) For instance if I type this in after the import above: makeseq("this better be an even number of tokens", dict or list or set) makeseq("bacon pigs lies politicians foreclosures bankers cheeseburgers good", dict or list or set) makeseq("this is a list and it is not a very big list", list or set) makeseq("Yet another list to show the different types increment seperately", list or set) makeseq("and finally some sets", set) makeseq("sets can be be be be be very very useful to eliminate duplicates duplicates", set) makeseq("But this time I'm just counting set incidence up to three", set) I get this in the interpreter: D1 = {'Replace': 'me,', 'for': 'dict', 'of': 'tokens', 'even': 'number'} D2 = {'even': 'number', 'of': 'tokens', 'be': 'an', 'this': 'better'} D3 = {'cheeseburgers': 'good', 'bacon': 'pigs', 'lies': 'politicians', 'foreclosures': 'bankers'} L1 = ['this', 'is', 'a', 'list', 'and', 'it', 'is', 'not', 'a', 'very', 'big', 'list'] L2 = ['Yet', 'another', 'list', 'to', 'show', 'the', 'different', 'types', 'increment', 'seperately'] S1 = {'sets', 'some', 'finally', 'and'} S2 = {'eliminate', 'to', 'very', 'can', 'be', 'sets', 'duplicates', 'useful'} S3 = {'just', 'to', 'time', 'incidence', 'set', 'this', "I'm", 'But', 'up', 'counting', 'three'} Come to think of it I should rename makeseq since only the list is a sequence. Then I just paste all that in to replace the original routine. Since I'm learning, I just like to have objects I can practice on without a lot of typing difficult characters. Below is the module, maker.py, that I import. As you can see I'm using globals to increment the numbering for dicts, lists, and sets, separately. This only creates strings at present, but I realized I can get around that and "unstring" once I learn regular expressions. Since I'm going "outside" the program to a higher level, and copying back into it, I can break some informatic rules. It's the way you could write a Java program with python, then run it, doing unPythonic things. That's my tentative theory, anyway. (Although using Python to write Java is like using a Faberge egg to pound nails, IMHO ;') ================== begin maker.py module ======================== '''Accept a space-separated string of tokens that are each contiguous characters. The second parameter will turn them into a dict, list, or set. Dicts must have an even number of tokens. More than one of each type will be sequentially numbered so they can be differentiated, such as D1, D2, L1, L2, L3. S1, S2, etc. All sequences will be printed out to be copied from the interpreter for programmatic use.''' dictnumfarkadoodle = listnumfarkadoodle = setnumfarkadoodle = 0 # Since these are global I'm using words not likely to be duplicated until I figure a different way and # replace 'farkadoodle' with '' ;') def makeseq(instring, typein): global dictnumfarkadoodle, listnumfarkadoodle, setnumfarkadoodle if isinstance(dict(), typein): newdict = {} dl = instring.split() if len(dl) % 2 != 0: raise Exception ("list entries must be even") # so they match for idx in range(0,len(dl),2): newdict[dl[idx]] = dl[idx+1] dictnumfarkadoodle += 1 print('D' + str(dictnumfarkadoodle) + ' =', newdict) elif isinstance(list(), typein): newlist = [] dl = instring.split() for word in dl: newlist.append(word) listnumfarkadoodle += 1 print('L' + str(listnumfarkadoodle) + ' =', newlist) elif isinstance(set(), typein): newset = set() dl = instring.split() for word in dl: newset.add(word) setnumfarkadoodle += 1 print('S' + str(setnumfarkadoodle) + ' =', newset) else: print('Second parameter must be list, set, or dict') # oops, I error out on a non-type 2nd parameter. Fix this later ============== end module ==================== A pride of lions, a gaggle of geese, a pack of wolves, a sewer of bankers. From alan.gauld at btinternet.com Sat Jun 22 01:56:53 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 22 Jun 2013 00:56:53 +0100 (BST) Subject: [Tutor] Data persistence problem In-Reply-To: References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: <1371859013.59304.YahooMailNeo@web186004.mail.ir2.yahoo.com> ?Just a wee thought: ? ? if isinstance(dict(), typein): >? ? ? ? newdict = {} >? ? ? ? dl = instring.split() >? ? ? ? if len(dl) % 2 != 0: raise Exception ("list entries must be >even") # so they match >? ? ? ? for idx in range(0,len(dl),2): >? ? ? ? ? ? newdict[dl[idx]] = dl[idx+1] >The for loop can be replaced with: newdict =?dict(zip(L[::2],L[1::2])) Which avoids the explicit arithmetic and indexing and is therefore, arguably,? cleaner... I'd probably wrap it in a try clause too: if isinstance(dict(),typein): ? ?try:?newdict =?dict(zip(dl[::2],dl[1::2])) ? ?except TypeError: ? ? raise ValueError("input lists must be an even length") And, since you always split the input, move that above all the isinstance() tests... Similarly you don't need the loops for lists or sets, just use: newlist = dl and? newset = set(dl) But that doesn't answer your question about incrementing the globals! :-) To me it looks from your sample data ?like it is working! Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From md123 at nycap.rr.com Sat Jun 22 02:46:19 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 21 Jun 2013 20:46:19 -0400 Subject: [Tutor] Writing logfile data to a user opened file In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474184C54E8@SCACMX008.exchad.jpmchase.net> References: <51C371E5.7060101@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184C4BBD@SCACMX008.exchad.jpmchase.net> <51C4A5B7.4030209@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184C54E8@SCACMX008.exchad.jpmchase.net> Message-ID: <51C4F3DB.9000006@nycap.rr.com> On 06/21/2013 04:44 PM, Prasad, Ramit wrote: > Matt D wrote: >> [Ramit P wrote:] >>> When you open a file the data should be written to that. If you want to >>> move existing data from logfile.txt into user opened file then you need >>> to read logfile.txt and then write it to the user opened file. To make >>> your life simpler, either pass in the file path or open the file save >>> dialog on __init__. >>> >>> >>> ~Ramit >>> >> I got so frustrated try to figure a way to use the logfile.txt that I >> changed how i log. first i name an array: >> >> class TrafficPane(wx.Panel): >> # Initializer >> # the class constructor >> def __init__(self, parent, msgq): >> wx.Panel.__init__(self, parent) >> self.msgq = msgq >> #create the array to put the traffic data in >> self.log_array = [] >> >> Then this is how the array gets into the file the user chooses: >> >> # openfile defined to start FileDialog >> def openFile(self, evt): >> with wx.FileDialog(self, "Choose a file", os.getcwd(), "", >> "*.txt*", wx.OPEN) as dlg: >> if dlg.ShowModal() == wx.ID_OK: >> path = dlg.GetPath() >> #mypath = os.path.basename(path) >> mypath = os.path.abspath(path) >> f = open(mypath, "rw+") > > Why are you opening the file in "rw+"? > >> f.writelines(self.log_array) > > You should really switch to the "with open() as f:" idiom I keep showing > you. This will automatically close the file for you. > > Also note that your file is only getting written once. You should > probably clear log_array and change the file mode back to append. > >> >> And this is how i get the TextCtrl values into the array: >> >> def update(self, field_values): >> next_line = "" >> #logger code--------------- >> # first new line >> #self.logfile.write('\n') >> # date and time >> #self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", >> localtime())))) >> next_line += (str(strftime("%Y-%m-%d %H:%M:%S", localtime()))) >> # loop through each of the TextCtrl objects >> for k,v in self.fields.items(): >> # get the value of the current TextCtrl field >> f = field_values.get(k, None) >> if f: >> # output the value with trailing comma >> #self.logfile.write('%s,'%(str(f))) >> next_line += (str(f) + ',') >> log_array.append(next_line) >> #end logger code---------- >> >> Its running right now. I haven't had the opportunity to test if it >> works so im keeping my fingers crossed. > > This is an inefficient string concatenation. It can take large amounts > of memory and time. > > next_line += (str(f) + ',') > > You can use str.join or use the csv module (which I recommend as it > will escape the delimeter (eg. commas ) if it shows up in the data ). > I have sent an example of the csv module already. Also note that > your order of the dictionary is not guaranteed so your data > may end up out of order after each run. > > 'hi', 1 , 5423 > 4255, 'hi', 2 > # instead of > 1, 'hi', 5423 > 2, 'hi', 4255 > > # A str.join example > next_line = [] > for key in sorted( self.fields ): > f = field_values.get(k, None) > if f: > next_line.append(str(f)) > line = ', '.join(next_line) > log_array.append(line) > > > ~Ramit Thanks! so i went with: # openfile defined to start FileDialog def openFile(self, evt): with wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.txt*", wx.OPEN) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() mypath = os.path.basename(path) #mypath = os.path.abspath(path) f = open(mypath, "a") f.writelines(self.log_array) couldn't figure how to use the "with open() as f:" and then down here: # Update the field values # put values in array def update(self, field_values): next_line = "" next_line += strftime("%Y-%m-%d %H:%M:%S") next_line += ','.join( field_values[k] for k in self.fields.keys() if k in field_values ) log_array.append(next_line) #if the field 'duid' == 'hdu', then clear all the fields if field_values['duid'] == 'hdu': self.clear() #loop through all TextCtrl fields storing the key/value pairs in k, v for k,v in self.fields.items(): # get the pickle value for this TextCtrl f = field_values.get(k, None) # if the value is empty then set the new value if f: v.SetValue(f) code definitely looks better but is its not working. the TextCtrls are not receiving their values anymore? i cant tell why? From cybervigilante at gmail.com Sat Jun 22 03:10:05 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 21 Jun 2013 18:10:05 -0700 Subject: [Tutor] Data persistence problem In-Reply-To: <1371859013.59304.YahooMailNeo@web186004.mail.ir2.yahoo.com> References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <1371859013.59304.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: On 21 June 2013 16:56, ALAN GAULD wrote: > > But that doesn't answer your question about incrementing the globals! :-) > To me it looks from your sample data like it is working! Good tips, though. Those sneaky zips are useful ;') Yes, the globals works fine. I just wondered if there was a way to get around using globals; but right now I'm trying something else, anyway - since that does work. The ultimate in laziness would be to get the program to append to itself so I,don't have to cut and paste from the interpreter, but I'm running into some tacky problems. Although some of them are from the IDE. But others might be from the OS, and there are different OSes so this wouldn't be portable. -- Jim A pride of lions, a gaggle of geese, a pack of wolves, a sewer of bankers. From md123 at nycap.rr.com Sat Jun 22 03:42:53 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 21 Jun 2013 21:42:53 -0400 Subject: [Tutor] Writing logfile data to a user opened file In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474184C54E8@SCACMX008.exchad.jpmchase.net> References: <51C371E5.7060101@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184C4BBD@SCACMX008.exchad.jpmchase.net> <51C4A5B7.4030209@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184C54E8@SCACMX008.exchad.jpmchase.net> Message-ID: <51C5011D.7070707@nycap.rr.com> > > You should really switch to the "with open() as f:" idiom I keep showing > you. This will automatically close the file for you. > it just occured to me to do this: def openFile(self, evt): with wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.txt*", wx.OPEN) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() mypath = os.path.basename(path) with open(mypath, "a") as f: f.writelines(self.log_array) so thats how i used what you said, "with open() as f:". is this the right way to open the file? From cybervigilante at gmail.com Sat Jun 22 04:26:53 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 21 Jun 2013 19:26:53 -0700 Subject: [Tutor] Data persistence problem In-Reply-To: <1371859013.59304.YahooMailNeo@web186004.mail.ir2.yahoo.com> References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <1371859013.59304.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: On 21 June 2013 16:56, ALAN GAULD wrote: > if isinstance(dict(),typein): > try: newdict = dict(zip(dl[::2],dl[1::2])) > except TypeError: > raise ValueError("input lists must be an even length") Not sure why TypeError and ValueError is used. I would have thought StopIteration but explain your logic on that as I'm unclear. But the Exception never tripped, either way. I tried different length iterables in the zip, but it looks like dict knows tostop before it trip thems. Only next() does raises the exception. Unless I am confused ;') >>> zippy = zip([1,2],[3,4,5,6,7,8,9]) >>> D = dict(zippy) >>> D {1: 3, 2: 4} # dict works fine >>> next(zippy) # exhausting zippy raises StopIteration Traceback (most recent call last): File "", line 301, in runcode File "", line 1, in StopIteration -- Jim A pride of lions, a gaggle of geese, a pack of wolves, a sewer of bankers. From __peter__ at web.de Sat Jun 22 09:04:35 2013 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Jun 2013 09:04:35 +0200 Subject: [Tutor] "farkadoodle" or: unique global names, was Re: Data persistence problem References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: Jim Mooney wrote: > dictnumfarkadoodle = listnumfarkadoodle = setnumfarkadoodle = 0 > # Since these are global I'm using words not likely to be duplicated > until I figure a different way and > # replace 'farkadoodle' with '' ;') Name clashes are generally not a problem if (1) you keep module size manageable and (2) use descriptive names I'd suggest _dictname_index or _makeseq_dictname_index If you want to follow the generator approach you can use default arguments: >>> from itertools import count >>> def make_nextname(template): ... return map(template.format, count()).__next__ ... >>> f = make_nextname("farkadoodle{}") >>> f() 'farkadoodle0' >>> f() 'farkadoodle1' >>> f() 'farkadoodle2' >>> def make_seq(text, type, next_setname=make_nextname("set{}")): ... if type == set: ... print(next_setname(), "=", set(text.split())) ... else: ... raise ValueError("unsupported type") ... >>> make_seq("alpha beta gamma", set) set0 = {'alpha', 'beta', 'gamma'} >>> make_seq("alpha beta gamma", set) set1 = {'alpha', 'beta', 'gamma'} >>> make_seq("alpha beta gamma", set) set2 = {'alpha', 'beta', 'gamma'} Here's an alternative implementation of make_nextname() which may be easier to understand: >>> def make_nextname(template): ... counter = -1 ... def nextname(): ... nonlocal counter ... counter += 1 ... return template.format(counter) ... return nextname ... >>> f = make_nextname("foo{:03}") >>> f() 'foo000' >>> f() 'foo001' >>> f() 'foo002' This technique of nesting a function inside another function ("closure") can also be used on make_seq directly: def make_make_seq(): set_index = 0 ... def make_seq(text, type): nonlocal set_index if type == set: print("set%s" % set_index, "=", set(text.split())) set_index += 1 ... return make_seq make_seq = make_make_seq() make_seq("a b c", set) # set0 = {'c', 'b', 'a'} make_seq("a b c", set) # set1 = {'c', 'b', 'a'} From alan.gauld at btinternet.com Sat Jun 22 09:44:22 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Jun 2013 08:44:22 +0100 Subject: [Tutor] Data persistence problem In-Reply-To: References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <1371859013.59304.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: On 22/06/13 03:26, Jim Mooney wrote: >> if isinstance(dict(),typein): >> try: newdict = dict(zip(dl[::2],dl[1::2])) >> except TypeError: >> raise ValueError("input lists must be an even length") > > Not sure why TypeError and ValueError is used. I used them because that's what I got in my testing of dict on Python 2.7. The zip() may actually obviate the need since it stops zipping when it runs out of matches. And the reason I changed from your Exception type is that using the base Exception is nearly always wrong. It means that you then have to catch the top level Exception which will include every possible error that could occur. So if somebody hits Ctl-C for instance (KeyboardInterrupt) you will still be telling them to pass even length input. So it's better to either use a standard exception type or invent a new one. In this case TypeError was what it was throwing and ValueError seemed to me to describe an invalid length list... > StopIteration This is usually used to force a stop of a loop - usually because you've ran out of data. Since I wasn't using an explicit loop it didn't seem appropriate but I could see how you might consider it an option. Certainly better than Exception.. > iterables in the zip, but it looks like dict knows tostop No, it's zip() that knows when to stop. In 2.7 I get: >>> dict([1,2],[1,2,3]) Traceback (most recent call last): File "", line 1, in TypeError: dict expected at most 1 arguments, got 2 >>> zip([1,2],[1,2,3]) [(1, 1), (2, 2)] >>> The behaviour may have changed in 3.3... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jun 22 09:47:40 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Jun 2013 08:47:40 +0100 Subject: [Tutor] Writing logfile data to a user opened file In-Reply-To: <51C5011D.7070707@nycap.rr.com> References: <51C371E5.7060101@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184C4BBD@SCACMX008.exchad.jpmchase.net> <51C4A5B7.4030209@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184C54E8@SCACMX008.exchad.jpmchase.net> <51C5011D.7070707@nycap.rr.com> Message-ID: On 22/06/13 02:42, Matt D wrote: > if dlg.ShowModal() == wx.ID_OK: > path = dlg.GetPath() > mypath = os.path.basename(path) > with open(mypath, "a") as f: > f.writelines(self.log_array) > > so thats how i used what you said, "with open() as f:". is this the > right way to open the file? You need to indent the writelines() call so its inside the 'with' block. with open(mypath, "a") as f: f.writelines(self.log_array) This means you don't need to call f.close() each time - which you were missing from your earlier code. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jacklittlemc at yahoo.com Sat Jun 22 10:09:05 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Sat, 22 Jun 2013 01:09:05 -0700 (PDT) Subject: [Tutor] Global Variables Message-ID: <1371888545.5587.YahooMailNeo@web124501.mail.ne1.yahoo.com> Is there a way to keep a global throughout multiple def statements? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Jun 22 10:50:17 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Jun 2013 18:50:17 +1000 Subject: [Tutor] Global Variables In-Reply-To: <1371888545.5587.YahooMailNeo@web124501.mail.ne1.yahoo.com> References: <1371888545.5587.YahooMailNeo@web124501.mail.ne1.yahoo.com> Message-ID: <51C56549.6050008@pearwood.info> On 22/06/13 18:09, Jack Little wrote: > Is there a way to keep a global throughout multiple def statements? I don't understand the question. The only way to *not* keep a global through multiple def statements is if you delete the global: x = 1 # Global. def function_one(): code goes here... def function_two(): code goes here... del x def function_three(): code goes here... But I suspect that this is not what you mean. Can you explain in more detail what you mean? -- Steven From steve at pearwood.info Sat Jun 22 11:11:07 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Jun 2013 19:11:07 +1000 Subject: [Tutor] Data persistence problem In-Reply-To: References: Message-ID: <51C56A2B.6030900@pearwood.info> On 22/06/13 00:32, Wolfgang Maier wrote: > Arijit Ukil tcs.com> writes: > >> >> I have following random number generation >> function >> def >> rand_int (): >> rand_num = int(math.ceil >> (random.random()*1000)) >> return >> rand_num >> I like to make the value of rand_num >> (return of rand_int) static/ unchanged after first call even if it is called >> multiple times. If x= rand_int () returns 45 at the first call, x >> should retain 45 even in multiple calls. > > Sifting through the random module documentation a bit: > > def rand_int(update=False): > if update: > dummy = random.random() > oldstate=random.getstate() > rand_num = random.randint(0,1000) > random.setstate(oldstate) > > return rand_num > > This will return a constant number when called with a False value for update > (the default), but will switch to returning a new number when called > with a True value once. You really don't want to do this! By doing this, every time you call your rand_int() function, you will reset the application-wide pseudo-random number generator, possibly making a mess of other parts of your application and the standard library. You also throw away a random value, which probably won't make a difference for the default Python PRNG, but may be bad if you're using a lousy PRNG. There is a much simpler ways of doing this (see below), but if you must use getstate and setstate, then you should create your own personal random number generator rather than use the system-wide default PRNG. myrandom = random.Random() def rand_int(update=False): if update: dummy = myrandom.random() oldstate = myrandom.getstate() rand_num = myrandom.randint(0, 1000) myrandom.setstate(oldstate) return rand_num This doesn't look like much, but it's actually an awful lot of work just to return a fixed, constant number! The PRNG used by Python is *very good*, which means it is also computationally quite expensive. Here's a cheaper way to get the same effect, using a mutable default argument to store the last result, then only call the PRNG when you actually need to: def rand_int(update=False, seed=[None]): if update or seed[0] is None: seed[0] = random.randint(0, 1000) return seed[0] -- Steven From steve at pearwood.info Sat Jun 22 11:53:39 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Jun 2013 19:53:39 +1000 Subject: [Tutor] Data persistence problem In-Reply-To: References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <1371859013.59304.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: <51C57423.1060205@pearwood.info> On 22/06/13 11:10, Jim Mooney wrote: > The ultimate in laziness would be to get the program to > append to itself so I,don't have to cut and paste from the > interpreter, but I'm running into some tacky problems. Although some > of them are from the IDE. But others might be from the OS, and there > are different OSes so this wouldn't be portable. Sounds to me like you are experimenting with "Do What I Mean" software. Here's a cautionary tale about DWIM: http://www.catb.org/jargon/html/D/DWIM.html -- Steven From steve at pearwood.info Sat Jun 22 12:08:25 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Jun 2013 20:08:25 +1000 Subject: [Tutor] Global Variables In-Reply-To: <1371888545.5587.YahooMailNeo@web124501.mail.ne1.yahoo.com> References: <1371888545.5587.YahooMailNeo@web124501.mail.ne1.yahoo.com> Message-ID: <51C57799.5010404@pearwood.info> On 22/06/13 18:09, Jack Little wrote: > Is there a way to keep a global throughout multiple def statements? Oh, a further thought! Perhaps you mean something like this? x = 42 # Global value. def function_one(): global x # Define it once. code using global x goes here... def function_two(): # x is already declared global, so no need to do it again code using global x goes here... # Run the code. function_one() function_two() If that's what you mean, the answer is, thank goodness, no, there is no way to do this! Relying on global variables is, as a general rule, a good way to end up with unmaintainable, buggy code that cannot easily be tested and is frustrating to debug. Sixty years of experience in programming has lead to the conclusion that global variables are best avoided. To be precise, it is not so much the *global variable* part that is harmful, but the reliance on side-effects in the code: calling a function invisibly gets input from a global, and outputs to a global. We can get better, safer, easier to understand code by using explicit input arguments and a return result: def function_one(arg): code using argument "arg" goes here... return result of calculation def function_two(arg): code using "arg" goes here... return result of calculation # Run the code. x = 42 x = function_one(x) y = function_two(x) In this case, we can see that the value of x is passed to function_one as input. There's no need to guess that it magically uses some global variable. We can also see that the result of that calculation is stored back into x. Then in the next line, the new value of x is passed to function_two as input, and the result is stored in a different variable, y. Although there is a very slight increase in the amount of typing, with practice and experience this leads to more maintainable, more easily debugged code. -- Steven From steve at pearwood.info Sat Jun 22 13:00:32 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Jun 2013 21:00:32 +1000 Subject: [Tutor] Data persistence problem In-Reply-To: References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: <51C583D0.5040102@pearwood.info> On 22/06/13 09:00, Jim Mooney wrote: > On 21 June 2013 14:59, ALAN GAULD wrote: > >> >> Give us a clue, show us your code! > > I was hoping you wouldn't say that since it's another of my insane > Lazy Typer programs to avoid typing, which are no doubt considered > frivolous. Although I'm learning a lot doing them ;') Well, perhaps not *frivolous*. After all, Python itself might be said to be a "lazy typer" programming language, compared to some such as Pascal, C, or especially Java. Compare the archetypal "Hello World" program in Java versus Python: === Java version === public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } } === Python version === print("Hello, World") Speaking of Java, I get a kick out of this article and love to link to it on every possible opportunity: http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html :-) > Okay, I have a snippet that posts the below text in automatically. I > can use it to make any number of dicts, lists, or sets, from just > tokens in a single string, and they are printed out as the different > types, named and and numbered so they have different program names. > That way I don't have to type in quotes, commas, colons, and so forth. > Once the interpreter prints them out, I just select all and paste them > into my program, replacing what's below. Kind of a manual > meta-programming ;') > > ============= pasted in snippet ================ > > ## Output sequence will be all strings. The first type in the 2nd > parameter list will be the > ## default due to 'or" short circuiting, so you can just delete to get > what you want. > ## You MUST have an even number of tokens for a dict or you'll get an exception. > > from maker import makeseq > makeseq("Replace me, even number of tokens for dict", dict or list or set) I think that a better design here would be three functions that explicitly tell you what they do: makedict makelist makeset The three of them could call an underlying internal function that does most of the work. Or not, as the case may be. > ============= end snippet ==================== > > From this I can create any number of numbered dicts, lists or sets *Numbered* variables? Oh wow, is it 1975 again? I didn't think I'd be programming in BASIC again... :-) > (The 'or' short circuit means I get dicts as default, and only have to > delete from the front to get the others - dicts are default since > they're the most annoying to type - now That's lazy.) Surely typing one of "dict", "list" or "set" is not too much effort? makeseq("stuff goes here ...", dict) makeseq("stuff goes here ...", list) makeseq("stuff goes here ...", set) makeseq("stuff goes here ...", tuple) makeseq("stuff goes here ...", frozenset) You don't even need to put quotes around the type. In fact, you *shouldn't* put quotes around the type, since that will stop it from working. [...] > makeseq("this is a list and it is not a very big list", list or set) Creating your own tools is fine, but they ought to do a little more than just duplicate the functionality of built-in tools. I'll come back to the dict case again further down, but the list and set cases are trivial: L1 = "this is a list and it is not a very big list".split() L2 = "Yet another list to show the different types increment separately".split() S1 = set("and finally some sets".split()) Best of all, the time you save not having to type "makeseq" can now be used to think of meaningful, descriptive names for the variables :-) Here are some improvements to your makeseq function: > dictnumfarkadoodle = listnumfarkadoodle = setnumfarkadoodle = 0 > # Since these are global I'm using words not likely to be duplicated > until I figure a different way and > # replace 'farkadoodle' with '' ;') > > def makeseq(instring, typein): > global dictnumfarkadoodle, listnumfarkadoodle, setnumfarkadoodle > if isinstance(dict(), typein): Rather than create a new dict, then check to see if it is an instance of typein, you can just do this: if typein is dict: ... elif typein is list: ... elif typein is set: ... and similar for tuple and frozenset. > newdict = {} > dl = instring.split() > if len(dl) % 2 != 0: > raise Exception ("list entries must be even") # so they match It is normally better to use a more specific exception. In this case, I recommend using TypeError, since TypeError is used for cases where you pass the wrong number of arguments to a type constructor (among other things). > for idx in range(0,len(dl),2): > newdict[dl[idx]] = dl[idx+1] In general, any time you find yourself channeling Pascal circa 1984, you're doing it wrong :-) There is very rarely any need to iterate over index numbers like this. The preferred Python way would be to slice the list into two halves, then zip them together: keys = d1[0::2] # Every second item, starting at 0. values = d1[1::2] # Every second item, starting at 1. newdict = dict(zip(keys, values)) which can be re-written as a single line: newdict = dict(zip(d1[0::2], d1[1::2])) > dictnumfarkadoodle += 1 > print('D' + str(dictnumfarkadoodle) + ' =', newdict) > elif isinstance(list(), typein): > newlist = [] > dl = instring.split() > for word in dl: > newlist.append(word) dl is already a list. There's no need to laboriously, and manually, copy the items from dl one by one. Instead you can tell Python to copy them: newlist = list(dl) or if you prefer slicing notation: newlist = dl[:] # Slice from the beginning to the end. but really, why bother to copy the list? newlist = instring.split() > listnumfarkadoodle += 1 > print('L' + str(listnumfarkadoodle) + ' =', newlist) > elif isinstance(set(), typein): > newset = set() > dl = instring.split() > for word in dl: > newset.add(word) I'm going to leave this one for you. Given what you've seen with the list section, how would you improve this one? (Hint: here too, dl is a list, and set() takes a list as argument and returns a set.) > setnumfarkadoodle += 1 > print('S' + str(setnumfarkadoodle) + ' =', newset) > else: print('Second parameter must be list, set, or dict') > > # oops, I error out on a non-type 2nd parameter. Fix this later Actually, no, you don't error out. You just print a message. To make it a proper error, you need to raise an exception: raise TypeError("second param blah blah blah...") or similar. -- Steven From steve at pearwood.info Sat Jun 22 13:10:24 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Jun 2013 21:10:24 +1000 Subject: [Tutor] "farkadoodle" or: unique global names, was Re: Data persistence problem In-Reply-To: References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> Message-ID: <51C58620.8090606@pearwood.info> On 22/06/13 17:04, Peter Otten wrote: > This technique of nesting a function inside another function ("closure") To be pedantic, not all nested functions are closures. Here's one which is not: def outer(arg): def inner(x): return x + 1 assert inner.__closure__ is None return inner(arg) In this case, the inner function does not refer to any variables defined in the outer function. Instead, it is explicitly passed the value it needs as an argument. Here's one which is a closure: def outer(arg): def inner(): return arg + 1 assert inner.__closure__ is not None return inner() The function attribute "__closure__" is set to None for regular functions. For closures, it is set to a bunch of stuff needed for the inner function to work correctly. (No user serviceable parts inside.) Basically, the inner function needs to carry around with it a little piece of its environment, so it can retrieve the value of "arg" when required. -- Steven From steve at pearwood.info Sat Jun 22 13:22:03 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Jun 2013 21:22:03 +1000 Subject: [Tutor] Data persistence problem In-Reply-To: References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <1371859013.59304.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: <51C588DB.8030809@pearwood.info> On 22/06/13 12:26, Jim Mooney wrote: > On 21 June 2013 16:56, ALAN GAULD wrote: > > >> if isinstance(dict(),typein): >> try: newdict = dict(zip(dl[::2],dl[1::2])) >> except TypeError: >> raise ValueError("input lists must be an even length") > > Not sure why TypeError and ValueError is used. I would have thought > StopIteration but explain your logic on that as I'm unclear. But the > Exception never tripped, either way. I tried different length > iterables in the zip, but it looks like dict knows tostop before it > trip thems. Only next() does raises the exception. Unless I am > confused ;') It's not dict which is smart in this case, but zip(), which stops when one of the sequences has run out: py> zip("abcdefg", "1234", "ABCDEFGHIJKLMN") [('a', '1', 'A'), ('b', '2', 'B'), ('c', '3', 'C'), ('d', '4', 'D')] In Python 3, zip is "lazy" and only returns items on request, rather than "eager" returning them all at once in a list. To get the same result in Python 3, use list(zip(...)) instead. If you arrange for dict to see a missing value, it will raise ValueError: py> dict([('a', 1), ('b', 2), ('c',)]) Traceback (most recent call last): File "", line 1, in ValueError: dictionary update sequence element #2 has length 1; 2 is required >>>> zippy = zip([1,2],[3,4,5,6,7,8,9]) >>>> D = dict(zippy) >>>> D > {1: 3, 2: 4} # dict works fine >>>> next(zippy) # exhausting zippy raises StopIteration > Traceback (most recent call last): > File "", line 301, in runcode > File "", line 1, in > StopIteration That's because zippy is already exhausted by dict, and once exhausted, it stays exhausted. -- Steven From steve at pearwood.info Sat Jun 22 13:28:16 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Jun 2013 21:28:16 +1000 Subject: [Tutor] Best Code testing practice? In-Reply-To: <51C498C4.10507@nycap.rr.com> References: <51C2EAE2.9090209@nycap.rr.com> <51C498C4.10507@nycap.rr.com> Message-ID: <51C58A50.30807@pearwood.info> On 22/06/13 04:17, Matt D wrote: > Hey guys! > Have decided that it is probably going to be better for my purposes to > simply crack open a terminal, cd into the appropriate directory, and do > the 'python test_code.py' or whatever the file name is from the command > line. I feel it is better for me to learn how to write code in gedit > before i use an IDE. Nicely said! -- Steven From md123 at nycap.rr.com Sat Jun 22 17:16:01 2013 From: md123 at nycap.rr.com (Matt D) Date: Sat, 22 Jun 2013 11:16:01 -0400 Subject: [Tutor] Writing logfile data to a user opened file In-Reply-To: References: <51C371E5.7060101@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184C4BBD@SCACMX008.exchad.jpmchase.net> <51C4A5B7.4030209@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184C54E8@SCACMX008.exchad.jpmchase.net> <51C5011D.7070707@nycap.rr.com> Message-ID: <51C5BFB1.9060907@nycap.rr.com> On 06/22/2013 03:47 AM, Alan Gauld wrote: > On 22/06/13 02:42, Matt D wrote: > >> if dlg.ShowModal() == wx.ID_OK: >> path = dlg.GetPath() >> mypath = os.path.basename(path) >> with open(mypath, "a") as f: >> f.writelines(self.log_array) >> >> so thats how i used what you said, "with open() as f:". is this the >> right way to open the file? > > You need to indent the writelines() call so its inside > the 'with' block. > > with open(mypath, "a") as f: > f.writelines(self.log_array) > > This means you don't need to call f.close() each time - which you were > missing from your earlier code. > Thanks! That is how i had it; not sure how the indent got nixed when pasted to my mail. From eryksun at gmail.com Sat Jun 22 17:38:23 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 22 Jun 2013 11:38:23 -0400 Subject: [Tutor] "farkadoodle" or: unique global names, was Re: Data persistence problem In-Reply-To: <51C58620.8090606@pearwood.info> References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <51C58620.8090606@pearwood.info> Message-ID: On Sat, Jun 22, 2013 at 7:10 AM, Steven D'Aprano wrote: > The function attribute "__closure__" is set to None for regular functions. > For closures, it is set to a bunch of stuff needed for the inner function to > work correctly. (No user serviceable parts inside.) Basically, the inner > function needs to carry around with it a little piece of its environment, so > it can retrieve the value of "arg" when required. Using a tuple of cells (loaded from __closure__) allows for fast lookups. If you check with dis, you'll see the ops used with cells are LOAD_DEREF and STORE_DEREF. These handle the indirection through the cell object, which is a flat cost. It's not a function of nesting level. Using cells also avoids referencing the outer frame(s), which would interfere with garbage collection (GC). One catch with Python nested scopes is that binding a name defaults to the local scope. You can get around this by using a mutable container, just as was done with globals before the "global" keyword was added in version 0.9.4 (1991). The better solution is a new keyword, but adding keywords is radical surgery. The "nonlocal" keyword, as Peter used, had to wait for 3.x. From eryksun at gmail.com Sat Jun 22 17:58:27 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 22 Jun 2013 11:58:27 -0400 Subject: [Tutor] EXE Problem In-Reply-To: References: <1371624655.61616.YahooMailNeo@web124504.mail.ne1.yahoo.com> Message-ID: On Wed, Jun 19, 2013 at 6:58 PM, Alan Gauld wrote: > On 19/06/13 17:41, Jim Mooney wrote: > >> you should use forward slashes. I have no idea why Bill Gates thought >> backslashes were kewl > > Because MS DOS was copying CP/M which didn't have directory paths > (it was used with 180K floppy disks that stored everything at the top > level) but did have command options that were indicated by a > forward slash > > DIR /S > > was a sorted directory listing etc. > > So MS DOS inherited / as an options marker which precluded > it's later use as a path separator... CP/M didn't have a hierarchical file system, but it did have up to 16 USER areas. As to / switches, maybe at some point someone confused CP/M with DEC's TOPS-10, which used switches quite a lot (it even had SWITCH.INI for defaults). TOPS-10 would have been familiar to many 1970s programmers. Its DIR command had over 70 switches, such as /SORT (default) and /NOSORT. In contrast, DIR on CP/M used options in square brackets, such as the following example: DIR [DRIVE=B,USER=ALL,EXCLUDE,NOSORT] *.DAT This would list all files on B: in all USER areas exluding DAT files, without sorting. The USER areas in CP/M are reminiscent of TOPS-10 user-file directories. A UFD was designated by a [project, programmer] number (PPN), and could have up to 5 levels of sub-file directories (SFD). For example, DSKB:FOO.TXT[14,5,BAR,BAZ], where 14,5 is a PPN. In VMS style it's DSKB:[USER.BAR.BAZ]FOO.TXT. In comparison, slash vs. backslash seems trivial. From nsivaram.net at gmail.com Sat Jun 22 18:56:40 2013 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Sat, 22 Jun 2013 22:26:40 +0530 Subject: [Tutor] appending/updating values dict key value pairs Message-ID: <878v22f5iv.fsf@gmail.com> What's the best way to append to the list which is the value to a dict key? I did the following based on the docs and I'm not sure why it works >>> b = { 'a': [4, 5]} >>> list.append(b.get('a'),'c') >>> b {'a': [4, 5, 'c']} >>> as in, shouldn't it be b['a'] = list.append(b.get('a'),'c') which doesn't seem to work. sivaram -- From breamoreboy at yahoo.co.uk Sat Jun 22 19:04:24 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 22 Jun 2013 18:04:24 +0100 Subject: [Tutor] appending/updating values dict key value pairs In-Reply-To: <878v22f5iv.fsf@gmail.com> References: <878v22f5iv.fsf@gmail.com> Message-ID: On 22/06/2013 17:56, Sivaram Neelakantan wrote: > > What's the best way to append to the list which is the value to a dict > key? > > I did the following based on the docs and I'm not sure why it works > >>>> b = { 'a': [4, 5]} >>>> list.append(b.get('a'),'c') >>>> b > {'a': [4, 5, 'c']} >>>> > > > as in, shouldn't it be > > b['a'] = list.append(b.get('a'),'c') > > which doesn't seem to work. > > sivaram > -- b['a'].append('c') -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From nsivaram.net at gmail.com Sat Jun 22 19:52:36 2013 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Sat, 22 Jun 2013 23:22:36 +0530 Subject: [Tutor] appending/updating values dict key value pairs References: <878v22f5iv.fsf@gmail.com> Message-ID: <87zjuidod7.fsf@gmail.com> On Sat, Jun 22 2013,Mark Lawrence wrote: [snipped 7 lines] >>>>> b = { 'a': [4, 5]} >>>>> list.append(b.get('a'),'c') >>>>> b >> {'a': [4, 5, 'c']} >>>>> >> >> >> as in, shouldn't it be >> >> b['a'] = list.append(b.get('a'),'c') >> >> which doesn't seem to work. >> >> sivaram >> -- > > b['a'].append('c') arrgh! I should have known this. Thank you for making it obvious to the noob. sivaram -- From cybervigilante at gmail.com Sat Jun 22 20:29:03 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 22 Jun 2013 11:29:03 -0700 Subject: [Tutor] Data persistence problem In-Reply-To: <51C583D0.5040102@pearwood.info> References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <51C583D0.5040102@pearwood.info> Message-ID: On 22 June 2013 04:00, Steven D'Aprano wrote: > Speaking of Java, I get a kick out of this article and love to link to it on > every possible opportunity: > > http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html Funny. Speaking of Java, I saw a used book on design patterns, that wasn't too old, but all the examples were in Java. Why not just hit myself in the head with a brick? Except for a really old general book, all the recent books on design patterns, which I was curious about, are on specific languages - design patterns for Java (speak of the devil), Visual Basic, Tcl, even Android. But I couldn't fine One on Python. Is there a reason for this? Don't they play well with Python, or did I miss the book somehow? I think Java is all nouns since it's a "business" language and managers do love their nouns. (There is a big difference between managers and entrepreneurs, which an entrepreneur once pointed out to me, though.) -- Jim A pride of lions, a gaggle of geese, a pack of wolves, a sewer of bankers. From fomcl at yahoo.com Sat Jun 22 21:39:53 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 22 Jun 2013 12:39:53 -0700 (PDT) Subject: [Tutor] appending/updating values dict key value pairs In-Reply-To: <87zjuidod7.fsf@gmail.com> References: <878v22f5iv.fsf@gmail.com> <87zjuidod7.fsf@gmail.com> Message-ID: <1371929993.34393.YahooMailNeo@web163802.mail.gq1.yahoo.com> ________________________________ > From: Sivaram Neelakantan >To: tutor at python.org >Sent: Saturday, June 22, 2013 7:52 PM >Subject: Re: [Tutor] appending/updating values dict key value pairs > > >On Sat, Jun 22 2013,Mark Lawrence wrote: > > >[snipped 7 lines] > >>>>>> b = { 'a': [4, 5]} >>>>>> list.append(b.get('a'),'c') >>>>>> b >>> {'a': [4, 5, 'c']} >>>>>> >>> >>> >>> as in, shouldn't it be >>> >>> b['a'] = list.append(b.get('a'),'c') >>> >>> which doesn't seem to work. >>> >>>???sivaram >>>???-- >> >> b['a'].append('c') > > >arrgh! I should have known this.? Thank you for making it obvious to >the noob. I use dict.setdefault fairly often for things like this: >>> d = {} >>> d.setdefault("aKey", []).append("aValue") >>> d.setdefault("aKey", []).append("anotherValue") >>> d {'aKey': ['aValue', 'anotherValue']} >>> d.setdefault("anotherKey", []).append("aValue") >>> d {'aKey': ['aValue', 'anotherValue'], 'anotherKey': ['aValue']} From fomcl at yahoo.com Sat Jun 22 21:59:12 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 22 Jun 2013 12:59:12 -0700 (PDT) Subject: [Tutor] "farkadoodle" or: unique global names, was Re: Data persistence problem In-Reply-To: References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <51C58620.8090606@pearwood.info> Message-ID: <1371931152.54551.YahooMailNeo@web163803.mail.gq1.yahoo.com> ? > One catch with Python nested scopes is that binding a name defaults to > the local scope. You can get around this by using a mutable container, > just as was done with globals before the "global" keyword was added in > version 0.9.4 (1991). The better solution is a new keyword, but adding > keywords is radical surgery. The "nonlocal" keyword, as Peter used, > had to wait for 3.x. I was playing around with this a bit and arrived at the following surprising (for me at least) result. I thought the global/local/nonlocal keywords could be used to get values from another scope. Though this could also happen implicitly, e.g. if only x = "I am global" is defined and x is used (and not redefined) inside a function, then python still knows this variable inside that function. Is there any way to make this work? (it may not be desirable, though) #Python 3.2.3 (default, Apr 10 2013, 05:29:11) [GCC 4.6.3] on linux2 >>> x = "I am global" >>> def outer(): ...???? x = "I am nonlocal" ...???? def inner(): ...???????? x = "I am local" ...???????? print(x)? # expecting to print 'I am local' ...???????? nonlocal x ...???????? print(x) # expecting to print 'I am nonlocal' ...???????? global x ...???????? print(x) # expecting to print 'I am global' ...???? inner() ... :6: SyntaxWarning: name 'x' is assigned to before nonlocal declaration :8: SyntaxWarning: name 'x' is assigned to before global declaration SyntaxError: name 'x' is nonlocal and global From jf_byrnes at comcast.net Sat Jun 22 23:01:20 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Sat, 22 Jun 2013 16:01:20 -0500 Subject: [Tutor] How convert an int to a string Message-ID: I need to convert a series of digits like 060713 to a string so I can make it look like a date 06-07-13. >>> a = 060713 >>> a[:2] Traceback (most recent call last): File "", line 1, in TypeError: 'int' object has no attribute '__getitem__' >>> b = str(a) >>> b[:2] '25' >>> b '25035' >>> I was confused at first but then realized that the 0 makes it octal. I thought str() would do it but it didn't. Reading about str() it talks of string representation. So how can I convert it to a true string I can slice and build my date look a like? Thanks, Jim From alan.gauld at btinternet.com Sat Jun 22 23:10:14 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Jun 2013 22:10:14 +0100 Subject: [Tutor] Data persistence problem In-Reply-To: <51C583D0.5040102@pearwood.info> References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <51C583D0.5040102@pearwood.info> Message-ID: On 22/06/13 12:00, Steven D'Aprano wrote: > Speaking of Java, I get a kick out of this article and love to link to > it on every possible opportunity: > > http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html This could get seriously OT here... I found that an interesting blog in that I agreed with half of it, disagreed with half and couldn't make up my mind about the other half!!! :-) But I also found the followup comments interesting. And most interesting of all, despite the verbiage on natural languages, nobody commented on the distinction between classes and objects. My peeve with Java is that it is Class oriented rather than Object oriented. Classes are common nouns (eg river), objects are proper nouns (eg Nile). My other peeve is static typing. I've been using OOP since 1985 in a mix of static and dynamic languages(*) and have come to the conclusion that OOP only works properly in a dynamic typed environment. Smalltalk, Objective C and Python have very different object models and OOP idioms but all three can produce clean elegant OOP solutions. ObjectPascal, C++ and Java equally have different object models but all run into similar problems with OOP. You wind up creating lots of wrapper/interface classes just to get round the limitations of the type strictures. However, all successful OOP languages I've used have got round the need for free functions by simply defining a top level container class called App or system or some such (or by having functions as first class objects!). It really doesn't need to be as big an issue as the blog makes out. The real problem is the way the Java community have regimented the use of OOP. (*) In approximately this order: Smalltalk, ObjectPascal(Apple), C++, Lisp(Flavors), ObjectiveC, ADA, Eiffel, Modula 2/3, Actor, PL/SQL, Java, ObjectPascal(Delphi), COBOL(yes really!), Tcl(incTcl), Python, Perl, Ruby, C#, VB, JavaScript, Lisp(CLOS). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Sat Jun 22 23:15:24 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 22 Jun 2013 22:15:24 +0100 Subject: [Tutor] Data persistence problem In-Reply-To: References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <51C583D0.5040102@pearwood.info> Message-ID: On 22/06/2013 19:29, Jim Mooney wrote: > On 22 June 2013 04:00, Steven D'Aprano wrote: > > >> Speaking of Java, I get a kick out of this article and love to link to it on >> every possible opportunity: >> >> http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html > > Funny. Speaking of Java, I saw a used book on design patterns, that > wasn't too old, but all the examples were in Java. Why not just hit > myself in the head with a brick? > > Except for a really old general book, all the recent books on design > patterns, which I was curious about, are on specific languages - > design patterns for Java (speak of the devil), Visual Basic, Tcl, even > Android. But I couldn't fine One on Python. Is there a reason for > this? Don't they play well with Python, or did I miss the book > somehow? Loads of the design pattern stuff is written to help programmers get around the straight jacket that languages can impose, whereas implementating the same patterns in Python is often ludicrously easy. If you want to dig further, I suggest you arm yourself with plenty of coffee and sandwiches, then use your favourite search engine to hunt for "Python patterns Alex Martelli". Enjoy :) -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From alan.gauld at btinternet.com Sat Jun 22 23:16:43 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Jun 2013 22:16:43 +0100 Subject: [Tutor] appending/updating values dict key value pairs In-Reply-To: <878v22f5iv.fsf@gmail.com> References: <878v22f5iv.fsf@gmail.com> Message-ID: On 22/06/13 17:56, Sivaram Neelakantan wrote: >>>> list.append(b.get('a'),'c') Lets look at what this is doing in simplistic terms. 'list' is the class and 'append' is a method of the class. When we call a method via the class we have to provide the 'self' argument explicitly so in this case self is b.get('a') which is the result of getting the value associated with the key 'a'; in b. or put another way it is b['a'] so we can simplify a little to list.append(b['a'], 'c') But we normally call methods via the object instance rather than the class so simplifying this further we get: b['a'].append('c') Which is how we would normally do it. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jun 22 23:31:45 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Jun 2013 22:31:45 +0100 Subject: [Tutor] EXE Problem In-Reply-To: References: <1371624655.61616.YahooMailNeo@web124504.mail.ne1.yahoo.com> Message-ID: On 22/06/13 16:58, eryksun wrote: > In contrast, DIR on CP/M used options in square > brackets, such as the following example: > > DIR [DRIVE=B,USER=ALL,EXCLUDE,NOSORT] *.DAT You are right, CP/M did use square brackets for flags, I'd forgotten those. But it did have some / switches too. (or at least CP/M 3 (aka CP/M plus), which was the only version I used, did.) So, my example of DIR /S was wrong. But I got the concept from my old CP/M programming manual which says... A> mbasic5 /m:&hc000 Which tells mbasic to protect memory location hc000... But mbasic isn't really part of CP/M it was a BASIC interpreter written by .... Microsoft! So maybe DOS got its / flags because they were already using them for their BASIC... > The USER areas in CP/M Weren't USER areas a late introduction to CP/M? (Version 3 again I think...) But I agree very similar to the DEC setup. But then most of the early OS developers were working on DEC kit back then, DEC had most of the research hardware market sown up in the '70s. CP/M came from Dartmouth Navy Labs, Unix from Bell labs, Microsoft from Harvard(very indirectly). Anyways, apologies for my earlier misinformation - the old grey cells are a little older than they used to be! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Sat Jun 22 23:33:54 2013 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Jun 2013 23:33:54 +0200 Subject: [Tutor] How convert an int to a string References: Message-ID: Jim Byrnes wrote: > I need to convert a series of digits like 060713 to a string so I can > make it look like a date 06-07-13. > > >>> a = 060713 > >>> a[:2] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'int' object has no attribute '__getitem__' > >>> b = str(a) > >>> b[:2] > '25' > >>> b > '25035' > >>> > > I was confused at first but then realized that the 0 makes it octal. I > thought str() would do it but it didn't. Reading about str() it talks of > string representation. So how can I convert it to a true string I can > slice and build my date look a like? >>> a = 060713 >>> "%06o" % a '060713' >>> "{:06o}".format(a) '060713' From fomcl at yahoo.com Sat Jun 22 23:44:09 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 22 Jun 2013 14:44:09 -0700 (PDT) Subject: [Tutor] How convert an int to a string In-Reply-To: References: Message-ID: <1371937449.20586.YahooMailNeo@web163801.mail.gq1.yahoo.com> --- Original Message ----- > From: Jim Byrnes > To: tutor at python.org > Cc: > Sent: Saturday, June 22, 2013 11:01 PM > Subject: [Tutor] How convert an int to a string > > I need to convert a series of digits like 060713 to a string so I can > make it look like a date 06-07-13. > >>>> a = 060713 >>>> a[:2] > Traceback (most recent call last): > ? File "", line 1, in > TypeError: 'int' object has no attribute '__getitem__' >>>> b = str(a) >>>> b[:2] > '25' >>>> b > '25035' >>>> > > I was confused at first but then realized that the? 0? makes it octal. I > thought str() would do it but it didn't. Reading about str() it talks of > string representation.? So how can I convert it to a true string I can > slice and build my date look a like? weird indeed. Can wait to hear more about it. But oct() does the trick. >>> a = 060713 >>> a 25035 >>> import time >>> time.strftime("%d-%m-%y", time.strptime(oct(a), "%d%m%y")) '06-07-13' >>> b = str(oct(a)) >>> "%02s-%02s-%02s" % (b[:2], b[2:4], b[4:]) '06-07-13' From breamoreboy at yahoo.co.uk Sat Jun 22 23:59:12 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 22 Jun 2013 22:59:12 +0100 Subject: [Tutor] How convert an int to a string In-Reply-To: <1371937449.20586.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <1371937449.20586.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On 22/06/2013 22:44, Albert-Jan Roskam wrote: > > > --- Original Message ----- > >> From: Jim Byrnes >> To: tutor at python.org >> Cc: >> Sent: Saturday, June 22, 2013 11:01 PM >> Subject: [Tutor] How convert an int to a string >> >> I need to convert a series of digits like 060713 to a string so I can >> make it look like a date 06-07-13. >> >>>>> a = 060713 >>>>> a[:2] >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: 'int' object has no attribute '__getitem__' >>>>> b = str(a) >>>>> b[:2] >> '25' >>>>> b >> '25035' >>>>> >> >> I was confused at first but then realized that the 0 makes it octal. I >> thought str() would do it but it didn't. Reading about str() it talks of >> string representation. So how can I convert it to a true string I can >> slice and build my date look a like? > > weird indeed. Can wait to hear more about it. But oct() does the trick. > >>>> a = 060713 >>>> a > 25035 >>>> import time >>>> time.strftime("%d-%m-%y", time.strptime(oct(a), "%d%m%y")) > '06-07-13' >>>> b = str(oct(a)) >>>> "%02s-%02s-%02s" % (b[:2], b[2:4], b[4:]) > '06-07-13' How do you propose handling the errors that will occur when any of day, month or year have a non octal digit? -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From david at graniteweb.com Sun Jun 23 00:10:42 2013 From: david at graniteweb.com (David Rock) Date: Sat, 22 Jun 2013 17:10:42 -0500 Subject: [Tutor] How convert an int to a string In-Reply-To: References: Message-ID: <20130622221042.GC22060@wdfs.graniteweb.com> * Jim Byrnes [2013-06-22 16:01]: > I need to convert a series of digits like 060713 to a string so I can > make it look like a date 06-07-13. > > >>> a = 060713 > >>> a[:2] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'int' object has no attribute '__getitem__' > >>> b = str(a) > >>> b[:2] > '25' > >>> b > '25035' > >>> > > I was confused at first but then realized that the 0 makes it octal. I > thought str() would do it but it didn't. Reading about str() it talks of > string representation. So how can I convert it to a true string I can > slice and build my date look a like? Is there a requirement to store them as numbers in the first place? Why not just store them as a string? a = '060713' -- David Rock david at graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 190 bytes Desc: Digital signature URL: From eryksun at gmail.com Sun Jun 23 00:13:50 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 22 Jun 2013 18:13:50 -0400 Subject: [Tutor] "farkadoodle" or: unique global names, was Re: Data persistence problem In-Reply-To: <1371931152.54551.YahooMailNeo@web163803.mail.gq1.yahoo.com> References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <51C58620.8090606@pearwood.info> <1371931152.54551.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: On Sat, Jun 22, 2013 at 3:59 PM, Albert-Jan Roskam wrote: > > I was playing around with this a bit and arrived at the following > surprising (for me at least) result. I thought the global/local/nonlocal > keywords could be used to get values from another scope. Though this > could also happen implicitly, e.g. if only x = "I am global" is defined > and x is used (and not redefined) inside a function, then python still > knows this variable inside that function. > > Is there any way to make this work? (it may not be desirable, though) local isn't a keyword. Maybe you're thinking of the locals() function. The global and nonlocal keywords define the scope of a name for the entire block. You can't flip it on and off like a toggle switch. That would give me headaches. Anyway, try to avoid globals and use descriptive names. If you still have a clash, use globals()[name]. From davea at davea.name Sun Jun 23 00:57:59 2013 From: davea at davea.name (Dave Angel) Date: Sat, 22 Jun 2013 18:57:59 -0400 Subject: [Tutor] How convert an int to a string In-Reply-To: References: Message-ID: <51C62BF7.1000007@davea.name> On 06/22/2013 05:01 PM, Jim Byrnes wrote: > I need to convert a series of digits like 060713 to a string so I can > make it look like a date 06-07-13. > Where is this series of digits coming from? Is it in the source code, or in a file, or coming from the user, or what? If it's in source code, add quotes around it, and it'll be a string. The whole octal nonsense is a non-starter, because it won't handle a date like September 18. Octal numbers only have digits zero through seven. If the digits are coming from a file, then they're already a string. Don't waste the time converting to decimal and/or octal, just use them. If they come from somewhere else, then tell us. And while you're at it, tell us the Python version so we have a chance at matching the advice to what you're running. > >>> a = 060713 That assignment will try to make it octal. If there are digits bigger than 7, it'll fail. -- DaveA From jf_byrnes at comcast.net Sun Jun 23 01:03:38 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Sat, 22 Jun 2013 18:03:38 -0500 Subject: [Tutor] How convert an int to a string In-Reply-To: <20130622221042.GC22060@wdfs.graniteweb.com> References: <20130622221042.GC22060@wdfs.graniteweb.com> Message-ID: On 06/22/2013 05:10 PM, David Rock wrote: > * Jim Byrnes [2013-06-22 16:01]: >> I need to convert a series of digits like 060713 to a string so I can >> make it look like a date 06-07-13. >> >> >>> a = 060713 >> >>> a[:2] >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: 'int' object has no attribute '__getitem__' >> >>> b = str(a) >> >>> b[:2] >> '25' >> >>> b >> '25035' >> >>> >> >> I was confused at first but then realized that the 0 makes it octal. I >> thought str() would do it but it didn't. Reading about str() it talks of >> string representation. So how can I convert it to a true string I can >> slice and build my date look a like? > > Is there a requirement to store them as numbers in the first place? Why > not just store them as a string? > > a = '060713' > Yes. I am scripting data entry in a spreadsheet. I can enter the 6 numbers quite rapidly using the number pad but entering the " - "'s to make it look like a date slows me down. So I thought I would let python do that for me. Regards, Jim From davea at davea.name Sun Jun 23 01:24:13 2013 From: davea at davea.name (Dave Angel) Date: Sat, 22 Jun 2013 19:24:13 -0400 Subject: [Tutor] How convert an int to a string In-Reply-To: References: <20130622221042.GC22060@wdfs.graniteweb.com> Message-ID: <51C6321D.6080400@davea.name> On 06/22/2013 07:03 PM, Jim Byrnes wrote: > On 06/22/2013 05:10 PM, David Rock wrote: >> * Jim Byrnes [2013-06-22 16:01]: >>> I need to convert a series of digits like 060713 to a string so I can >>> make it look like a date 06-07-13. >>> >>> >>> a = 060713 >>> >>> a[:2] >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: 'int' object has no attribute '__getitem__' >>> >>> b = str(a) >>> >>> b[:2] >>> '25' >>> >>> b >>> '25035' >>> >>> >>> >>> I was confused at first but then realized that the 0 makes it octal. I >>> thought str() would do it but it didn't. Reading about str() it talks of >>> string representation. So how can I convert it to a true string I can >>> slice and build my date look a like? >> >> Is there a requirement to store them as numbers in the first place? Why >> not just store them as a string? >> >> a = '060713' >> > > Yes. I am scripting data entry in a spreadsheet. I can enter the 6 > numbers Six digits, not numbers. > quite rapidly using the number pad but entering the " - "'s to > make it look like a date slows me down. So I thought I would let python > do that for me. > I don't have any experience with using Rxlorg to script the Gemdaddy spreadsheet program. Maybe if you actually got specific, somebody would have familiarity with the ones you're using. Most likely all you have to do is specify with the spreadsheet that the user is to enter a string. If it makes some sort of assumption that strings cannot start with a digit, then it's just broken. In some spreadsheets, the user enter a leading equals-sign to indicate the type of data to follow. -- DaveA From pasokan at talentsprint.com Sun Jun 23 04:15:00 2013 From: pasokan at talentsprint.com (Asokan Pichai) Date: Sun, 23 Jun 2013 07:45:00 +0530 Subject: [Tutor] Data persistence problem In-Reply-To: References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <51C583D0.5040102@pearwood.info> Message-ID: On Sun, Jun 23, 2013 at 2:45 AM, Mark Lawrence wrote: > On 22/06/2013 19:29, Jim Mooney wrote: > >> On 22 June 2013 04:00, Steven D'Aprano wrote: >> >> >> Speaking of Java, I get a kick out of this article and love to link to >>> it on >>> every possible opportunity: >>> >>> http://steve-yegge.blogspot.**com.au/2006/03/execution-in-** >>> kingdom-of-nouns.html >>> >> >> Funny. Speaking of Java, I saw a used book on design patterns, that >> wasn't too old, but all the examples were in Java. Why not just hit >> myself in the head with a brick? >> >> Except for a really old general book, all the recent books on design >> patterns, which I was curious about, are on specific languages - >> design patterns for Java (speak of the devil), Visual Basic, Tcl, even >> Android. But I couldn't fine One on Python. Is there a reason for >> this? Don't they play well with Python, or did I miss the book >> somehow? >> > > Loads of the design pattern stuff is written to help programmers get > around the straight jacket that languages can impose, whereas > implementating the same patterns in Python is often ludicrously easy. > http://norvig.com/design-patterns/ Read this for an insight into how design patterns change for dynamic languages .. Asokan Pichai "Expecting the world to treat you fairly because you are a good person is a little like expecting the bull to not attack you because you are a vegetarian" -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Jun 23 04:24:38 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 23 Jun 2013 12:24:38 +1000 Subject: [Tutor] "farkadoodle" or: unique global names, was Re: Data persistence problem In-Reply-To: <1371931152.54551.YahooMailNeo@web163803.mail.gq1.yahoo.com> References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <51C58620.8090606@pearwood.info> <1371931152.54551.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: <51C65C66.5030703@pearwood.info> On 23/06/13 05:59, Albert-Jan Roskam wrote: > I was playing around with this a bit and arrived at the following surprising (for me at least) result. I thought the global/local/nonlocal keywords could be used to get values from another scope. Though this could also happen implicitly, e.g. if only x = "I am global" is defined and x is used (and not redefined) inside a function, then python still knows this variable inside that function. No, Python does not work that way, unlike (say) Lua where you can write code that fetches a global variable x and assigns it to a local variable x. In Python, the presence of keywords nonlocal and global affect the entire function body, not just lines following them. They're also only needed when you assign to a variable. Looking up the variable's name does not require a declaration. The rule Python follows goes something like this: * If you assign to a name (e.g. "spam = 42") anywhere inside the body of a function, then that name is treated as a local variable, which is a fast lookup. * Otherwise, it is treated as unknown scope, and Python will search nesting functions (if any), globals, and finally builtins for the name. An example: py> import builtins py> builtins.a = "builtins" # Kids, don't do this at home! py> b = c = d = "global" py> def f(): ... c = d = "nonlocal" ... def g(): ... d = "local" ... print(a, b, c, d) ... g() ... py> f() builtins global nonlocal local * If you wish to assign to a variable in another scope, you must declare it. You can only declare global and nonlocal. You cannot declare a variable is builtin (you're not supposed to write to the builtin scope), and there is no way to declare *which* nonlocal function scope you write to. Other than that, you can write to the builtin scope directly, if you import it first, or the global scope by using globals(). But if you're doing either of these things, you probably shouldn't be. Writing to the *local* scope via locals() is not guaranteed to work! It is a lot of fun (for some definition of fun) trying to determine under what circumstances it may or may not work, depending on the version and implementation of Python and even which scope you are in when you call locals(). -- Steven From jacklittlemc at yahoo.com Sun Jun 23 08:18:35 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Sat, 22 Jun 2013 23:18:35 -0700 (PDT) Subject: [Tutor] random.choice() problem Message-ID: <1371968315.93621.YahooMailNeo@web124505.mail.ne1.yahoo.com> I am trying to use random.choice for a text based game. I am using windows 7, 64-bit python. Here is my code: def lvl2(): ? ? print "COMMANDER: Who should you train with?" ? ? trn=random.choice(1,2) ? ? if trn==1: ? ? ? ? lvl2_1() ? ? ? ? print "Squad One!" ? ? elif trn==2: ? ? ? ? lvl2_2() ? ? ? ? print "Squad Nine!" Here is my error: ?File "C:\Users\Jack\Desktop\python\skye.py", line 20, in lvl2 ? ? trn=random.choice(1,2) TypeError: choice() takes exactly 2 arguments (3 given) >>>? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Jun 23 08:55:57 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 23 Jun 2013 16:55:57 +1000 Subject: [Tutor] random.choice() problem In-Reply-To: <1371968315.93621.YahooMailNeo@web124505.mail.ne1.yahoo.com> References: <1371968315.93621.YahooMailNeo@web124505.mail.ne1.yahoo.com> Message-ID: <51C69BFD.40503@pearwood.info> On 23/06/13 16:18, Jack Little wrote: > I am trying to use random.choice for a text based game. I am using windows 7, 64-bit python. Here is my code: > > def lvl2(): > print "COMMANDER: Who should you train with?" > trn=random.choice(1,2) [...] > Here is my error: > > File "C:\Users\Jack\Desktop\python\skye.py", line 20, in lvl2 > trn=random.choice(1,2) > TypeError: choice() takes exactly 2 arguments (3 given) Alas, here you have stumbled over one of those corners of Python where things do not work *quite* as well as they ought to. Even though random.choice looks like a function, it is actually a method, and methods have an extra argument, automatically generated by Python, called "self". So when you call random.choice(1, 2) Python provides three, not two, arguments: self, 1, 2 hence the error message about "3 given". Since random.choice takes two arguments, and Python provides one of them, that only leaves one argument for you to provide. What should that be? Well, if you read the documentation, it tells you. At the interactive interpreter, you can enter help(random.choice) which will give you: Help on method choice in module random: choice(self, seq) method of random.Random instance Choose a random element from a non-empty sequence. Ignoring "self", you have to give a *sequence* of values. A list is a good sequence to use: # Incorrect: random.choice(1, 2) # Correct: random.choice([1, 2]) -- Steven From nsivaram.net at gmail.com Sun Jun 23 11:42:31 2013 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Sun, 23 Jun 2013 15:12:31 +0530 Subject: [Tutor] appending/updating values dict key value pairs References: <878v22f5iv.fsf@gmail.com> Message-ID: <87li61go3c.fsf@gmail.com> On Sun, Jun 23 2013,Alan Gauld wrote: [snipped 21 lines] > But we normally call methods via the object instance rather than the > class so simplifying this further we get: > > b['a'].append('c') > Thanks for the detailed explanation. I've sort of used a dict of this sort {'a': [1,2,'fff'] } in my programs and I've noticed that I've got to unpack the list with hardcoded list positions when I retrieve the value of a key. I think I'd be better off, if I did something of {'a' : ['foo': 1, 'bar':2, 'offset': 'fff'] } wouldn't that be better from a maintainability POV? Are there any examples of such? Or is there a 'struct' option for python? I don't want to use OO methods for now. sivaram -- From steve at pearwood.info Sun Jun 23 12:33:20 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 23 Jun 2013 20:33:20 +1000 Subject: [Tutor] appending/updating values dict key value pairs In-Reply-To: <87li61go3c.fsf@gmail.com> References: <878v22f5iv.fsf@gmail.com> <87li61go3c.fsf@gmail.com> Message-ID: <51C6CEF0.5020403@pearwood.info> On 23/06/13 19:42, Sivaram Neelakantan wrote: > On Sun, Jun 23 2013,Alan Gauld wrote: > > > [snipped 21 lines] > >> But we normally call methods via the object instance rather than the >> class so simplifying this further we get: >> >> b['a'].append('c') >> > > Thanks for the detailed explanation. > > I've sort of used a dict of this sort {'a': [1,2,'fff'] } in my > programs and I've noticed that I've got to unpack the list with > hardcoded list positions when I retrieve the value of a key. > > I think I'd be better off, if I did something of > > {'a' : ['foo': 1, 'bar':2, 'offset': 'fff'] } That won't work; you need to make the inner value a dict using {}, not a list using []. > wouldn't that be better from a maintainability POV? Are there any > examples of such? Or is there a 'struct' option for python? I don't > want to use OO methods for now. Python doesn't have structs in the sense you mean. (But see below for alternatives.) There is a struct module for working with low-level C-style bytes, ints, doubles etc. but that's not what you want. In this case, you can stick with nested dicts: {'a' : {'foo': 1, 'bar':2, 'offset': 'fff'}} It may be less typing if you use this format: {'a': dict(foo=1, bar=2, offset='fff'), 'b': dict(foo=2, bar=6, offset='fe0'), 'c': dict(foo=4, bar=9, offset='d02'), } Instead of working with dicts, it isn't very hard to create your own struct-like class: class MyStruct(object): def __init__(self, foo, bar, offset): self.foo = foo self.bar = bar self.offset = offset A little tedious, but it only needs to be done once, then: {'a': MyStruct(1, 2, 'fff'), 'b': MyStruct(2, 6, 'fe0'), 'c': MyStruct(4, 9, 'd02'), } The advantage is that you can both read and write the attributes: s = MyStruct(4, 9, 'd02') s.foo = 42 print(s.bar) A third alternative is namedtuple, from the collections module. from collections import namedtuple MyStruct = namedtuple('MyStruct', 'foo bar offset') s = MyStruct(4, 9, 'd02') print(s.bar) The advantage here is that namedtuple automatically includes extra "polish", such as printing nicely. The only negative is that namedtuples are immutable: once created, you cannot modify them, you have to create a new one: # this doesn't work s.foo = 42 # instead do this: s = MyStruct(42, s.bar, s.offset) This is deliberate, not a bug. But if you can live with that limitation of namedtuples, then they are the recommended way to get the equivalent of a Pascal record or C struct. Otherwise just create a quick little class as needed. -- Steven From eryksun at gmail.com Sun Jun 23 12:37:07 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 23 Jun 2013 06:37:07 -0400 Subject: [Tutor] appending/updating values dict key value pairs In-Reply-To: <87li61go3c.fsf@gmail.com> References: <878v22f5iv.fsf@gmail.com> <87li61go3c.fsf@gmail.com> Message-ID: On Sun, Jun 23, 2013 at 5:42 AM, Sivaram Neelakantan wrote: > I've sort of used a dict of this sort {'a': [1,2,'fff'] } in my > programs and I've noticed that I've got to unpack the list with > hardcoded list positions when I retrieve the value of a key. > > I think I'd be better off, if I did something of > > {'a' : ['foo': 1, 'bar':2, 'offset': 'fff'] } > > wouldn't that be better from a maintainability POV? Are there any > examples of such? Or is there a 'struct' option for python? I don't > want to use OO methods for now. The correct syntax is a dict of dicts: {'a': {'foo': 1, 'bar': 2, 'offset': 'fff'}} A dict is something of a resource hog, and it's unordered. Use it as the container because it's mutable and lookups are fast, but for the values consider using a namedtuple. It has a smaller footprint, and it's ordered. from collections import namedtuple Record = namedtuple('Record', 'foo bar offset') You can initialize an instance using either positional or keyword arguments: data = { 'a': Record(1, 2, 0xfff), 'b': Record(foo=3, bar=4, offset=0xaaa), } Access the fields by index or attribute: >>> a = data['a']; a[0], a[1], a[2] (1, 2, 4095) >>> b = data['b']; b.foo, b.bar, b.offset (3, 4, 2730) A tuple is immutable, so modifying a field requires a new tuple. Use the _replace method: >>> data['b'] = data['b']._replace(offset=0xbbb) >>> b = data['b']; b.foo, b.bar, b.offset (3, 4, 3003) If you're curious, it's easy to see how namedtuple works: >>> Record = namedtuple('Record', 'foo bar offset', verbose=True) class Record(tuple): 'Record(foo, bar, offset)' __slots__ = () _fields = ('foo', 'bar', 'offset') def __new__(_cls, foo, bar, offset): 'Create new instance of Record(foo, bar, offset)' return _tuple.__new__(_cls, (foo, bar, offset)) ... From davea at davea.name Sun Jun 23 12:46:40 2013 From: davea at davea.name (Dave Angel) Date: Sun, 23 Jun 2013 06:46:40 -0400 Subject: [Tutor] random.choice() problem In-Reply-To: <1371968315.93621.YahooMailNeo@web124505.mail.ne1.yahoo.com> References: <1371968315.93621.YahooMailNeo@web124505.mail.ne1.yahoo.com> Message-ID: <51C6D210.8060309@davea.name> On 06/23/2013 02:18 AM, Jack Little wrote: > I am trying to use random.choice for a text based game. I am using windows 7, 64-bit python. Here is my code: > > def lvl2(): > print "COMMANDER: Who should you train with?" > trn=random.choice(1,2) > if trn==1: > lvl2_1() > print "Squad One!" > elif trn==2: > lvl2_2() > print "Squad Nine!" > > > > > > Here is my error: > > File "C:\Users\Jack\Desktop\python\skye.py", line 20, in lvl2 > trn=random.choice(1,2) > TypeError: choice() takes exactly 2 arguments (3 given) >>>> > > > You don't say what version of Python you're using, but I'll assume 2.7 Steven's answer is correct, but here's another option: trn = random.randint(1,2) Here, the 1 and 2 are separate arguments delimiting a range of integer values. Note that it includes both end points, unlike the xrange function. Alternatively, you could use trn = random.randrange(1,3) To make the above clearer, suppose you wanted an int value between 1 and 20, inclusive. You could do that at least four ways: trn = random.choice([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) trn = random.choice(range(1, 21)) trn = random.randint(1, 20) trn = random.randrange(1, 21) -- DaveA From __peter__ at web.de Sun Jun 23 13:19:11 2013 From: __peter__ at web.de (Peter Otten) Date: Sun, 23 Jun 2013 13:19:11 +0200 Subject: [Tutor] random.choice() problem References: <1371968315.93621.YahooMailNeo@web124505.mail.ne1.yahoo.com> <51C6D210.8060309@davea.name> Message-ID: Dave Angel wrote: > On 06/23/2013 02:18 AM, Jack Little wrote: >> I am trying to use random.choice for a text based game. I am using >> windows 7, 64-bit python. Here is my code: >> >> def lvl2(): >> print "COMMANDER: Who should you train with?" >> trn=random.choice(1,2) >> if trn==1: >> lvl2_1() >> print "Squad One!" >> elif trn==2: >> lvl2_2() >> print "Squad Nine!" >> Here is my error: >> >> File "C:\Users\Jack\Desktop\python\skye.py", line 20, in lvl2 >> trn=random.choice(1,2) >> TypeError: choice() takes exactly 2 arguments (3 given) > Steven's answer is correct, but here's another option: > > trn = random.randint(1,2) > > Here, the 1 and 2 are separate arguments delimiting a range of integer > values. Note that it includes both end points, unlike the xrange > function. Here's yet another option: if you move the print statements into the lvl2_...() functions you can simplify your code by choosing the function directly: >>> import random >>> def level2_1(): ... # ... ... print "Squad One!" ... >>> def level2_2(): ... # ... ... print "Squad Nine!" ... >>> def level2(): ... print "COMMANDER: Who should you train with?" ... level2_x = random.choice([level2_1, level2_2]) ... level2_x() ... >>> level2() COMMANDER: Who should you train with? Squad One! >>> level2() COMMANDER: Who should you train with? Squad Nine! >>> level2() COMMANDER: Who should you train with? Squad Nine! From nsivaram.net at gmail.com Sun Jun 23 15:40:26 2013 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Sun, 23 Jun 2013 19:10:26 +0530 Subject: [Tutor] appending/updating values dict key value pairs References: <878v22f5iv.fsf@gmail.com> <87li61go3c.fsf@gmail.com> <51C6CEF0.5020403@pearwood.info> Message-ID: <87vc559c8l.fsf@gmail.com> On Sun, Jun 23 2013,Steven D'Aprano wrote: > On 23/06/13 19:42, Sivaram Neelakantan wrote: [snipped 28 lines] > Python doesn't have structs in the sense you mean. (But see below > for alternatives.) There is a struct module for working with > low-level C-style bytes, ints, doubles etc. but that's not what you > want. > > In this case, you can stick with nested dicts: > > {'a' : {'foo': 1, 'bar':2, 'offset': 'fff'}} > > > It may be less typing if you use this format: > > {'a': dict(foo=1, bar=2, offset='fff'), > 'b': dict(foo=2, bar=6, offset='fe0'), > 'c': dict(foo=4, bar=9, offset='d02'), > } > > > Instead of working with dicts, it isn't very hard to create your own > struct-like class: > > > class MyStruct(object): > def __init__(self, foo, bar, offset): > self.foo = foo > self.bar = bar > self.offset = offset > > > A little tedious, but it only needs to be done once, then: > > {'a': MyStruct(1, 2, 'fff'), > 'b': MyStruct(2, 6, 'fe0'), > 'c': MyStruct(4, 9, 'd02'), > } > > The advantage is that you can both read and write the attributes: > > s = MyStruct(4, 9, 'd02') > s.foo = 42 > print(s.bar) > > > A third alternative is namedtuple, from the collections module. > > > from collections import namedtuple > > MyStruct = namedtuple('MyStruct', 'foo bar offset') > s = MyStruct(4, 9, 'd02') > print(s.bar) > > > The advantage here is that namedtuple automatically includes extra > "polish", such as printing nicely. The only negative is that > namedtuples are immutable: once created, you cannot modify them, you > have to create a new one: > > # this doesn't work > s.foo = 42 > # instead do this: > s = MyStruct(42, s.bar, s.offset) > > > This is deliberate, not a bug. But if you can live with that > limitation of namedtuples, then they are the recommended way to get > the equivalent of a Pascal record or C struct. Otherwise just create > a quick little class as needed. Thank you for explaining the options, I'd probably go with namedtuple as it seems to match my needs and I don't want to work on OO/Classes for now. I'll read up on the documentation for namedtuple. sivaram -- From nsivaram.net at gmail.com Sun Jun 23 15:43:41 2013 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Sun, 23 Jun 2013 19:13:41 +0530 Subject: [Tutor] appending/updating values dict key value pairs References: <878v22f5iv.fsf@gmail.com> <87li61go3c.fsf@gmail.com> Message-ID: <87r4ft9c36.fsf@gmail.com> On Sun, Jun 23 2013,eryksun wrote: [snipped 14 lines] > The correct syntax is a dict of dicts: > > {'a': {'foo': 1, 'bar': 2, 'offset': 'fff'}} > > A dict is something of a resource hog, and it's unordered. Use it as > the container because it's mutable and lookups are fast, but for the > values consider using a namedtuple. It has a smaller footprint, and > it's ordered. > > from collections import namedtuple > > Record = namedtuple('Record', 'foo bar offset') > > You can initialize an instance using either positional or keyword arguments: > > data = { > 'a': Record(1, 2, 0xfff), > 'b': Record(foo=3, bar=4, offset=0xaaa), > } > > Access the fields by index or attribute: > > >>> a = data['a']; a[0], a[1], a[2] > (1, 2, 4095) > > >>> b = data['b']; b.foo, b.bar, b.offset > (3, 4, 2730) > > A tuple is immutable, so modifying a field requires a new tuple. Use > the _replace method: > > >>> data['b'] = data['b']._replace(offset=0xbbb) > > >>> b = data['b']; b.foo, b.bar, b.offset > (3, 4, 3003) > > > If you're curious, it's easy to see how namedtuple works: > > >>> Record = namedtuple('Record', 'foo bar offset', verbose=True) > class Record(tuple): > 'Record(foo, bar, offset)' > > __slots__ = () > > _fields = ('foo', 'bar', 'offset') > > def __new__(_cls, foo, bar, offset): > 'Create new instance of Record(foo, bar, offset)' > return _tuple.__new__(_cls, (foo, bar, offset)) [snipped 6 lines] Thanks for the explanation, I'd go with namedtuple as recommended. sivaram -- From jf_byrnes at comcast.net Sun Jun 23 18:43:20 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Sun, 23 Jun 2013 11:43:20 -0500 Subject: [Tutor] How convert an int to a string In-Reply-To: <51C6321D.6080400@davea.name> References: <20130622221042.GC22060@wdfs.graniteweb.com> <51C6321D.6080400@davea.name> Message-ID: On 06/22/2013 06:24 PM, Dave Angel wrote: > On 06/22/2013 07:03 PM, Jim Byrnes wrote: >> On 06/22/2013 05:10 PM, David Rock wrote: >>> * Jim Byrnes [2013-06-22 16:01]: >>>> I need to convert a series of digits like 060713 to a string so I can >>>> make it look like a date 06-07-13. >>>> >>>> >>> a = 060713 >>>> >>> a[:2] >>>> Traceback (most recent call last): >>>> File "", line 1, in >>>> TypeError: 'int' object has no attribute '__getitem__' >>>> >>> b = str(a) >>>> >>> b[:2] >>>> '25' >>>> >>> b >>>> '25035' >>>> >>> >>>> >>>> I was confused at first but then realized that the 0 makes it >>>> octal. I >>>> thought str() would do it but it didn't. Reading about str() it >>>> talks of >>>> string representation. So how can I convert it to a true string I can >>>> slice and build my date look a like? >>> >>> Is there a requirement to store them as numbers in the first place? Why >>> not just store them as a string? >>> >>> a = '060713' >>> >> >> Yes. I am scripting data entry in a spreadsheet. I can enter the 6 >> numbers > > Six digits, not numbers. > >> quite rapidly using the number pad but entering the " - "'s to >> make it look like a date slows me down. So I thought I would let python >> do that for me. >> > > I don't have any experience with using Rxlorg to script the Gemdaddy > spreadsheet program. Maybe if you actually got specific, somebody would > have familiarity with the ones you're using. It is Calligrsheets. I didn't mention it because I was focused on the python error message I was seeing. Python version is 2.7.3. > Most likely all you have to do is specify with the spreadsheet that the > user is to enter a string. If it makes some sort of assumption that > strings cannot start with a digit, then it's just broken. I can set the cell contents as text or numeric and I can extract the info either as a string or an int. Each method gives it own error. The code is short so I will post it. def regionChanged(regions): """ In column A. Converts data entered as mmddyy to mm-dd-yy """ myCell = viewer.selection() print myCell if myCell[0] - 1 == 1: #cell_value = sheet.text(myCell[0] - 1, myCell[1]) #[1] cell_value = sheet.value(myCell[0] - 1, myCell[1]) #[2] print 'Type is ', type(cell_value) cell_value = cell_value[:2] + '-' + cell_value[2:4] + '-' + cell_value[4:] print 'Cell value is ', cell_value cell_name = sheet.cellName(myCell[0] - 1, myCell[1]) writer.setCell(cell_name) writer.setValue(cell_name, cell_value) viewer.setSelection([2, myCell[1], 1, 1]) [1] cell_value will always be a string. [2] cell_value will be a string or a long depending on cell type. Here is the output from the terminal. Note: Kross is the plugin that enables Python scripting. ### code from [1], cell type = text ### Kross: "PythonScript::Constructor." Kross: "PythonScript::execute" Kross: "PythonScript::execute result=None" [2, 5, 1, 1] Type is Cell value is 06-25-13 Kross: "PythonInterpreter::extractException: " Kross: "PythonExtension::proxyhandler Had exception on line -1: invalid literal for int() with base 10: '06-25-13' " ValueError: invalid literal for int() with base 10: '06-25-13' Kross: "PythonScript::Destructor." ### code from [2], cell type = text ### Kross: "PythonScript::Constructor." Kross: "PythonScript::execute" Kross: "PythonScript::execute result=None" [2, 5, 1, 1] Type is Cell value is 06-25-13 Kross: "PythonInterpreter::extractException: " Kross: "PythonExtension::proxyhandler Had exception on line -1: invalid literal for int() with base 10: '06-25-13' " ValueError: invalid literal for int() with base 10: '06-25-13' Kross: "PythonScript::Destructor." ### code [1], cell type = numeric ### Kross: "PythonScript::Constructor." Kross: "PythonScript::execute" Kross: "PythonScript::execute result=None" [2, 5, 1, 1] Type is Cell value is 06-25-13 Kross: "PythonInterpreter::extractException: " Kross: "PythonExtension::proxyhandler Had exception on line -1: invalid literal for int() with base 10: '06-25-13' " ValueError: invalid literal for int() with base 10: '06-25-13' Kross: "PythonScript::Destructor." ### code [2], cell type numeric ### Kross: "PythonScript::Constructor." Kross: "PythonScript::execute" Kross: "PythonScript::execute result=None" [2, 5, 1, 1] Type is Kross: "PythonInterpreter::extractException: File "file:///home/jfb/.kde/share/apps/sheets/scripts/enter_invoices.py", line 38, in regionChanged " TypeError: 'long' object has no attribute '__getitem__' Kross: "PythonScript::Destructor." Regards, Jim From abhagat at seti.org Tue Jun 18 01:58:57 2013 From: abhagat at seti.org (Anu Bhagat) Date: Mon, 17 Jun 2013 16:58:57 -0700 Subject: [Tutor] Unix Environment variables Message-ID: <51BFA2C1.9030300@seti.org> Hi I am fairly new to python. I will greatly appreciate if some one can tell me how set up environment variables from a python script. Thanks in advance. Anu -- Nothing is impossible, the word itself says 'I'm possible'. Audrey Hepburn Anu Bhagat SETI Institute 189 North Bernardo Street Mountain View, CA 94043-5203 Phone : 650.960.4592 Fax : 650.960.5830 From andycooper47 at btinternet.com Mon Jun 17 23:06:08 2013 From: andycooper47 at btinternet.com (Andrew Cooper) Date: Mon, 17 Jun 2013 22:06:08 +0100 (BST) Subject: [Tutor] Python 2 or 3? Message-ID: <1371503168.60924.YahooMailNeo@web186102.mail.ir2.yahoo.com> Dear Pythoners, Sorry I am completely new to this but so far as I can see there are two versions of Python, version 2 (which is more established and has much more support) and version 3 which is relatively new. As a beginner, which of the versions (2 or 3) would it be advisable to start with first? I suspect version 2, but I would like to hear that from experienced Python users. Many thanks, Andy Cooper -------------- next part -------------- An HTML attachment was scrubbed... URL: From fabiosantosart at gmail.com Sun Jun 16 19:45:41 2013 From: fabiosantosart at gmail.com (=?ISO-8859-1?Q?F=E1bio_Santos?=) Date: Sun, 16 Jun 2013 18:45:41 +0100 Subject: [Tutor] How to find descendants recursively? In-Reply-To: References: Message-ID: On Sun, Jun 16, 2013 at 6:20 PM, Timo wrote: > I have a datafile which is parsed by an external library, I'm having trouble > creating a hierarchical structure of the data. > > This is what I got so far: > > items = get_items() # returns a generator > for item in items: > print(item) > children = get_children(item) # also returns a generator > for child in children: > print("--", child) > > This is fine as it will get the children for each parent item. I can't seem > to figure out how to go further and get the chidren of the children and so > on. > > Thanks. > Use recursion to sort this out. Recursion is the technique of calling the same function you are in, and it's very useful for tree traversal problems like this one. def recurse_items(items, dash_count=0): for item in items: print(('-' * dash_count) + str(item)) children = get_children(item) # also returns a generator if children: recurse_items(children, dash_count + 1) recurse_items(items) I added a "dash_count" to the mix, so you can see an example of how to keep track of the level you are in on the tree. Hope I was of some help. Cheers! -- F?bio Santos From fabiosantosart at gmail.com Fri Jun 21 12:00:48 2013 From: fabiosantosart at gmail.com (=?ISO-8859-1?Q?F=E1bio_Santos?=) Date: Fri, 21 Jun 2013 11:00:48 +0100 Subject: [Tutor] Data persistence problem In-Reply-To: References: Message-ID: On 21 Jun 2013 07:36, "Arijit Ukil" wrote: > > I have following random number generation function > > def rand_int (): > rand_num = int(math.ceil (random.random()*1000)) > return rand_num > > I like to make the value of rand_num (return of rand_int) static/ unchanged after first call even if it is called multiple times. If x= rand_int () returns 45 at the first call, x should retain 45 even in multiple calls. > Pls help. > Use a variable. _the_num = random.randint(......) def rand_int(): return _the_num -------------- next part -------------- An HTML attachment was scrubbed... URL: From iliketurtles.jm at googlemail.com Wed Jun 19 17:58:21 2013 From: iliketurtles.jm at googlemail.com (Jack Mcgarry) Date: Wed, 19 Jun 2013 16:58:21 +0100 Subject: [Tutor] python error Message-ID: Hello ,I am contacting you because I have this bug with my python that needs solving. You see i coded this program when i was learning to do graphical coding (still am) and i was using pygame, you may be familiar with this program it is called skier. i clicked "run module" and ran skier but when it ran this error came up: Traceback (most recent call last): File "C:\Python27\skier1.py", line 1, in import pygame, sys, random File "C:\Python27\pygame\__init__.py", line 95, in from pygame.base import * ImportError: DLL load failed: %1 is not a valid Win32 application. my computer is 64bit and windows 7 im using python 2.7 (64bit) can you help? -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at johnharris.tv Sun Jun 16 17:57:00 2013 From: john at johnharris.tv (John Harris) Date: Sun, 16 Jun 2013 16:57:00 +0100 Subject: [Tutor] 2 basic problems Message-ID: Hi Charles, I have added some comments below explaining why you are not getting the results you expect: >>> 4+4 8 The above is an expression, when you hit enter python will evaluate it and give the answer. >>> 3+3=4 SyntaxError: can't assign to operator >>> 3=1 SyntaxError: can't assign to literal > I thought the last 2 lines should return False This is an assignment statement, the single '=' means when you hit enter python will try to set the value of one side to the other. Hence the assignment error. Instead try: >>> 3+3==4 False >>> 3==1 False -------- lot=('1'+'6'+'8') print(lot) a=open("acc","w") a.write(lot) a.close b=open("acc","r") b.read() print (b) b.close returns >>> 168 >>> Firstly your .close methods need to have parens to actually call the method. So instead of a.close we need a.close() Then your b.read() line will work, I get the output '168' when I call b.read(). Lastly, the line b = open("acc", "r") creates a new file object (b). From the docs: "Open a file, returning an object of the file type." Therefore when you print(b) python will call the __repr__() method of the file object which is why you see the line . John -------------- next part -------------- An HTML attachment was scrubbed... URL: From lu.nemec at gmail.com Mon Jun 17 16:17:59 2013 From: lu.nemec at gmail.com (Lukas Nemec) Date: Mon, 17 Jun 2013 16:17:59 +0200 Subject: [Tutor] looking for volunteers with testing simple python program Message-ID: <51BF1A97.6000404@gmail.com> Hello, I changed some simple python client/server chatroom recipe to include RSA keypair based encryption and signature verification because I'm sick of someone spying on my conversations on FB and similar. Here is the code: https://github.com/lunemec/python-chat If anyone is interrested in trying the software - mostly bughunting and improvements please run these commands after downloading the source codes: cd client |openssl genrsa -out your_cert_name.pem -des3 4096 ||openssl rsa -pubout -in yourt_cert_name.pem -passin pass:"yourpassword" -out your_chatroom_nick.pub ## After this step, please send me your_chatroom_nick.pub file, it should have the same name.pub as you want to use in the chatroom, otherwise we can't decrypt your messages # if you don't have pycrypt, then sudo pip install pycrypto python client.py your_chatroom_nick nemec.lu 3490 your_cert_name.pem yourpassword Now we should be able to chat :) Enjoy, and please don't kill me for writing here :) Lukas | -------------- next part -------------- An HTML attachment was scrubbed... URL: From lu.nemec at gmail.com Mon Jun 17 20:20:50 2013 From: lu.nemec at gmail.com (=?UTF-8?B?THVrw6HFoSBOxJttZWM=?=) Date: Mon, 17 Jun 2013 20:20:50 +0200 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51BF52B5.1050902@davea.name> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> Message-ID: <51BF5382.2040608@gmail.com> Dne 17. 6. 2013 20:17, Dave Angel napsal(a): > On 06/17/2013 01:36 PM, Matt D wrote: >> Hey, >> I wrote some simple code to write data to a logfile and it works pretty >> well (thanks guys). Now my problem is that every time i run the program >> the old logfile.txt is overwritten. I need to be able to stop and start >> the program without overwriting, or losing, the old data. here is the >> relavent code: >> >> # central part of the program >> # lays out the GUI panel >> # omitted lots for our purposes here >> Class panel(wx.Panel): >> >> # open a file named "logfile.txt" in "w" writing mode. >> # this will create the file if it doesn't exist. >> self.logfile = open('logfile.txt', 'w') >> >> # Updates the TextCtrl field values >> # and logs TextCtrl field values >> def update(self, field_values): >> >> #logger code--------------- >> #first write the CURRENT date/time >> self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", >> gmtime())))) >> # loop through each of the TextCtrl objects >> for k,v in self.fields.items(): >> #get the value of the current TextCtrl field >> f = field_values.get(k, None) >> if f: >> #output the value with trailing comma >> self.logfile.write('%s,'%(str(f))) >> self.logfile.write('\n') >> #end logger code ---------------- >> >> In addition to not deleting the old data, it would be awesome to have >> some sort of wxPython widget that would give the user the ability to >> 'save as', or name and save the file, from the GUI panel. >> Thanks! >> > > Clearly you didn't absorb or act on much of the advice from the last > time. So this time I'll just give you a brief hint. > > Don't use write mode when opening the file. Find the docs on open(), > and see what other choices there are. > > > Or even better, use python moto, dont re-invent the wheel, so use built in library logging, read the docs for it, or if you want, I can send you some examples how to work it, it takes some time to figure out properly... From lu.nemec at gmail.com Wed Jun 19 08:59:03 2013 From: lu.nemec at gmail.com (Lukas Nemec) Date: Wed, 19 Jun 2013 08:59:03 +0200 Subject: [Tutor] EXE Problem In-Reply-To: <1371624655.61616.YahooMailNeo@web124504.mail.ne1.yahoo.com> References: <1371624655.61616.YahooMailNeo@web124504.mail.ne1.yahoo.com> Message-ID: <51C156B7.4030500@gmail.com> Do Win+R type: cmd hit enter. in the opened cmd write cd C:/where/you/have/the/exe (you can move it to C: for simplicity) and run it from there it will not close this time, and you can see the debugging info. Enjoy. On 06/19/2013 08:50 AM, Jack Little wrote: > I compiled a program in python, but the second I open it, there is a > flash of the error, but then the cmd window closes. > > > _______________________________________________ > 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 wvd8 at cdc.gov Mon Jun 17 16:26:03 2013 From: wvd8 at cdc.gov (Jacobs, Teri (CDC/NIOSH/DSHEFS) (CTR)) Date: Mon, 17 Jun 2013 14:26:03 +0000 Subject: [Tutor] Help with Python in ArcGIS 10.1! Message-ID: <1EB2BA350028DF42B1CB289EDDD10549209F7BA4@EMBX-CHAM2.cdc.gov> Hi, I have a command line to spread geoprocessing operations across multiple processes to speed up performance. However, I do not know how to import the command line (or at least import it properly) in Python 2.7.2. Here's the script example given on ArcGIS 10.1 Help: import arcpy # Use half of the cores on the machine. arcpy.env.parallelProcessingFactor = "50%" I tried typing it into the command line but nothing happened. Instructions would be much appreciated!!! Teri A. Jacobs Geography Fellow Surveillance Branch/DSHEFS/NIOSH/CDC 513-841-4338 WVD8 at cdc.gov -------------- next part -------------- An HTML attachment was scrubbed... URL: From zagheni at yahoo.com Fri Jun 21 00:10:16 2013 From: zagheni at yahoo.com (Antonio Zagheni) Date: Thu, 20 Jun 2013 19:10:16 -0300 Subject: [Tutor] Help Message-ID: <69416018-7813-43AC-91B1-02316FAC6F8E@yahoo.com> Hi there, I am a begginer in Python. I did a function that returns a string and I want to copy this to the clipboard. I have tried a lot of suggestions found at Google but nothing works properly. Is there an easy way to do that? I am using Python 2.7 and Windows 7. Thanks a lot. Antonio Zagheni. From amitsaha.in at gmail.com Sun Jun 23 23:35:47 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Mon, 24 Jun 2013 07:35:47 +1000 Subject: [Tutor] Unix Environment variables In-Reply-To: <51BFA2C1.9030300@seti.org> References: <51BFA2C1.9030300@seti.org> Message-ID: Hello, On Tue, Jun 18, 2013 at 9:58 AM, Anu Bhagat wrote: > Hi I am fairly new to python. I will greatly appreciate if some one can tell > me how set up environment variables from a python script. > > Thanks in advance. You can use the 'os' module. This is the document for Python 2 [1]. That should help you retrieving/setting environment variables. [1] http://docs.python.org/2/library/os.html#os.environ Best, Amit. > > Anu > -- > Nothing is impossible, the word itself says 'I'm possible'. Audrey Hepburn > > Anu Bhagat > SETI Institute > 189 North Bernardo Street > Mountain View, CA 94043-5203 > Phone : 650.960.4592 > Fax : 650.960.5830 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- http://echorand.me From rhettnaxel at gmail.com Sun Jun 23 23:41:59 2013 From: rhettnaxel at gmail.com (Alexander) Date: Sun, 23 Jun 2013 17:41:59 -0400 Subject: [Tutor] python error In-Reply-To: References: Message-ID: On Wed, Jun 19, 2013 at 11:58 AM, Jack Mcgarry < iliketurtles.jm at googlemail.com> wrote: > Hello ,I am contacting you because I have this bug with my python that > needs solving. You see i coded this program when i was learning to do > graphical coding (still am) and i was using pygame, you may be familiar > with this program it is called skier. i clicked "run module" and ran skier > but when it ran this error came up: Traceback (most recent call last): > File "C:\Python27\skier1.py", line 1, in > import pygame, sys, random > File "C:\Python27\pygame\__init__.py", line 95, in > from pygame.base import * > ImportError: DLL load failed: %1 is not a valid Win32 application. > > my computer is 64bit and windows 7 im using python 2.7 (64bit) > > can you help? > > yes submit your code > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Alexander Etter -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhettnaxel at gmail.com Sun Jun 23 23:46:32 2013 From: rhettnaxel at gmail.com (Alexander) Date: Sun, 23 Jun 2013 17:46:32 -0400 Subject: [Tutor] looking for volunteers with testing simple python program In-Reply-To: <51BF1A97.6000404@gmail.com> References: <51BF1A97.6000404@gmail.com> Message-ID: On Mon, Jun 17, 2013 at 10:17 AM, Lukas Nemec wrote: > Hello, > > I changed some simple python client/server chatroom recipe > to include RSA keypair based encryption and signature verification > > because I'm sick of someone spying on my conversations on FB and similar. > > Here is the code: > > https://github.com/lunemec/python-chat > > If anyone is interrested in trying the software - mostly bughunting and > improvements > > please run these commands after downloading the source codes: > > cd client > openssl genrsa -out your_cert_name.pem -des3 4096 > openssl rsa -pubout -in yourt_cert_name.pem -passin > pass:"yourpassword" -out your_chatroom_nick.pub > > ## After this step, please send me your_chatroom_nick.pub file, it should > have the same name.pub as you want to use in the chatroom, otherwise we > can't decrypt your messages > > # if you don't have pycrypt, then sudo pip install pycrypto > python client.py your_chatroom_nick nemec.lu 3490 your_cert_name.pem > yourpassword > > Now we should be able to chat :) > > Enjoy, and please don't kill me for writing here :) > > Lukas > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > I guess this is for testing, but I have a question. If somebody sends you their .pub file (email or otherwise over internet), and a villainous third party intercepts that .pub file, will they be able to decrypt the data sent over this program? Thanks. -- Alexander -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Sun Jun 23 23:48:20 2013 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 23 Jun 2013 14:48:20 -0700 Subject: [Tutor] Unix Environment variables In-Reply-To: References: <51BFA2C1.9030300@seti.org> Message-ID: Note, however, that changing environment variables only affects the environment of your script and it's child processes. Once your script exits, the original shell you called it from is NOT changed. Sent from my iPad On 2013/6/23, at 14:35, Amit Saha wrote: > Hello, > > On Tue, Jun 18, 2013 at 9:58 AM, Anu Bhagat wrote: >> Hi I am fairly new to python. I will greatly appreciate if some one can tell >> me how set up environment variables from a python script. >> >> Thanks in advance. > > You can use the 'os' module. This is the document for Python 2 [1]. > That should help you retrieving/setting environment variables. > > [1] http://docs.python.org/2/library/os.html#os.environ > > Best, > Amit. > >> >> Anu >> -- >> Nothing is impossible, the word itself says 'I'm possible'. Audrey Hepburn >> >> Anu Bhagat >> SETI Institute >> 189 North Bernardo Street >> Mountain View, CA 94043-5203 >> Phone : 650.960.4592 >> Fax : 650.960.5830 >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > > -- > http://echorand.me > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sun Jun 23 23:56:50 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 23 Jun 2013 22:56:50 +0100 Subject: [Tutor] Just flushed the queue hence the old mails. Message-ID: -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From eryksun at gmail.com Mon Jun 24 00:18:11 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 23 Jun 2013 18:18:11 -0400 Subject: [Tutor] Help In-Reply-To: <69416018-7813-43AC-91B1-02316FAC6F8E@yahoo.com> References: <69416018-7813-43AC-91B1-02316FAC6F8E@yahoo.com> Message-ID: On Thu, Jun 20, 2013 at 6:10 PM, Antonio Zagheni wrote: > > I am a begginer in Python. > I did a function that returns a string and I want to copy this to the clipboard. > I have tried a lot of suggestions found at Google but nothing works properly. > Is there an easy way to do that? > I am using Python 2.7 and Windows 7. It's simple to access the clipboard with Tkinter: >>> from Tkinter import Tk, TclError >>> root = Tk() >>> root.withdraw() '' >>> root.clipboard_clear() >>> root.clipboard_append('eggs ') >>> root.clipboard_append('and spam') >>> root.clipboard_get() 'eggs and spam' >>> root.clipboard_clear() >>> try: root.clipboard_get() ... except TclError as e: print e ... CLIPBOARD selection doesn't exist or form "STRING" not defined From bgailer at gmail.com Mon Jun 24 01:41:12 2013 From: bgailer at gmail.com (bob gailer) Date: Sun, 23 Jun 2013 19:41:12 -0400 Subject: [Tutor] Help with Python in ArcGIS 10.1! In-Reply-To: <1EB2BA350028DF42B1CB289EDDD10549209F7BA4@EMBX-CHAM2.cdc.gov> References: <1EB2BA350028DF42B1CB289EDDD10549209F7BA4@EMBX-CHAM2.cdc.gov> Message-ID: <51C78798.5050608@gmail.com> On 6/17/2013 10:26 AM, Jacobs, Teri (CDC/NIOSH/DSHEFS) (CTR) wrote: > > Hi, > Hi - welcome to the tutor list. Be aware that we are a few volunteers. Your question is one very long line. Please in future ensure it is wrapped so we don't have to scroll. I have wrapped it here. > > I have a command line What is a "command line"? > to spread geoprocessing operations across multiple processes > to speed up performance. However, I do not > know how to import the command line (or at least import it properly) > in Python 2.7.2. Here's the script example given on ArcGIS 10.1 Help: > > import arcpy > > # Use half of the cores on the machine. > > arcpy.env.parallelProcessingFactor = "50%" > > I tried typing it > What is "it". You show 3 lines of code above. Do you mean all 3 lines? > > into the command line > What is "the command line"? Do you mean Command Prompt or Python shell? > > but nothing happened. > What did you expect? Did you hit enter after each line? Did the cursor move to the next line? Did you get another prompt? What did the prompt look like? I think you get the idea - you need to tell us more, since we did not watch you try the above. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolfrage8765 at gmail.com Mon Jun 24 01:46:37 2013 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Sun, 23 Jun 2013 19:46:37 -0400 Subject: [Tutor] Python 2 or 3? In-Reply-To: <1371503168.60924.YahooMailNeo@web186102.mail.ir2.yahoo.com> References: <1371503168.60924.YahooMailNeo@web186102.mail.ir2.yahoo.com> Message-ID: <3afbeae5-e6f5-4962-adf4-40f531ee5cb8.maildroid@localhost> Personally. I say 3, because support for external modules is growing every day and only a few major modules remain, like twisted. But 3 will soon be the standard so start to learn on it now and you will not need to transition latter when 3 replaces 2 as the standard. I currently use 3 and only miss twisted. Sent from my android device. -----Original Message----- From: Andrew Cooper To: "tutor at python.org" Sent: Sun, 23 Jun 2013 5:31 PM Subject: [Tutor] Python 2 or 3? Dear Pythoners, Sorry I am completely new to this but so far as I can see there are two versions of Python, version 2 (which is more established and has much more support) and version 3 which is relatively new. As a beginner, which of the versions (2 or 3) would it be advisable to start with first? I suspect version 2, but I would like to hear that from experienced Python users. Many thanks, Andy Cooper -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Jun 24 01:49:03 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 24 Jun 2013 00:49:03 +0100 Subject: [Tutor] Python 2 or 3? In-Reply-To: <1371503168.60924.YahooMailNeo@web186102.mail.ir2.yahoo.com> References: <1371503168.60924.YahooMailNeo@web186102.mail.ir2.yahoo.com> Message-ID: On 17/06/2013 22:06, Andrew Cooper wrote: > Dear Pythoners, > Sorry I am completely new to this but so far as I can see there are two > versions of Python, version 2 (which is more established and has much > more support) and version 3 which is relatively new. > As a beginner, which of the versions (2 or 3) would it be advisable to > start with first? > I suspect version 2, but I would like to hear that from experienced > Python users. > Many thanks, > Andy Cooper > Version 3 unless you must use a library that's not yet ported, as it saves you porting your code at a later date. -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From davea at davea.name Mon Jun 24 01:50:49 2013 From: davea at davea.name (Dave Angel) Date: Sun, 23 Jun 2013 19:50:49 -0400 Subject: [Tutor] How convert an int to a string In-Reply-To: References: <20130622221042.GC22060@wdfs.graniteweb.com> <51C6321D.6080400@davea.name> Message-ID: <51C789D9.5020505@davea.name> On 06/23/2013 12:43 PM, Jim Byrnes wrote: > On 06/22/2013 06:24 PM, Dave Angel wrote: >> On 06/22/2013 07:03 PM, Jim Byrnes wrote: >>> On 06/22/2013 05:10 PM, David Rock wrote: >>>> * Jim Byrnes [2013-06-22 16:01]: >>>>> I need to convert a series of digits like 060713 to a string so I can >>>>> make it look like a date 06-07-13. >>>>> >>>>> >>> a = 060713 >>>>> >>> a[:2] >>>>> Traceback (most recent call last): >>>>> File "", line 1, in >>>>> TypeError: 'int' object has no attribute '__getitem__' >>>>> >>> b = str(a) >>>>> >>> b[:2] >>>>> '25' >>>>> >>> b >>>>> '25035' >>>>> >>> >>>>> >>>>> I was confused at first but then realized that the 0 makes it >>>>> octal. I In Python source code. But the date number is being entered into the spreadsheet, so the leading zero means no such thing. It also means no such thing when a strictly Python program does something like: x = int(raw_input()) This is why context is so important. >>>>> thought str() would do it but it didn't. Reading about str() it >>>>> talks of >>>>> string representation. So how can I convert it to a true string I can >>>>> slice and build my date look a like? >>>> >>>> Is there a requirement to store them as numbers in the first place? >>>> Why >>>> not just store them as a string? >>>> >>>> a = '060713' >>>> >>> >>> Yes. I am scripting data entry in a spreadsheet. I can enter the 6 >>> numbers >> >> Six digits, not numbers. >> >>> quite rapidly using the number pad but entering the " - "'s to >>> make it look like a date slows me down. So I thought I would let python >>> do that for me. >>> >> >> I don't have any experience with using Rxlorg to script the Gemdaddy >> spreadsheet program. Maybe if you actually got specific, somebody would >> have familiarity with the ones you're using. > > It is Calligrsheets. I can't find any such thing. Do you perhaps mean Calligra Sheets, at http://www.calligra.org/sheets/ ??? If so, I'm having trouble finding any information on the internet about scripting it, in Python or otherwise. It is available on Ubuntu's "Software Centre," but the only review was rather negative. Using what to interface to it? I'll assume that's what's called Kross below. I'll also have to make wild guesses about the available functions and methods that Kross gives you. Like do you have to use writer.setValue() for both ints and strings, or does it have separate function calls? Does it have one for setting dates? Perhaps string is the wrong type entirely. I can't find any information on the web about scripting Calligra. If there's no installed help either, I'd find something with better docs. > I didn't mention it because I was focused on the > python error message I was seeing. Python version is 2.7.3. But you don't have a Python error message. It's missing the most important parts, the traceback. Something has intercepted that exception and printed only a summary. And specified a line number of negative-one, which isn't reasonable either. If the try/except is your own, then either fix the display or temporarily disable the try. If the try/except is in the "Kross" code, and you have access to it, then see what it looks like in the appropriate place. > >> Most likely all you have to do is specify with the spreadsheet that the >> user is to enter a string. If it makes some sort of assumption that >> strings cannot start with a digit, then it's just broken. > > I can set the cell contents as text or numeric and I can extract the > info either as a string or an int. Each method gives it own error. The > code is short so I will post it. > > def regionChanged(regions): > """ In column A. Converts data entered as mmddyy to mm-dd-yy """ > myCell = viewer.selection() > print myCell This prints a list of ints. What are they meaning? > if myCell[0] - 1 == 1: > #cell_value = sheet.text(myCell[0] - 1, myCell[1]) #[1] > cell_value = sheet.value(myCell[0] - 1, myCell[1]) #[2] > print 'Type is ', type(cell_value) > cell_value = cell_value[:2] + '-' + cell_value[2:4] + '-' + > cell_value[4:] > print 'Cell value is ', cell_value Save yourself some trouble, and use repr(cell_value). That way you'll see the type (indirectly) and the value all at once. For example, if it's a string, this will simply add quotes to the output, making it clear that it's a string. > cell_name = sheet.cellName(myCell[0] - 1, myCell[1]) > writer.setCell(cell_name) > writer.setValue(cell_name, cell_value) > viewer.setSelection([2, myCell[1], 1, 1]) > > [1] cell_value will always be a string. > [2] cell_value will be a string or a long depending on cell type. What are [1] and [2] referring to here, and in the comments below? Is it somehow related to the myCell[0] above that you're sort-of testing for ==2? > > Here is the output from the terminal. Note: Kross is the plugin that > enables Python scripting. > > > ### code from [1], cell type = text ### > Kross: "PythonScript::Constructor." > Kross: "PythonScript::execute" > Kross: "PythonScript::execute result=None" > [2, 5, 1, 1] > Type is > Cell value is 06-25-13 > Kross: "PythonInterpreter::extractException: > " > Kross: "PythonExtension::proxyhandler Had exception on line -1: > invalid literal for int() with base 10: '06-25-13' > " > ValueError: invalid literal for int() with base 10: '06-25-13' Fine. Something's getting an exception. Who? Is it your code that's intercepting it and stripping useful information, or is it Kross? > Kross: "PythonScript::Destructor." > > > ### code from [2], cell type = text ### > Kross: "PythonScript::Constructor." > Kross: "PythonScript::execute" > Kross: "PythonScript::execute result=None" > [2, 5, 1, 1] > Type is > Cell value is 06-25-13 > Kross: "PythonInterpreter::extractException: > " > Kross: "PythonExtension::proxyhandler Had exception on line -1: > invalid literal for int() with base 10: '06-25-13' SOMEBODY is trying to convert a string "06-25-13" to an int. All you have to do is discover the actual stack trace so you can assign blame. > " > ValueError: invalid literal for int() with base 10: '06-25-13' > Kross: "PythonScript::Destructor." > > > ### code [1], cell type = numeric ### > Kross: "PythonScript::Constructor." > Kross: "PythonScript::execute" > Kross: "PythonScript::execute result=None" > [2, 5, 1, 1] > Type is Why would sheet.value() be giving you a str if the cell is type numeric? > Cell value is 06-25-13 > Kross: "PythonInterpreter::extractException: > " > Kross: "PythonExtension::proxyhandler Had exception on line -1: > invalid literal for int() with base 10: '06-25-13' > " > ValueError: invalid literal for int() with base 10: '06-25-13' > Kross: "PythonScript::Destructor." > > > > ### code [2], cell type numeric ### > Kross: "PythonScript::Constructor." > Kross: "PythonScript::execute" > Kross: "PythonScript::execute result=None" > [2, 5, 1, 1] > Type is > Kross: "PythonInterpreter::extractException: > File > "file:///home/jfb/.kde/share/apps/sheets/scripts/enter_invoices.py", > line 38, in regionChanged > " > TypeError: 'long' object has no attribute '__getitem__' > Kross: "PythonScript::Destructor." > > Have you just tried simplifying it? Like skipping the cell-name stuff, and/or just using cell (0,0). Maybe the particular cell that you made of type text is not the one with the name, or maybe the label name is a duplicate. Or like using the various forms of setting a cell to set a group of cells to several different literals, both string and numeric? -- DaveA From davea at davea.name Mon Jun 24 01:59:19 2013 From: davea at davea.name (Dave Angel) Date: Sun, 23 Jun 2013 19:59:19 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51BF5382.2040608@gmail.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> Message-ID: <51C78BD7.9030502@davea.name> On 06/17/2013 02:20 PM, Luk?? N?mec wrote: >> > Or even better, use python moto, dont re-invent the wheel, so use built > in library logging, read the docs for it, or if you want, I can send you > some examples how to work it, it takes some time to figure out properly... But what he's doing has nothing to do with logging. He's just using that word. -- DaveA From dragondon at dragondon.net Mon Jun 24 03:04:40 2013 From: dragondon at dragondon.net (DragonDon) Date: Mon, 24 Jun 2013 10:04:40 +0900 Subject: [Tutor] Python 2 or 3? In-Reply-To: <1371503168.60924.YahooMailNeo@web186102.mail.ir2.yahoo.com> References: <1371503168.60924.YahooMailNeo@web186102.mail.ir2.yahoo.com> Message-ID: Week, not an experienced user per se, the more important thing is to just start. I can say this, the vast majority of online python classes use v2. So, if you have never programmed before, like myself, then 2 is going to be what you will learn. Learning to upgrade later is no big deal and I doubt you will immediately be writing programs that will need to be converted. I learned that there are a few tricks in regards to this 2/3 difference like: # adjust for Python 2 or 3 import sys ....if sys.version[0] >= ?3?: ........getUserInput = input ....else: ........getUserInput = raw_input But theses are only stop-gap measures maybe? It really depends on why you arelearning python i think. DragonDon On Jun 24, 2013 6:33 AM, "Andrew Cooper" wrote: > Dear Pythoners, > Sorry I am completely new to this but so far as I can see there are two > versions of Python, version 2 (which is more established and has much more > support) and version 3 which is relatively new. > As a beginner, which of the versions (2 or 3) would it be advisable to > start with first? > I suspect version 2, but I would like to hear that from experienced Python > users. > Many thanks, > Andy Cooper > > _______________________________________________ > 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 htdatcse at gmail.com Mon Jun 24 03:12:00 2013 From: htdatcse at gmail.com (Dat Huynh) Date: Mon, 24 Jun 2013 11:12:00 +1000 Subject: [Tutor] Question about python for web Message-ID: Dear all, I have a very simple question about running a simple web application with apache on MacOS. Step 1: Copy the file mod_wsgi.so from the link http://code.google.com/p/modwsgi/downloads/detail?name=mod_wsgi-macosx106-ap22py26-3.3.so into the folder "/usr/libexec/apache2" Step 2: Add the following line: LoadModule wsgi_module libexec/apache2/mod_wsgi.so into the file "/etc/apache2/httpd.conf" Step 3: Edit a file "test.py" as below and copy the file to the folder "/Library/WebServer/Documents". #!usr/bin/python print "Content-type: text/html" print print "" print "" print "" print "Test Page" print "" When I type the following url "http://localhost/test.py" on my browser, I see exactly the content of the file, NOT the text "Test Page" only. I think I miss something in the procedure. What should I do to make my browser process the received HTML data? Thank you very much. Sincerely, Dat. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Mon Jun 24 04:38:45 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 23 Jun 2013 19:38:45 -0700 Subject: [Tutor] "farkadoodle" or: unique global names, was Re: Data persistence problem In-Reply-To: <51C65C66.5030703@pearwood.info> References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <51C58620.8090606@pearwood.info> <1371931152.54551.YahooMailNeo@web163803.mail.gq1.yahoo.com> <51C65C66.5030703@pearwood.info> Message-ID: On 22 June 2013 19:24, Steven D'Aprano wrote: > * If you assign to a name (e.g. "spam = 42") anywhere inside the body of a > function, then that name is treated as a local variable, which is a fast > lookup. > > * Otherwise, it is treated as unknown scope, and Python will search nesting > functions (if any), globals, and finally builtins for the name. What about class variables instead of globals?, I put this in the my lazy typer module, maker.py, which works fine to persist the numbers between function calls so I can increment them: class count: dict = list = set = tuple = 0 then I use count.dict += 1 , etc. Would that restrict python from an upward search, or am I dreaming? And yes, I got rid of the Basic-style names D1, D2. The program now converts numbers to human-names up to dict_ninety_nine = , for instance. And no, I didn't type ninety_nine dictionary entries to do that. I'm too lazy a typer ;') -- Jim Resistance is futile, but running away is often surprisingly effective. From jf_byrnes at comcast.net Mon Jun 24 04:59:47 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Sun, 23 Jun 2013 21:59:47 -0500 Subject: [Tutor] How convert an int to a string In-Reply-To: <51C789D9.5020505@davea.name> References: <20130622221042.GC22060@wdfs.graniteweb.com> <51C6321D.6080400@davea.name> <51C789D9.5020505@davea.name> Message-ID: On 06/23/2013 06:50 PM, Dave Angel wrote: > On 06/23/2013 12:43 PM, Jim Byrnes wrote: >> On 06/22/2013 06:24 PM, Dave Angel wrote: >>> On 06/22/2013 07:03 PM, Jim Byrnes wrote: >>>> On 06/22/2013 05:10 PM, David Rock wrote: >>>>> * Jim Byrnes [2013-06-22 16:01]: >>>>>> I need to convert a series of digits like 060713 to a string so I can >>>>>> make it look like a date 06-07-13. >>>>>> >>>>>> >>> a = 060713 >>>>>> >>> a[:2] >>>>>> Traceback (most recent call last): >>>>>> File "", line 1, in >>>>>> TypeError: 'int' object has no attribute '__getitem__' >>>>>> >>> b = str(a) >>>>>> >>> b[:2] >>>>>> '25' >>>>>> >>> b >>>>>> '25035' >>>>>> >>> >>>>>> >>>>>> I was confused at first but then realized that the 0 makes it >>>>>> octal. I > > In Python source code. But the date number is being entered into the > spreadsheet, so the leading zero means no such thing. It also means no > such thing when a strictly Python program does something like: > x = int(raw_input()) > This is why context is so important. > >>>>>> thought str() would do it but it didn't. Reading about str() it >>>>>> talks of >>>>>> string representation. So how can I convert it to a true string I >>>>>> can >>>>>> slice and build my date look a like? >>>>> >>>>> Is there a requirement to store them as numbers in the first place? >>>>> Why >>>>> not just store them as a string? >>>>> >>>>> a = '060713' >>>>> >>>> >>>> Yes. I am scripting data entry in a spreadsheet. I can enter the 6 >>>> numbers >>> >>> Six digits, not numbers. >>> >>>> quite rapidly using the number pad but entering the " - "'s to >>>> make it look like a date slows me down. So I thought I would let >>>> python >>>> do that for me. >>>> >>> >>> I don't have any experience with using Rxlorg to script the Gemdaddy >>> spreadsheet program. Maybe if you actually got specific, somebody would >>> have familiarity with the ones you're using. >> >> It is Calligrsheets. > > I can't find any such thing. Do you perhaps mean Calligra Sheets, at > http://www.calligra.org/sheets/ ??? If so, I'm having trouble finding > any information on the internet about scripting it, in Python or > otherwise. It is available on Ubuntu's "Software Centre," but the only > review was rather negative. > Yes it is Calligra Sheets, that was a typo. It is a fork of what used to be the KDE app kspread. Documentation is sparse that's why it has taken me this long to make any progress at all. Here are a couple of the more usefull links. http://techbase.kde.org/Development/Tutorials/KSpread_Scripting http://kross.dipe.org/dox/kspread.html#a00013 > Using what to interface to it? I'll assume that's what's called Kross > below. I'll also have to make wild guesses about the available > functions and methods that Kross gives you. Like do you have to use > writer.setValue() for both ints and strings, or does it have separate > function calls? Does it have one for setting dates? Perhaps string is > the wrong type entirely. Yes Kross enables the python scripting. From the docs: bool setValue(QVariant value, bool parse=true) [slot] Set the value of the current cell. value The value that should be set. parse If this is true, the default, then the value got parsed to look for the type else we assume the value has the correct type. true if the value was set successful else false is returned. I take this to mean that it checks the under lying format of the cell and then supplies the value in that format. As to dates I haven't tried one. I actually don't need or want a true date format. I'm not going to do any date math or anything. I am just looking for some representation that looks like mm-dd-yy. > I can't find any information on the web about scripting Calligra. If > there's no installed help either, I'd find something with better docs. Well after a lot of searching and working with them I came the conclusion that Calligra Sheets was the best alternative available for python scripting in the Linux world. > >> I didn't mention it because I was focused on the >> python error message I was seeing. Python version is 2.7.3. > > But you don't have a Python error message. It's missing the most > important parts, the traceback. Something has intercepted that > exception and printed only a summary. And specified a line number of > negative-one, which isn't reasonable either. > > If the try/except is your own, then either fix the display or > temporarily disable the try. It is not. I pasted in all my code. > If the try/except is in the "Kross" code, and you have access to it, > then see what it looks like in the appropriate place. It is open source but I think it is C++ so doubt my looking at it would help me much. >> >>> Most likely all you have to do is specify with the spreadsheet that the >>> user is to enter a string. If it makes some sort of assumption that >>> strings cannot start with a digit, then it's just broken. >> >> I can set the cell contents as text or numeric and I can extract the >> info either as a string or an int. Each method gives it own error. The >> code is short so I will post it. >> >> def regionChanged(regions): >> """ In column A. Converts data entered as mmddyy to mm-dd-yy """ >> myCell = viewer.selection() >> print myCell > > This prints a list of ints. What are they meaning? Those are cell coordinates. [col, row, number of cols to right of anchor cell, number of rows down from the anchor cell] In this case it represents one cell. I should have commented it out before I ran it. I was using it to check where I was in the spreadsheet. > >> if myCell[0] - 1 == 1: >> #cell_value = sheet.text(myCell[0] - 1, myCell[1]) #[1] >> cell_value = sheet.value(myCell[0] - 1, myCell[1]) #[2] >> print 'Type is ', type(cell_value) >> cell_value = cell_value[:2] + '-' + cell_value[2:4] + '-' + >> cell_value[4:] >> print 'Cell value is ', cell_value > > Save yourself some trouble, and use repr(cell_value). That way you'll > see the type (indirectly) and the value all at once. For example, if > it's a string, this will simply add quotes to the output, making it > clear that it's a string. OK >> cell_name = sheet.cellName(myCell[0] - 1, myCell[1]) >> writer.setCell(cell_name) >> writer.setValue(cell_name, cell_value) >> viewer.setSelection([2, myCell[1], 1, 1]) >> >> [1] cell_value will always be a string. >> [2] cell_value will be a string or a long depending on cell type. > > What are [1] and [2] referring to here, and in the comments below? Is > it somehow related to the myCell[0] above that you're sort-of testing > for ==2? I was trying to match the errors below with the line of code that ran and the under lying format of the cell I was working with. I'm not sure what you meant by sort-of testing for == 2. myCell[0] and myCell[1] represent cell coordinates like (col, row). >> Here is the output from the terminal. Note: Kross is the plugin that >> enables Python scripting. >> >> >> ### code from [1], cell type = text ### >> Kross: "PythonScript::Constructor." >> Kross: "PythonScript::execute" >> Kross: "PythonScript::execute result=None" >> [2, 5, 1, 1] >> Type is >> Cell value is 06-25-13 >> Kross: "PythonInterpreter::extractException: >> " >> Kross: "PythonExtension::proxyhandler Had exception on line -1: >> invalid literal for int() with base 10: '06-25-13' >> " >> ValueError: invalid literal for int() with base 10: '06-25-13' > > Fine. Something's getting an exception. Who? Is it your code that's > intercepting it and stripping useful information, or is it Kross? Not mine. I don't know why it is being stripped because if I make an actual syntax error the line number is shown. > >> Kross: "PythonScript::Destructor." >> >> >> ### code from [2], cell type = text ### >> Kross: "PythonScript::Constructor." >> Kross: "PythonScript::execute" >> Kross: "PythonScript::execute result=None" >> [2, 5, 1, 1] >> Type is >> Cell value is 06-25-13 >> Kross: "PythonInterpreter::extractException: >> " >> Kross: "PythonExtension::proxyhandler Had exception on line -1: >> invalid literal for int() with base 10: '06-25-13' > > SOMEBODY is trying to convert a string "06-25-13" to an int. All you > have to do is discover the actual stack trace so you can assign blame. > >> " >> ValueError: invalid literal for int() with base 10: '06-25-13' >> Kross: "PythonScript::Destructor." >> >> >> ### code [1], cell type = numeric ### >> Kross: "PythonScript::Constructor." >> Kross: "PythonScript::execute" >> Kross: "PythonScript::execute result=None" >> [2, 5, 1, 1] >> Type is > > Why would sheet.value() be giving you a str if the cell is type numeric? In this case the line of code containing sheet.text() was used and if I understand what documentation there is it always returns text. > >> Cell value is 06-25-13 >> Kross: "PythonInterpreter::extractException: >> " >> Kross: "PythonExtension::proxyhandler Had exception on line -1: >> invalid literal for int() with base 10: '06-25-13' >> " >> ValueError: invalid literal for int() with base 10: '06-25-13' >> Kross: "PythonScript::Destructor." >> >> >> >> ### code [2], cell type numeric ### >> Kross: "PythonScript::Constructor." >> Kross: "PythonScript::execute" >> Kross: "PythonScript::execute result=None" >> [2, 5, 1, 1] >> Type is >> Kross: "PythonInterpreter::extractException: >> File >> "file:///home/jfb/.kde/share/apps/sheets/scripts/enter_invoices.py", >> line 38, in regionChanged >> " >> TypeError: 'long' object has no attribute '__getitem__' >> Kross: "PythonScript::Destructor." >> >> > > Have you just tried simplifying it? Like skipping the cell-name stuff, > and/or just using cell (0,0). Maybe the particular cell that you made of > type text is not the one with the name, or maybe the label name is a > duplicate. I don't think I can get it much simpler. I am using one cell in column A. When I test I set the entire column to either text or numeric. > Or like using the various forms of setting a cell to set a group of > cells to several different literals, both string and numeric? Before I started this project I found some examples on the web. Many of them did not work. As a learning exercise I rewrote them and got them to work. So I have been able to read and write data to cells. I think the errors I mentioned at the start of this email put my focus on the wrong thing. I was thinking if I could just get the type correct all would be well. Thinking about and answering your questions showed me that was not the case. I guess I will have to start over and rethink what I am trying to do. Thanks, JIm From johnsteedman360 at gmail.com Mon Jun 24 10:12:13 2013 From: johnsteedman360 at gmail.com (John Steedman) Date: Mon, 24 Jun 2013 09:12:13 +0100 Subject: [Tutor] Function Return Values (or References) Message-ID: Hi Tutors, I'm confused by the following possible contradiction. Would someone please explain or point me to the right docs. FACT 1 "Variables in python hold references to objects." http://en.wikipedia.org/wiki/Python_syntax_and_semantics FACT 2 >>>def Increment ( x ) : >>> // return x + 1 >>> x = x + 1 >>> return x >>> >>>y = 1 >>>z = Increment ( y ) >>>y 1 >>>z 2 By FACT 1 x should be a reference parameter...? By Fact 2 x would seem to be a copy...? What in the world of dynamic typing is going on? Many thanks, John -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Mon Jun 24 11:34:18 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 24 Jun 2013 05:34:18 -0400 Subject: [Tutor] "farkadoodle" or: unique global names, was Re: Data persistence problem In-Reply-To: References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <51C58620.8090606@pearwood.info> <1371931152.54551.YahooMailNeo@web163803.mail.gq1.yahoo.com> <51C65C66.5030703@pearwood.info> Message-ID: On Sun, Jun 23, 2013 at 10:38 PM, Jim Mooney wrote: > What about class variables instead of globals?, I put this in the my > lazy typer module, maker.py, which works fine to persist the numbers > between function calls so I can increment them: > > class count: > dict = list = set = tuple = 0 > > then I use count.dict += 1 , etc. > > Would that restrict python from an upward search, or am I dreaming? A class body is compiled and evaluated as a function (with unoptimized locals), but this function isn't searched as a nested scope. Otherwise the methods of the class could refer to class attributes without using __getattribute__, which would be confusing as it would bypass descriptor binding (i.e. properties, bound methods). But a consequence of this rule also tends to frustrate people: >>> class Spam: ... n = 2 ... evens = [x for x in range(10) if x % n == 0] ... Traceback (most recent call last): File "", line 1, in File "", line 3, in Spam File "", line 3, in NameError: global name 'n' is not defined In this case, the function is compiled to skip the class scope and instead use LOAD_GLOBAL to find n. Since the class name "Spam" isn't bound yet (the class object doesn't exist yet), you can't get around the problem by using Spam.n. Here's an example that shows the class scope getting skipped to instead use the outer scope of function f(): >>> def f(): ... n = 2 ... class Spam: ... n = 3 # skip this ... evens = [x for x in range(10) if x % n == 0] ... return Spam.evens ... >>> f() [0, 2, 4, 6, 8] > And yes, I got rid of the Basic-style names D1, D2. The program now > converts numbers to human-names up to dict_ninety_nine = , for > instance. And no, I didn't type ninety_nine dictionary entries to do > that. I'm too lazy a typer ;') Oh my. I don't think using the numbers spelled out makes it any better. I couldn't keep dict_thirty_four vs dict_sixty_five straight in my head to save my life. From davea at davea.name Mon Jun 24 11:54:35 2013 From: davea at davea.name (Dave Angel) Date: Mon, 24 Jun 2013 05:54:35 -0400 Subject: [Tutor] Function Return Values (or References) In-Reply-To: References: Message-ID: <51C8175B.9000205@davea.name> On 06/24/2013 04:12 AM, John Steedman wrote: > Hi Tutors, > > I'm confused by the following possible contradiction. Would someone please > explain or point me to the right docs. > > FACT 1 > > "Variables in python hold references to objects." > http://en.wikipedia.org/wiki/Python_syntax_and_semantics > > FACT 2 > >>>> def Increment ( x ) : >>>> // return x + 1 >>>> x = x + 1 >>>> return x >>>> >>>> y = 1 >>>> z = Increment ( y ) >>>> y > 1 >>>> z > 2 > > By FACT 1 x should be a reference parameter...? > By Fact 2 x would seem to be a copy...? > > What in the world of dynamic typing is going on? > Python docs usually use the word "binding" rather than reference. A variable (name) is bound to an object. But it can be rebound. For example, any assignment rebinds the name to a (possibly new) object. So as soon as you did the x=x+1, you're no longer referring to the original object. Another factor is that int (and float, str, and tuple, plus some others) is immutable. That means that once the object is created, its value cannot change. So there's no way to change the Increment() function to do exactly what you ask for. Since y is bound to an immutable object, the function cannot change that value. Now let's choose a mutable object and try the analogous thing. def add_to_end(mylist): mylist = mylist + [42] return mylist Once again, if we test it with k = [4] j = add_to_end(k) k j we'll see that k is unchanged. But this one we CAN fix. def add_to_end(mylist): mylist.append(42) #notice we do NOT rebind it, we mutate the object inplace return mylist Incidentally, convention is that if a function mutates its (single) argument, it does not return it, and if it returns a modified copy, it doesn't alter the original. See for example sort() and sorted(), respectively. If you happen to be familiar with C++, a reference there is bound once when it's defined, and it cannot be changed to reference a different object. What would be equivalent to a python rebinding is simply a compile-time error. Of course in C++, whenever such things get in the way, you fake your way out with casting. Hope this helps. -- DaveA From __peter__ at web.de Mon Jun 24 11:59:38 2013 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Jun 2013 11:59:38 +0200 Subject: [Tutor] Function Return Values (or References) References: Message-ID: John Steedman wrote: > Hi Tutors, > > I'm confused by the following possible contradiction. Would someone please > explain or point me to the right docs. > > FACT 1 > > "Variables in python hold references to objects." > http://en.wikipedia.org/wiki/Python_syntax_and_semantics > > FACT 2 > >>>>def Increment ( x ) : >>>> // return x + 1 >>>> x = x + 1 >>>> return x >>>> >>>>y = 1 >>>>z = Increment ( y ) >>>>y > 1 >>>>z > 2 > > By FACT 1 x should be a reference parameter...? > By Fact 2 x would seem to be a copy...? > > What in the world of dynamic typing is going on? There's a big confusion in terminology. Does http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing help? Here's a more detailed explanation: From johnsteedman360 at gmail.com Mon Jun 24 12:41:27 2013 From: johnsteedman360 at gmail.com (John Steedman) Date: Mon, 24 Jun 2013 11:41:27 +0100 Subject: [Tutor] Function Return Values (or References) In-Reply-To: References: Message-ID: Thanks for all these clear and knowledgeable answers. I'm much clearer on this now and will read up a bit more around these subjects. John On Mon, Jun 24, 2013 at 10:59 AM, Peter Otten <__peter__ at web.de> wrote: > John Steedman wrote: > > > Hi Tutors, > > > > I'm confused by the following possible contradiction. Would someone > please > > explain or point me to the right docs. > > > > FACT 1 > > > > "Variables in python hold references to objects." > > http://en.wikipedia.org/wiki/Python_syntax_and_semantics > > > > FACT 2 > > > >>>>def Increment ( x ) : > >>>> // return x + 1 > >>>> x = x + 1 > >>>> return x > >>>> > >>>>y = 1 > >>>>z = Increment ( y ) > >>>>y > > 1 > >>>>z > > 2 > > > > By FACT 1 x should be a reference parameter...? > > By Fact 2 x would seem to be a copy...? > > > > What in the world of dynamic typing is going on? > > There's a big confusion in terminology. Does > > http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing > > help? Here's a more detailed explanation: > > < > http://learntofish.wordpress.com/2012/01/09/call-by-object-reference-call-by-sharing/ > > > > > > _______________________________________________ > 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 zagheni at yahoo.com Mon Jun 24 15:34:06 2013 From: zagheni at yahoo.com (Antonio Zagheni) Date: Mon, 24 Jun 2013 06:34:06 -0700 (PDT) Subject: [Tutor] Help (Antonio Zagheni) In-Reply-To: References: Message-ID: <1372080846.26531.YahooMailNeo@web164006.mail.gq1.yahoo.com> Hello eryksun, Thanks for your help... But I am trying to paste the clipboard content to MS word and when I do it MS word becomes not responding. So, if you can help... Thanks a lot again, Antonio ZAgheni. Message: 3 Date: Sun, 23 Jun 2013 18:18:11 -0400 From: eryksun To: Antonio Zagheni Cc: "tutor at python.org" Subject: Re: [Tutor] Help Message-ID: ??? Content-Type: text/plain; charset=UTF-8 On Thu, Jun 20, 2013 at 6:10 PM, Antonio Zagheni wrote: > > I am a begginer in Python. > I did a function that returns a string and I want to copy this to the clipboard. > I have tried a lot of suggestions found at Google but nothing works properly. > Is there an easy way to do that? > I am using Python 2.7 and Windows 7. It's simple to access the clipboard with Tkinter: ? ? >>> from Tkinter import Tk, TclError ? ? >>> root = Tk() ? ? >>> root.withdraw() ? ? '' ? ? >>> root.clipboard_clear() ? ? >>> root.clipboard_append('eggs ') ? ? >>> root.clipboard_append('and spam') ? ? >>> root.clipboard_get() ? ? 'eggs and spam' ? ? >>> root.clipboard_clear() ? ? >>> try: root.clipboard_get() ? ? ... except TclError as e: print e ? ? ... ? ? CLIPBOARD selection doesn't exist or form "STRING" not defined ------------------------------ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Jun 24 15:39:47 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 24 Jun 2013 23:39:47 +1000 Subject: [Tutor] Function Return Values (or References) In-Reply-To: References: Message-ID: <51C84C23.80208@pearwood.info> On 24/06/13 18:12, John Steedman wrote: > Hi Tutors, > > I'm confused by the following possible contradiction. Would someone please > explain or point me to the right docs. [snip confusion about parameter passing and Python's object model] > By FACT 1 x should be a reference parameter...? > By Fact 2 x would seem to be a copy...? Function arguments in Python are *neither* passed by reference nor passed by value (copied). Here's a post I made some years ago going into long detail about it. I hope this is helpful for you. http://mail.python.org/pipermail/tutor/2010-December/080505.html -- Steven From __peter__ at web.de Mon Jun 24 17:34:16 2013 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Jun 2013 17:34:16 +0200 Subject: [Tutor] Help (Antonio Zagheni) References: <1372080846.26531.YahooMailNeo@web164006.mail.gq1.yahoo.com> Message-ID: Antonio Zagheni wrote: >> I am a begginer in Pythonu >> I did a function that returns a string and I want to copy this to the >> clipboard. I have tried a lot of suggestions found at Google but nothing >> works properly. Is there an easy way to do that? >> I am using Python 2.7 and Windows 7. > > It's simple to access the clipboard with Tkinter: [eryksun] > >>> from Tkinter import Tk, TclError > >>> root = Tk() > >>> root.withdraw() > '' > >>> root.clipboard_clear() > > >>> root.clipboard_append('eggs ') > >>> root.clipboard_append('and spam') > >>> root.clipboard_get() > 'eggs and spam' > > >>> root.clipboard_clear() > >>> try: root.clipboard_get() > ... except TclError as e: print e > ... > CLIPBOARD selection doesn't exist or form "STRING" not defined [Antonio] > But I am trying to paste the clipboard content to MS word and when I do it > MS word becomes not responding. > > So, if you can help... Please show us the python script you are running and tell us how exactly you are invoking it. From alan.gauld at btinternet.com Mon Jun 24 19:57:48 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Jun 2013 18:57:48 +0100 Subject: [Tutor] Help (Antonio Zagheni) In-Reply-To: <1372080846.26531.YahooMailNeo@web164006.mail.gq1.yahoo.com> References: <1372080846.26531.YahooMailNeo@web164006.mail.gq1.yahoo.com> Message-ID: On 24/06/13 14:34, Antonio Zagheni wrote: > But I am trying to paste the clipboard content to MS word and when I do > it MS word becomes not responding. OK, so the question is not how to manipulate the clipboard but how to manipulate MS Word. There are multiple ways to approach that. What technology are you using to talk to Word? COM? DLL? Robotic? Do you have any code you can share to show us what you are trying to do? Also you could try the Win32 Python mailing list since they are experts at integrating Python with Windows things. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cybervigilante at gmail.com Mon Jun 24 20:52:55 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 24 Jun 2013 11:52:55 -0700 Subject: [Tutor] "farkadoodle" or: unique global names, was Re: Data persistence problem In-Reply-To: References: <1371851947.77149.YahooMailNeo@web186003.mail.ir2.yahoo.com> <51C58620.8090606@pearwood.info> <1371931152.54551.YahooMailNeo@web163803.mail.gq1.yahoo.com> <51C65C66.5030703@pearwood.info> Message-ID: eryksun > > Oh my. I don't think using the numbers spelled out makes it any > better. I couldn't keep dict_thirty_four vs dict_sixty_five straight > in my head to save my life. It was just for fun. But by coincidence I was trolling the web and some guy wanted to know if Python could change a number into words, like 349 into Three hundred forty nine. Not in the builtins, I'm afraid. Nothing recent seemed available to do that, on a quick websearch, but I see an easy way to go up to ten dectillion so I'll write that for practice. The only other module I found was so old I couldn't make 2to3 convert it. And it was vast overkill. I don't need Norwegian numbers - let the Norwegians count for themselves - one fish, two fish, three fish... Actually, I can think of a use for a large number routine (without the underlines) Politicians like to alarm us and get contributions by sending emails about the national debt all the time. "Sixteeen trillion, eight hundred eighty two billion, two hundred ninety million, one hundred fifty two thousand, two hundred forty seven dollars" looks so much more alarming than the numerals. And of course, if a dumb pol is reading his teleprompter he'll get brain freeze trying to cipher numerals that big, but he can just read out words. -- Jim Resistance is futile, but running away is often surprisingly effective. From davea at davea.name Mon Jun 24 23:57:56 2013 From: davea at davea.name (Dave Angel) Date: Mon, 24 Jun 2013 17:57:56 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51C8BC8A.9060008@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> Message-ID: <51C8C0E4.9040508@davea.name> On 06/24/2013 05:39 PM, Matt D wrote: > >> But what he's doing has nothing to do with logging. He's just using >> that word. >> >> > Right, I'm not doing a debugging thing. Just trying to create a log of > data that has been passed into the display of this program. Since I > started trying to use the array the program is not working. So I am > wondering if its not the best way to try to save TextCtrl values. > You accidentally posted this offline, direct to me. So it loses all context. I'll try to get it back into the thread, but it may not "take." I don't know what array you're referring to. I VERY seldom use arrays in Python, since list is much more flexible and easy to use. Nor do I know what you mean by the program not working. I also don't know what you mean by saving TextCtrl values. Aren't they being appended to the csv file (in random order) with your latest changes? You asked about a "save-as" feature. Why isn't that as simple as copying the current contents of the saved csv file? Or do you not know how you would go about copying? Be specific with your questions, and you might get some answers. Use those answers in later versions, and you'll get the same people more willing to help further. Why is it no longer of interest to you to get a predictable order in your csv file? -- DaveA From md123 at nycap.rr.com Tue Jun 25 00:05:37 2013 From: md123 at nycap.rr.com (Matt D) Date: Mon, 24 Jun 2013 18:05:37 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51C78BD7.9030502@davea.name> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> Message-ID: <51C8C2B1.3030907@nycap.rr.com> I have been unable to find a way to write pickled data to text file. My last attempt was to add the last two lines: # the dataevent class -- stores the data that gets transmitted when the event occurs. #it is the data in text fields, stored in self.data as a dictionary, which is basically a c++ map #One of these classes gets created whenever an event occurs. class DataEvent(wx.PyEvent): # the values of the text fields get passed into the constructor inside of data def __init__(self, data): wx.PyEvent.__init__(self) # this line *binds* this class to a certain type of event, wxDATA_EVENT self.SetEventType (wxDATA_EVENT) # and this is the actual data self.data = data with open('mypicklelog.txt','a') as log: log.write(self.data) I cant figure out why these last two line dont write to the .txt file after the program has received the pickled Python dictionary? Very stumped. From md123 at nycap.rr.com Tue Jun 25 00:36:46 2013 From: md123 at nycap.rr.com (Matt D) Date: Mon, 24 Jun 2013 18:36:46 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51C8C0E4.9040508@davea.name> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> Message-ID: <51C8C9FE.9000309@nycap.rr.com> On 06/24/2013 05:57 PM, Dave Angel wrote: > On 06/24/2013 05:39 PM, Matt D wrote: >> >>> But what he's doing has nothing to do with logging. He's just using >>> that word. >>> >>> >> Right, I'm not doing a debugging thing. Just trying to create a log of >> data that has been passed into the display of this program. Since I >> started trying to use the array the program is not working. So I am >> wondering if its not the best way to try to save TextCtrl values. >> > > You accidentally posted this offline, direct to me. So it loses all > context. I'll try to get it back into the thread, but it may not "take." > > I don't know what array you're referring to. I VERY seldom use arrays > in Python, since list is much more flexible and easy to use. Nor do I > know what you mean by the program not working. > > I also don't know what you mean by saving TextCtrl values. Aren't they > being appended to the csv file (in random order) with your latest changes? > > > You asked about a "save-as" feature. Why isn't that as simple as > copying the current contents of the saved csv file? Or do you not know > how you would go about copying? > > Be specific with your questions, and you might get some answers. Use > those answers in later versions, and you'll get the same people more > willing to help further. > > Why is it no longer of interest to you to get a predictable order in > your csv file? > > > -- > DaveA > > Well i decided to switch to a .txt file because it is easier for me to lay eyes on it and the commas are there if i want to import it into librecalc or sas or whatever. and values were writing in an acceptable order becuase, while the order was not of my choosing, the order was always the same. so that is fine for importing into another program for later inspection. What you said about the 'save as' is right, i didnt know how to go about copying the logfile.txt (as I had it) to the file the user opened. thats why i decided to try an array like this: # openfile defined to start FileDialog and write the traffic log to the file def openFile(self, evt): with wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.txt*", wx.OPEN) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() mypath = os.path.basename(path) with open(mypath, "a") as f: f.writelines(self.log_array) I name the array up in the initializer self.log_array = [] and this is supposed to get the the values out of the pickle and into the textcrls and into the array: # Update the field values # put values in array def update(self, field_values): next_line = "" next_line += strftime("%Y-%m-%d %H:%M:%S") next_line += ','.join( field_values[k] for k in self.fields.keys() if k in field_values ) log_array.append(next_line) #if the field 'duid' == 'hdu', then clear all the fields if field_values['duid'] == 'hdu': self.clear() #loop through all TextCtrl fields storing the key/value pairs in k, v for k,v in self.fields.items(): # get the pickle value for this TextCtrl f = field_values.get(k, None) # if the value is empty then set the new value if f: v.SetValue(f) But the program is not working, meaning the TextCtrl fields are not getting their values and the log is not being written. I dont know if I am missing a self.something or I some indentation wrong that doest throw the error or what. Very Stuck. From md123 at nycap.rr.com Tue Jun 25 00:48:43 2013 From: md123 at nycap.rr.com (Matt D) Date: Mon, 24 Jun 2013 18:48:43 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51C8C2B1.3030907@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> Message-ID: <51C8CCCB.3000200@nycap.rr.com> On 06/24/2013 06:05 PM, Matt D wrote: > I have been unable to find a way to write pickled data to text file. > My last attempt was to add the last two lines: > > # the dataevent class -- stores the data that gets transmitted when the > event occurs. > #it is the data in text fields, stored in self.data as a dictionary, > which is basically a c++ map > #One of these classes gets created whenever an event occurs. > class DataEvent(wx.PyEvent): > # the values of the text fields get passed into the constructor > inside of data > def __init__(self, data): > wx.PyEvent.__init__(self) > # this line *binds* this class to a certain type of event, > wxDATA_EVENT > self.SetEventType (wxDATA_EVENT) > # and this is the actual data > self.data = data > with open('mypicklelog.txt','a') as log: > log.write(self.data) > > I cant figure out why these last two line dont write to the .txt file > after the program has received the pickled Python dictionary? Very > stumped. > Sorry I forgot to show the error in terminal: File "/usr/local/lib/python2.7/dist-packages/baz/op25_traffic_pane.py", line 53, in __init__ log.write(self.data) TypeError: expected a character buffer object From steve at pearwood.info Tue Jun 25 00:57:28 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 25 Jun 2013 08:57:28 +1000 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51C8C2B1.3030907@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> Message-ID: <20130624225727.GA10635@ando> On Mon, Jun 24, 2013 at 06:05:37PM -0400, Matt D wrote: > I have been unable to find a way to write pickled data to text file. Normally you write pickled data to a file like this: import pickle data = {'something': 'goes', 'here': 42} with open("/path/to/file/name.pickle", "rb") as f: pickle.dump(data, f) And then read it back again like this: with open("/path/to/file/name.pickle") as f: data = pickle.load(f) You certainly shouldn't be writing pickle data to a log file! Firstly, log files are usually opened in text mode, not binary mode, so it probably won't work, and secondly even if it did work, you will be dumping a load of pickled binary data into the middle of what should be a text file. That's a bad idea. And even if it succeeded, what are you going to learn from seeing a line like this: \x80\x03}q\x00(X\x04\x00\x00\x00hereq\x01K*X\t\x00\x00\x00somethingq\x02X\x04\x00\x00\x00goesq\x03u. in the middle of your log file? Log files are supposed to be for humans to read, not for binary data like a pickle. > My last attempt was to add the last two lines: [...] > I cant figure out why these last two line dont write to the .txt file > after the program has received the pickled Python dictionary? Very > stumped. What does it do? Do you get an error? -- Steven From alan.gauld at btinternet.com Tue Jun 25 01:17:58 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 25 Jun 2013 00:17:58 +0100 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51C8C2B1.3030907@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> Message-ID: On 24/06/13 23:05, Matt D wrote: > I have been unable to find a way to write pickled data to text file. Probably because pickled data is not plain text. You need to use binary mode. However... > def __init__(self, data): > wx.PyEvent.__init__(self) > self.SetEventType (wxDATA_EVENT) > # and this is the actual data > self.data = data > with open('mypicklelog.txt','a') as log: > log.write(self.data) Since you are not using pickle here, all you are really doing is trying to write whatever data is to a text file that happens to have 'pickle' in its name. When writing to a text file you need to write strings. You have no guarantee that 'data' is a string. You should probably convert it before writing it. Thats one of the advantages of using real pickles - they take care of that complication for you. > I cant figure out why these last two line dont write to the .txt file > after the program has received the pickled Python dictionary? Pickle data has to be unpickled before you can use it. Before you can write it back again you need to repickle it. The code you posted does not show you producing and pickled data nor indeed you reading any pickled data... If 'data' is indeed in pickle format you cannot simply write it to a text file since Pickle is not in a text format. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From marc.tompkins at gmail.com Tue Jun 25 01:23:11 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 24 Jun 2013 16:23:11 -0700 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51C8CCCB.3000200@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8CCCB.3000200@nycap.rr.com> Message-ID: On Mon, Jun 24, 2013 at 3:48 PM, Matt D wrote: > > def __init__(self, data): > > wx.PyEvent.__init__(self) > > # this line *binds* this class to a certain type of event, > > wxDATA_EVENT > > self.SetEventType (wxDATA_EVENT) > > # and this is the actual data > > self.data = data > > with open('mypicklelog.txt','a') as log: > > log.write(self.data) > Jumping in a little late here, but: do you do anything else, later on, with self.data? If not, you could skip the "self.data = data" line and just do your thing with "data"... If you ARE doing something with it later on, of course, please disregard. I just wanted to point out that not everything needs to be persisted, if you're only using it once. -------------- next part -------------- An HTML attachment was scrubbed... URL: From md123 at nycap.rr.com Tue Jun 25 02:36:29 2013 From: md123 at nycap.rr.com (Matt D) Date: Mon, 24 Jun 2013 20:36:29 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> Message-ID: <51C8E60D.20709@nycap.rr.com> On 06/24/2013 07:17 PM, Alan Gauld wrote: > On 24/06/13 23:05, Matt D wrote: >> I have been unable to find a way to write pickled data to text file. > > Probably because pickled data is not plain text. > You need to use binary mode. However... > > >> def __init__(self, data): >> wx.PyEvent.__init__(self) >> self.SetEventType (wxDATA_EVENT) >> # and this is the actual data >> self.data = data >> with open('mypicklelog.txt','a') as log: >> log.write(self.data) > > Since you are not using pickle here, all you are really doing > is trying to write whatever data is to a text file that > happens to have 'pickle' in its name. > > When writing to a text file you need to write strings. > You have no guarantee that 'data' is a string. You should > probably convert it before writing it. Thats one of the > advantages of using real pickles - they take care of > that complication for you. > >> I cant figure out why these last two line dont write to the .txt file >> after the program has received the pickled Python dictionary? > > Pickle data has to be unpickled before you can use it. > Before you can write it back again you need to repickle it. > The code you posted does not show you producing and pickled > data nor indeed you reading any pickled data... > > If 'data' is indeed in pickle format you cannot simply write > it to a text file since Pickle is not in a text format. > > im sorry; some more code will clarify i think ; class DataEvent(wx.PyEvent): # the values of the text fields get passed into the constructor inside of data def __init__(self, data): wx.PyEvent.__init__(self) # this line *binds* this class to a certain type of event, wxDATA_EVENT self.SetEventType (wxDATA_EVENT) # and this is the actual data self.data = data with open('mypicklelog.txt','a') as log: log.write(self.data) self.data stores the data as a dictionary. from lower inthe program: # Display the values on the UI def display_data(self,event): #gets the "message" into the event object #message is equal to the "data" parameter in the "DataEvent" class message = event.data # unpickle the string pickled_dict = message.to_string() #separate the string into values for each text control (attrs is a pickle object) attrs = pickle.loads(pickled_dict) #pass this pickle object into update self.update(attrs) The purpose of getting the pickle in file is so that i can make a little program to resend it to this program at will for testing purposes. Clearly I was not aware that we cant put pickled data into a test file. What would be the best way to save the pickle for testing purposes? From cybervigilante at gmail.com Tue Jun 25 03:48:46 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 24 Jun 2013 18:48:46 -0700 Subject: [Tutor] mistaken about splitting expressions over lines Message-ID: For some reason I took the impression that you could split expressions over lines. However, this works: word = 'spam' new_word = word + 'eggs' print(word) But this is a syntax error: word = 'spam' new_word = word + 'eggs' print(word) That's easy to avoid, but what if you're adding five or six very long things, like some really long strings? -- Jim Never run on gravel with a lightbulb in your mouth (personal experience - don't ask.) From davea at davea.name Tue Jun 25 03:58:14 2013 From: davea at davea.name (Dave Angel) Date: Mon, 24 Jun 2013 21:58:14 -0400 Subject: [Tutor] mistaken about splitting expressions over lines In-Reply-To: References: Message-ID: <51C8F936.6080707@davea.name> On 06/24/2013 09:48 PM, Jim Mooney wrote: > For some reason I took the impression that you could split expressions > over lines. However, this works: > > word = 'spam' > new_word = word + 'eggs' > print(word) > > But this is a syntax error: > > word = 'spam' > new_word = word + > 'eggs' > print(word) > > That's easy to avoid, but what if you're adding five or six very long > things, like some really long strings? > Simplest thing is to add parentheses around the expression. new_word = (word + 'a very long string' + other_word + "another long string" + still_another) Alternatively, you can also use the statement continuation mechanism, whereby the last character of the line is a backslash. Using that approach you can break almost anywhere, except within a token or inside a string literal. And you can break up string literals without using a "+" operator, because adjacent string literals are combined at compile time. a = "this" \ " string" " is long" is exactly equivalent to a = "this string is long" -- DaveA From __peter__ at web.de Tue Jun 25 08:04:20 2013 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Jun 2013 08:04:20 +0200 Subject: [Tutor] Need help printing a pickled data References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> Message-ID: Matt D wrote: > On 06/24/2013 07:17 PM, Alan Gauld wrote: >> On 24/06/13 23:05, Matt D wrote: >>> I have been unable to find a way to write pickled data to text file. >> >> Probably because pickled data is not plain text. >> You need to use binary mode. However... >> >> >>> def __init__(self, data): >>> wx.PyEvent.__init__(self) >>> self.SetEventType (wxDATA_EVENT) >>> # and this is the actual data >>> self.data = data >>> with open('mypicklelog.txt','a') as log: >>> log.write(self.data) >> >> Since you are not using pickle here, all you are really doing >> is trying to write whatever data is to a text file that >> happens to have 'pickle' in its name. >> >> When writing to a text file you need to write strings. >> You have no guarantee that 'data' is a string. You should >> probably convert it before writing it. Thats one of the >> advantages of using real pickles - they take care of >> that complication for you. >> >>> I cant figure out why these last two line dont write to the .txt file >>> after the program has received the pickled Python dictionary? >> >> Pickle data has to be unpickled before you can use it. >> Before you can write it back again you need to repickle it. >> The code you posted does not show you producing and pickled >> data nor indeed you reading any pickled data... >> >> If 'data' is indeed in pickle format you cannot simply write >> it to a text file since Pickle is not in a text format. >> >> > im sorry; some more code will clarify i think ; No, you aren't listening to Alan. The suggestive filename notwithstanding > with open('mypicklelog.txt','a') as log: > log.write(self.data) will fail unless self.data is a string. Disregarding all other problems for the moment, you need with open('mypicklelog.txt','ab') as log: # open in binary mode pickle.dump(self.data, log) # serialize data and write to file where pickle.dump(obj, file) converts `obj` to a sequence of bytes before it is written to `file`. From eryksun at gmail.com Tue Jun 25 13:28:44 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 25 Jun 2013 07:28:44 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <20130624225727.GA10635@ando> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <20130624225727.GA10635@ando> Message-ID: On Mon, Jun 24, 2013 at 6:57 PM, Steven D'Aprano wrote: > > You certainly shouldn't be writing pickle data to a log file! Firstly, > log files are usually opened in text mode, not binary mode, so it > probably won't work, and secondly even if it did work, you will be > dumping a load of pickled binary data into the middle of what should be > a text file. That's a bad idea. And even if it succeeded, what are you > going to learn from seeing a line like this: I don't know which version Matt is using, but 2.x defaults to pickle protocol 0, which is ASCII. In 3.x you can manually specify protocol 0: >>> pickle.dumps([1,2,3], protocol=0) b'(lp0\nL1L\naL2L\naL3L\na.' With the ASCII protocol you can open the file in either text or binary mode, so long as you're consistent. But use binary mode if it needs to be cross-platform. From eryksun at gmail.com Tue Jun 25 14:14:51 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 25 Jun 2013 08:14:51 -0400 Subject: [Tutor] mistaken about splitting expressions over lines In-Reply-To: <51C8F936.6080707@davea.name> References: <51C8F936.6080707@davea.name> Message-ID: On Mon, Jun 24, 2013 at 9:58 PM, Dave Angel wrote: > > Alternatively, you can also use the statement continuation mechanism, > whereby the last character of the line is a backslash. Using that approach > you can break almost anywhere, except within a token or inside a string > literal. Also, the next character after a line continuation has to be a newline, e.g. no spaces, tabs, or comments. Your editor should have a feature to remove trailing white space on each line. >>> a = 'this' \ File "", line 1 a = 'this' \ ^ SyntaxError: unexpected character after line continuation character >>> a = ('this' # this way ... ' string' ' is long') # is more flexible >>> a 'this string is long' From md123 at nycap.rr.com Tue Jun 25 14:19:41 2013 From: md123 at nycap.rr.com (Matt D) Date: Tue, 25 Jun 2013 08:19:41 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <20130624225727.GA10635@ando> Message-ID: <51C98ADD.70203@nycap.rr.com> On 06/25/2013 07:28 AM, eryksun wrote: > On Mon, Jun 24, 2013 at 6:57 PM, Steven D'Aprano wrote: >> >> You certainly shouldn't be writing pickle data to a log file! Firstly, >> log files are usually opened in text mode, not binary mode, so it >> probably won't work, and secondly even if it did work, you will be >> dumping a load of pickled binary data into the middle of what should be >> a text file. That's a bad idea. And even if it succeeded, what are you >> going to learn from seeing a line like this: > > I don't know which version Matt is using, but 2.x defaults to pickle > protocol 0, which is ASCII. In 3.x you can manually specify protocol > 0: > > >>> pickle.dumps([1,2,3], protocol=0) > b'(lp0\nL1L\naL2L\naL3L\na.' > > With the ASCII protocol you can open the file in either text or binary > mode, so long as you're consistent. But use binary mode if it needs to > be cross-platform. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I'm using 2.7 for this program. I the docs say what you said about the default being 0 so I didn't know I needed to convert to string. Thanks. From fomcl at yahoo.com Tue Jun 25 14:52:36 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 25 Jun 2013 05:52:36 -0700 (PDT) Subject: [Tutor] mistaken about splitting expressions over lines In-Reply-To: References: <51C8F936.6080707@davea.name> Message-ID: <1372164756.40289.YahooMailNeo@web163806.mail.gq1.yahoo.com> _______________________________ >From: eryksun >To: Jim Mooney >Cc: tutor at python.org >Sent: Tuesday, June 25, 2013 2:14 PM >Subject: Re: [Tutor] mistaken about splitting expressions over lines > >? ? >>> a = ('this'? # this way >? ? ...? ? ? ' string' ' is long') # is more flexible >? ? >>> a >? ? 'this string is long' ? I did something similar after having read http://docs.python.org/2/howto/doanddont.html, under "Using Backslash to Continue Statements". ? But I always use + signs. I didn't know that omitting them also works. Is str.__add__ called then, too? Isn't this a violation of the 'Explicit is better than implicit(ly concatenate strings)' principle? >>> a = ('this' + ????????????? ' string' + ??????????????' is long') >>> a 'this string is long' From __peter__ at web.de Tue Jun 25 16:11:44 2013 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Jun 2013 16:11:44 +0200 Subject: [Tutor] mistaken about splitting expressions over lines References: <51C8F936.6080707@davea.name> <1372164756.40289.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam wrote: > _______________________________ >>From: eryksun >>To: Jim Mooney >>Cc: tutor at python.org >>Sent: Tuesday, June 25, 2013 2:14 PM >>Subject: Re: [Tutor] mistaken about splitting expressions over lines > > > >> >>>>> a = ('this' # this way >>... ' string' ' is long') # is more flexible >>>>> a >>'this string is long' > > > I did something similar after having read > http://docs.python.org/2/howto/doanddont.html, under "Using Backslash to > Continue Statements". > > But I always use + signs. I didn't know that omitting them also works. Is > str.__add__ called then, too? Isn't this a violation of the 'Explicit is > better than implicit(ly concatenate strings)' principle? >>>> a = ('this' + > ' string' + > ' is long') >>>> a > 'this string is long' In older Pythons for ("alpha" "beta") the compiler would merge the two strings into one whereas ("alpha" + "beta") would trigger a str.__add__() call at runtime. Nowadays the peephole optimiser recognizes ("alpha" + "beta") and replaces it with a single string: >>> import dis >>> def f(): ... return ("alpha" + ... "beta") ... >>> dis.dis(f) 3 0 LOAD_CONST 3 ('alphabeta') 3 RETURN_VALUE From eryksun at gmail.com Tue Jun 25 17:10:01 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 25 Jun 2013 11:10:01 -0400 Subject: [Tutor] mistaken about splitting expressions over lines In-Reply-To: References: <51C8F936.6080707@davea.name> <1372164756.40289.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On Tue, Jun 25, 2013 at 10:11 AM, Peter Otten <__peter__ at web.de> wrote: > > In older Pythons for ("alpha" "beta") the compiler would merge the two > strings into one whereas ("alpha" + "beta") would trigger a str.__add__() > call at runtime. Nowadays the peephole optimiser recognizes ("alpha" + > "beta") and replaces it with a single string: > >>>> import dis >>>> def f(): > ... return ("alpha" + > ... "beta") > ... >>>> dis.dis(f) > 3 0 LOAD_CONST 3 ('alphabeta') > 3 RETURN_VALUE Constant folding for binary operations has a length limit of 20 for sequences: >>> dis.dis(lambda: '0123456789' + '0123456789' + '0') 1 0 LOAD_CONST 3 ('0123456789 0123456789') 3 LOAD_CONST 2 ('0') 6 BINARY_ADD 7 RETURN_VALUE >>> dis.dis(lambda: (0,1,2,3,4,5,6,7,8,9) + ... (0,1,2,3,4,5,6,7,8,9) + (0,)) 2 0 LOAD_CONST 13 ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) 3 LOAD_CONST 14 ((0,)) 6 BINARY_ADD 7 RETURN_VALUE From __peter__ at web.de Tue Jun 25 17:35:04 2013 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Jun 2013 17:35:04 +0200 Subject: [Tutor] mistaken about splitting expressions over lines References: <51C8F936.6080707@davea.name> <1372164756.40289.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: eryksun wrote: > Constant folding for binary operations has a length limit of 20 for > sequences: > > >>> dis.dis(lambda: '0123456789' + '0123456789' + '0') > 1 0 LOAD_CONST 3 ('0123456789 > 0123456789') > 3 LOAD_CONST 2 ('0') > 6 BINARY_ADD > 7 RETURN_VALUE Interesting. Do you know why the limit is so low (especially for strings)? From eryksun at gmail.com Tue Jun 25 17:43:57 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 25 Jun 2013 11:43:57 -0400 Subject: [Tutor] mistaken about splitting expressions over lines In-Reply-To: References: <51C8F936.6080707@davea.name> <1372164756.40289.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On Tue, Jun 25, 2013 at 11:35 AM, Peter Otten <__peter__ at web.de> wrote: > eryksun wrote: > >> Constant folding for binary operations has a length limit of 20 for >> sequences: >> >> >>> dis.dis(lambda: '0123456789' + '0123456789' + '0') >> 1 0 LOAD_CONST 3 ('0123456789 >> 0123456789') >> 3 LOAD_CONST 2 ('0') >> 6 BINARY_ADD >> 7 RETURN_VALUE > > Interesting. Do you know why the limit is so low (especially for strings)? It isn't special-cased for strings. It just checks for a sequence length in general. The idea is to limit the size of .pyc files. Quote: If the new constant is a sequence, only folds when the size is below a threshold value. That keeps pyc files from becoming large in the presence of code like: (None,)*1000. The threshold of 20 isn't a tunable parameter. It's hard-coded in the source: size = PyObject_Size(newconst); if (size == -1) PyErr_Clear(); else if (size > 20) { Py_DECREF(newconst); return 0; } From ramit.prasad at jpmorgan.com Tue Jun 25 17:52:56 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 25 Jun 2013 15:52:56 +0000 Subject: [Tutor] Need help printing a pickled data In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474184DE2A9@SCACMX008.exchad.jpmchase.net> Peter Otten wrote: > Matt D wrote: > > > On 06/24/2013 07:17 PM, Alan Gauld wrote: > >> On 24/06/13 23:05, Matt D wrote: > >>> I have been unable to find a way to write pickled data to text file. > >> > >> Probably because pickled data is not plain text. > >> You need to use binary mode. However... > >> > >> > >>> def __init__(self, data): > >>> wx.PyEvent.__init__(self) > >>> self.SetEventType (wxDATA_EVENT) > >>> # and this is the actual data > >>> self.data = data > >>> with open('mypicklelog.txt','a') as log: > >>> log.write(self.data) > >> > >> Since you are not using pickle here, all you are really doing > >> is trying to write whatever data is to a text file that > >> happens to have 'pickle' in its name. > >> > >> When writing to a text file you need to write strings. > >> You have no guarantee that 'data' is a string. You should > >> probably convert it before writing it. Thats one of the > >> advantages of using real pickles - they take care of > >> that complication for you. > >> > >>> I cant figure out why these last two line dont write to the .txt file > >>> after the program has received the pickled Python dictionary? > >> > >> Pickle data has to be unpickled before you can use it. > >> Before you can write it back again you need to repickle it. > >> The code you posted does not show you producing and pickled > >> data nor indeed you reading any pickled data... > >> > >> If 'data' is indeed in pickle format you cannot simply write > >> it to a text file since Pickle is not in a text format. > >> > >> > > im sorry; some more code will clarify i think ; > > No, you aren't listening to Alan. The suggestive filename notwithstanding > > > with open('mypicklelog.txt','a') as log: > > log.write(self.data) > > will fail unless self.data is a string. Disregarding all other problems for > the moment, you need > > with open('mypicklelog.txt','ab') as log: # open in binary mode > pickle.dump(self.data, log) # serialize data and write to file > > where pickle.dump(obj, file) converts `obj` to a sequence of bytes before it > is written to `file`. Well I think self.data is some kind of container with a pickled string, given the code to unpickle it is: #message is equal to the "data" parameter in the "DataEvent" class message = event.data # unpickle the string pickled_dict = message.to_string() #separate the string into values for each text control (attrs is a pickle object) attrs = pickle.loads(pickled_dict) Try with open('mypicklelog.txt','ab') as log: # open in binary mode pickle.dump(pickle.loads(self.data.to_string()), log) # serialize data and write to file ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From md123 at nycap.rr.com Tue Jun 25 18:32:46 2013 From: md123 at nycap.rr.com (Matt D) Date: Tue, 25 Jun 2013 12:32:46 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> Message-ID: <51C9C62E.5060404@nycap.rr.com> > > with open('mypicklelog.txt','ab') as log: # open in binary mode > pickle.dump(self.data, log) # serialize data and write to file > > where pickle.dump(obj, file) converts `obj` to a sequence of bytes before it > is written to `file`. > I put this like this: class DataEvent(wx.PyEvent): # the values of the text fields get passed into the constructor inside of data def __init__(self, data): wx.PyEvent.__init__(self) # this line *binds* this class to a certain type of event, wxDATA_EVENT self.SetEventType (wxDATA_EVENT) # and this is the actual data self.data = data with open('mypicklelog.txt','ab') as log: # open in binary mode pickle.dump(self.data, log) # serialize data and write to file And I still get nothing. This has me super confused, I have trying at this for a long time and I have been reading the docs like http://docs.python.org/2/library/pickle.html And I still don't get it to work. So the C++ makes the pickle, this is from the comments in the C++ : /** * snapshot_du_handler. Writes traffic snapshots to a msg_queue based * on the HDU frame contents. The format used is that of a pickled * python dictionary allowing the other end of the queue to pick only * those fields of interest and ignore the rest. */ Then the python program (attached) program unpickles and repickles it? I attached the python program, if you have a minute or two please take a look, its not too long. -------------- next part -------------- A non-text attachment was scrubbed... Name: op25_traffic_pane.py Type: text/x-python Size: 9405 bytes Desc: not available URL: From md123 at nycap.rr.com Tue Jun 25 19:03:15 2013 From: md123 at nycap.rr.com (Matt D) Date: Tue, 25 Jun 2013 13:03:15 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474184DE2A9@SCACMX008.exchad.jpmchase.net> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DE2A9@SCACMX008.exchad.jpmchase.net> Message-ID: <51C9CD53.1010501@nycap.rr.com> > > Well I think self.data is some kind of container with a pickled string, > given the code to unpickle it is: > Exactly! This is what the C++ file 'pickle.h' creates to send to the Python GUI: /** * A pickled Python dictionary. Used to pass stuff to the UI. */ class pickle { public: /** * pickle constructor. * * \param frame_body A const_bit_queue representing the frame body. */ pickle(); /** * pickle virtual destructor. */ ~pickle(); /** * Add a key/value pair to the pickled dictionary */ void add(std::string key, std::string value); /** * Returns a string describing the Data Unit ID (DUID). */ std::string to_string() const; private: typedef std::map stringmap; stringmap map_; }; #endif /* INCLUDED_PICKLE_H */ I am pretty sure that it sends a C++ map of strings in a form that Python understands as a pickle. I put the code you gave me into the file so ill have to wait and see. meanwhile can you please take a look at this update() and tell me if you see something wrong because ever sense I tried using the array for logging the values from the TextCtrls the program is not updating meaning when the program receives the c++ map, or the pickle, I get nothing in the UI and I get nothing in the log. There got to be something wrong with the loop that I can not see. I attached the file so its not too much code here. I am pretty sure the problem is in the update(0) starts at line 210. -------------- next part -------------- A non-text attachment was scrubbed... Name: op25_traffic_pane.py Type: text/x-python Size: 9432 bytes Desc: not available URL: From ramit.prasad at jpmorgan.com Tue Jun 25 19:15:37 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 25 Jun 2013 17:15:37 +0000 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51C9C62E.5060404@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <51C9C62E.5060404@nycap.rr.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474184DE4A1@SCACMX008.exchad.jpmchase.net> Please leave attributions in so we know who is saying what. Matt D wrote: > [Ramit Prasad wrote] > > [Peter Otten wrote] > > > > with open('mypicklelog.txt','ab') as log: # open in binary mode > > pickle.dump(self.data, log) # serialize data and write to file > > > > where pickle.dump(obj, file) converts `obj` to a sequence of bytes before it > > is written to `file`. > > > > I put this like this: > > class DataEvent(wx.PyEvent): > # the values of the text fields get passed into the constructor > inside of data > def __init__(self, data): > wx.PyEvent.__init__(self) > # this line *binds* this class to a certain type of event, > wxDATA_EVENT > self.SetEventType (wxDATA_EVENT) > # and this is the actual data > self.data = data > with open('mypicklelog.txt','ab') as log: # open in binary mode > pickle.dump(self.data, log) # serialize data and write to file > > > And I still get nothing. This has me super confused, I have trying at > this for a long time and I have been reading the docs like > > http://docs.python.org/2/library/pickle.html > > And I still don't get it to work. So the C++ makes the pickle, this is > from the comments in the C++ : > > /** > * snapshot_du_handler. Writes traffic snapshots to a msg_queue based > * on the HDU frame contents. The format used is that of a pickled > * python dictionary allowing the other end of the queue to pick only > * those fields of interest and ignore the rest. > */ > > Then the python program (attached) program unpickles and repickles it? > I attached the python program, if you have a minute or two please take a > look, its not too long. The problem is that what gets sent across the queue is actually a container of some kind that has a pickled string. The comments in the code are just wrong. The key is following display_data which is correct. # unpickle the string pickled_dict = message.to_string() This is actually retrieving a string (or bytes more accurately) OF pickled data from some message or container object. These bytes then needs to be unpickled. #separate the string into values for each text control (attrs is a pickle object) attrs = pickle.loads(pickled_dict) Here the pickled data (as bytes/string) are unpickled and attrs is a Python dictionary (not a "pickle object"). *I use bytes/string interchangeably because in Python 2 they are the same. In Python 3 and semantically, they are different so the differentiation is important. The real question is why do you want this pickle in a file? I am not sure it will be easy to pull out and reuse anyway. Given your experience level, I think this is a lot of work for something that you are unlikely to be able to easily use. I think it would be more useful to `log.write(repr(attrs))`. Once you have the bytes of pickled data, just write that to file. with open('mypicklelog.txt','ab') as log: # All pickles will run together because there is no spacing. log.write(self.data.to_string()) Again, I think you would be better off with the repr() with open('mypicklelog.txt','ab') as log: log.write(repr(pickle.loads(self.data.to_string()))) ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Tue Jun 25 19:54:51 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 25 Jun 2013 18:54:51 +0100 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51C9C62E.5060404@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <51C9C62E.5060404@nycap.rr.com> Message-ID: On 25/06/13 17:32, Matt D wrote: > self.data = data > with open('mypicklelog.txt','ab') as log: # open in binary mode > pickle.dump(self.data, log) # serialize data and write to file > > > And I still get nothing. Define 'nothing'. Does the file exist? Does it have anything in it? Does self.data exist - what does it look like if you print it? Are there any error messages? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmorgan.com Tue Jun 25 20:02:33 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 25 Jun 2013 18:02:33 +0000 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51C9CD53.1010501@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DE2A9@SCACMX008.exchad.jpmchase.net> <51C9CD53.1010501@nycap.rr.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474184DE5EC@SCACMX008.exchad.jpmchase.net> Again, please leave in attributions. Matt D wrote: > [Ramit Prasad wrote] > > > > Well I think self.data is some kind of container with a pickled string, > > given the code to unpickle it is: > > > Exactly! This is what the C++ file 'pickle.h' creates to send to the > Python GUI: Not really. > > > /** > * A pickled Python dictionary. Used to pass stuff to the UI. > */ > class pickle > { > [snip C++ code] > > }; You can call it a pickle, but it is not actually a pickle. It is a wrapper around pickled data. That is *not* the same thing. > > #endif /* INCLUDED_PICKLE_H */ > > I am pretty sure that it sends a C++ map of strings in a form that > Python understands as a pickle. I put the code you gave me into the > file so ill have to wait and see. > meanwhile can you please take a look at this update() and tell me if you > see something wrong because ever sense I tried using the array for > logging the values from the TextCtrls the program is not updating > meaning when the program receives the c++ map, or the pickle, I get > nothing in the UI and I get nothing in the log. There got to be > something wrong with the loop that I can not see. I attached the file > so its not too much code here. I am pretty sure the problem is in the > update(0) starts at line 210. > I have 2 concerns. 1. Based on your results, I doubt if you can call to_string more than once 2. I don't think it's a good idea to log the pickle from the DataEvent.__init__. You should do all logging from update or display_data. Look at my most recent email it gives better code. If you really want to store the pickle data then write pickled_dict to file and remove the logging code from the DataEvent.__init__. I suspect that will give you the results you want again. ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From wprins at gmail.com Tue Jun 25 20:04:25 2013 From: wprins at gmail.com (Walter Prins) Date: Tue, 25 Jun 2013 19:04:25 +0100 Subject: [Tutor] looking for volunteers with testing simple python program In-Reply-To: References: <51BF1A97.6000404@gmail.com> Message-ID: Hi Alexander On 23 June 2013 22:46, Alexander wrote: > I guess this is for testing, but I have a question. If somebody sends you > their .pub file (email or otherwise over internet), and a villainous third > party intercepts that .pub file, will they be able to decrypt the data sent > over this program? While I've not looked at the actual program, it appears to use standard public key encryption techniques. The way public key encryption works is essentially that entities always have a public and a private key. The public keys are always published and freely available, and are used to *encrypt* messages for given individuals. Keys are essentially one-way, which means you cannot de-crypt a message encrypted with the same key it was encrypted with. Instead, only the received with the corresponding private key can decrypt the encrypted message. Hence, to answer you question: If a villainous third party intercepts the pub key, that doesn't help them in decrypting messages encrypted with that key. At best, they can also send you encrypted messages. If they wanted to decrypt messages meant for you they'd have to somehow gain access to your private key. Regards Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From md123 at nycap.rr.com Tue Jun 25 20:30:33 2013 From: md123 at nycap.rr.com (Matt D) Date: Tue, 25 Jun 2013 14:30:33 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <51C9C62E.5060404@nycap.rr.com> Message-ID: <51C9E1C9.1000003@nycap.rr.com> On 06/25/2013 01:54 PM, Alan Gauld wrote: > On 25/06/13 17:32, Matt D wrote: > >> self.data = data >> with open('mypicklelog.txt','ab') as log: # open in binary mode >> pickle.dump(self.data, log) # serialize data and write to >> file >> >> >> And I still get nothing. > > Define 'nothing'. > > Does the file exist? > Does it have anything in it? > Does self.data exist - what does it look like if you print it? > Are there any error messages? > Yeh nothing as in an empty file. The file is there but there is nothing written in it. self.data exists. that the problem if have is printing what is in it so i dont know what it looks like. No error messages currently in the terminal. From alan.gauld at btinternet.com Tue Jun 25 20:51:19 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 25 Jun 2013 19:51:19 +0100 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51C9E1C9.1000003@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <51C9C62E.5060404@nycap.rr.com> <51C9E1C9.1000003@nycap.rr.com> Message-ID: On 25/06/13 19:30, Matt D wrote: >> Does the file exist? >> Does it have anything in it? >> Does self.data exist - what does it look like if you print it? >> Are there any error messages? >> > Yeh nothing as in an empty file. The file is there but there is nothing > written in it. OK, Try deleting the file and rerunning the program. Check that the file is recreated and is still empty. > self.data exists. that the problem if have is printing > what is in it so i dont know what it looks like. Try print repr(self.data) See if that helps. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From md123 at nycap.rr.com Tue Jun 25 21:45:03 2013 From: md123 at nycap.rr.com (Matt D) Date: Tue, 25 Jun 2013 15:45:03 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474184DE4A1@SCACMX008.exchad.jpmchase.net> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <51C9C62E.5060404@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DE4A1@SCACMX008.exchad.jpmchase.net> Message-ID: <51C9F33F.8000708@nycap.rr.com> > > The real question is why do you want this pickle in a file? I am not sure > it will be easy to pull out and reuse anyway. Given your experience level, > I think this is a lot of work for something that you are unlikely to be able > to easily use. I think it would be more useful to `log.write(repr(attrs))`. > > Once you have the bytes of pickled data, just write that to file. > > with open('mypicklelog.txt','ab') as log: > # All pickles will run together because there is no spacing. > log.write(self.data.to_string()) > > > Again, I think you would be better off with the repr() > with open('mypicklelog.txt','ab') as log: > log.write(repr(pickle.loads(self.data.to_string()))) > > OK thanks. what i did is went back to the old logger where everything was working. and then i put self.update(attrs) with open('mypicklelog.txt','ab') as log: log.write(repr(attrs)) to try to lay eyes on the pickle. What i really need is a way to test this GUI without waiting so long. I was thinking if i could get a hold of one of the c++ maps i could make a small program that would enable me to send it to the python gui at will; to test the gui. I am not sure if there is a way around this testing difficulty because two of the TextCtrl fields are empty. This is because currently the c++ is only sending in the container the contents of the Header Data Unit (HDU). In digital radio the transmission consists of frames, the HDU is one of them, as the name suggest it is the first. But the Logical Data Unit 1 (LDU1) contains the source and destination id data that ultimately i need to get in the UI. So I am going to have to get into the c++ map stuff and get familiar with how this pickle process works anyway. This is pass/fail thing, it doesn't matter if my code is 'ugly' or whatever and I have time so it shouldn't be impossible. From ramit.prasad at jpmorgan.com Tue Jun 25 23:11:27 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 25 Jun 2013 21:11:27 +0000 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51C9F33F.8000708@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <51C9C62E.5060404@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DE4A1@SCACMX008.exchad.jpmchase.net> <51C9F33F.8000708@nycap.rr.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474184DEA8A@SCACMX008.exchad.jpmchase.net> Matt D write: > [Ramit Prasad wrote:] > > > > The real question is why do you want this pickle in a file? I am not sure > > it will be easy to pull out and reuse anyway. Given your experience level, > > I think this is a lot of work for something that you are unlikely to be able > > to easily use. I think it would be more useful to `log.write(repr(attrs))`. > > > > Once you have the bytes of pickled data, just write that to file. > > > > with open('mypicklelog.txt','ab') as log: > > # All pickles will run together because there is no spacing. > > log.write(self.data.to_string()) > > > > > > Again, I think you would be better off with the repr() > > with open('mypicklelog.txt','ab') as log: > > log.write(repr(pickle.loads(self.data.to_string()))) > > > > > > OK thanks. what i did is went back to the old logger where everything > was working. and then i put > > self.update(attrs) > with open('mypicklelog.txt','ab') as log: > log.write(repr(attrs)) > > to try to lay eyes on the pickle. What i really need is a way to test > this GUI without waiting so long. I was thinking if i could get a hold > of one of the c++ maps i could make a small program that would enable me > to send it to the python gui at will; to test the gui. That is not as simple as it sounds. How would you send it to the UI? Would you be using the same process? Are you hard coding the pickle location? Why not just hard code the dictionary instead and pass that? If you are using a separate process how do you plan to get the information to the UI? Files? Why not just hard code (or use a non-pickle format for file) and generate the dictionary needed? Are you going to use sockets for IPC/network communication? That is probably even more difficult. > > I am not sure if there is a way around this testing difficulty because > two of the TextCtrl fields are empty. This is because currently the c++ > is only sending in the container the contents of the Header Data Unit > (HDU). In digital radio the transmission consists of frames, the HDU is > one of them, as the name suggest it is the first. But the Logical Data > Unit 1 (LDU1) contains the source and destination id data that > ultimately i need to get in the UI. So I am going to have to get into > the c++ map stuff and get familiar with how this pickle process works > anyway. This is pass/fail thing, it doesn't matter if my code is 'ugly' > or whatever and I have time so it shouldn't be impossible. You are better off polling a directory for a text file with a specified format and reading that file. Construct the dictionary from that file and call update with it. Delete the file when done. An even easier solution is to call update() with a hard coded dictionary in TrafficPane.__init__. Or create a temporary button with a function that generates random data for the UI and passes it to update. I really think focusing on pickle is really a red herring and not related to any bit you are interested in. ~Ramit P This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rhettnaxel at gmail.com Tue Jun 25 23:58:10 2013 From: rhettnaxel at gmail.com (Alexander) Date: Tue, 25 Jun 2013 17:58:10 -0400 Subject: [Tutor] looking for volunteers with testing simple python program In-Reply-To: References: <51BF1A97.6000404@gmail.com> Message-ID: On Tue, Jun 25, 2013 at 2:04 PM, Walter Prins wrote: > Hi Alexander > > > On 23 June 2013 22:46, Alexander wrote: > >> I guess this is for testing, but I have a question. If somebody sends you >> their .pub file (email or otherwise over internet), and a villainous third >> party intercepts that .pub file, will they be able to decrypt the data sent >> over this program? > > > While I've not looked at the actual program, it appears to use standard > public key encryption techniques. The way public key encryption works is > essentially that entities always have a public and a private key. The > public keys are always published and freely available, and are used to > *encrypt* messages for given individuals. Keys are essentially one-way, > which means you cannot de-crypt a message encrypted with the same key it > was encrypted with. Instead, only the received with the corresponding > private key can decrypt the encrypted message. > > Hence, to answer you question: If a villainous third party intercepts the > pub key, that doesn't help them in decrypting messages encrypted with that > key. At best, they can also send you encrypted messages. If they wanted to > decrypt messages meant for you they'd have to somehow gain access to your > private key. > > Regards > > Walter > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Thanks for your response, Walter. -- Alexander Etter -------------- next part -------------- An HTML attachment was scrubbed... URL: From md123 at nycap.rr.com Wed Jun 26 02:35:03 2013 From: md123 at nycap.rr.com (Matt D) Date: Tue, 25 Jun 2013 20:35:03 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474184DE5EC@SCACMX008.exchad.jpmchase.net> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DE2A9@SCACMX008.exchad.jpmchase.net> <51C9CD53.1010501@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DE5EC@SCACMX008.exchad.jpmchase.net> Message-ID: <51CA3737.70909@nycap.rr.com> On 06/25/2013 02:02 PM, Prasad, Ramit wrote: > Again, please leave in attributions. > > Matt D wrote: >> [Ramit Prasad wrote] >>> >>> Well I think self.data is some kind of container with a pickled string, >>> given the code to unpickle it is: >>> >> Exactly! This is what the C++ file 'pickle.h' creates to send to the >> Python GUI: > > Not really. > >> >> >> /** >> * A pickled Python dictionary. Used to pass stuff to the UI. >> */ >> class pickle >> { >> > [snip C++ code] >> >> }; > > You can call it a pickle, but it is not actually a pickle. It is > a wrapper around pickled data. That is *not* the same thing. > confusing so that code above is the wrapper of what the code below makes, which is pickled data?: pickle::pickle() { } pickle::~pickle() { } void pickle::add(string key, string value) { map_[key] = value; } string pickle::to_string() const { size_t n = 1; ostringstream os; os << "(dp" << n++ << endl; for(stringmap::const_iterator i(map_.begin()); i != map_.end(); ++i) { os << "S'" << i->first << "'" << endl; os << "p" << n++ << endl; os << "S'" << i->second << "'" << endl; os << "p" << n++ << endl << "s"; } os << "." << endl; return os.str(); } From md123 at nycap.rr.com Wed Jun 26 03:06:43 2013 From: md123 at nycap.rr.com (Matt D) Date: Tue, 25 Jun 2013 21:06:43 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474184DEA8A@SCACMX008.exchad.jpmchase.net> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <51C9C62E.5060404@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DE4A1@SCACMX008.exchad.jpmchase.net> <51C9F33F.8000708@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DEA8A@SCACMX008.exchad.jpmchase.net> Message-ID: <51CA3EA3.8000004@nycap.rr.com> > You are better off polling a directory for a text file with a > specified format and reading that file. Construct the dictionary from > that file and call update with it. Delete the file when done. > > An even easier solution is to call update() with a hard coded > dictionary in TrafficPane.__init__. Or create a temporary button with > a function that generates random data for the UI and passes it to > update. > > I really think focusing on pickle is really a red herring and not > related to any bit you are interested in. > > Like I said, currently two of the the TextCtrl fields, don't receive their values because the 'data_unit' object ldu1.h, containing those two values, does not go through the pickling process, or more precisely it does not have an '#include pickle.h'. Note that the Python UI gets its display values from the 'data_unit' object hdu.h which has the '#include pickle.h' and its called like: std::string hdu::snapshot() const { pickle p; p.add("duid", duid_str()); p.add("nac", nac_str()); p.add("mfid", mfid_str()); p.add("algid", algid_str()); p.add("kid", kid_str()); p.add("mi", mi_str()); p.add("tgid", tgid_str()); return p.to_string(); } And then the strings are given values like this: string hdu::algid_str() const { const size_t ALGID_BITS[] = { 356, 357, 360, 361, 374, 375, 376, 377 }; const size_t ALGID_BITS_SZ = sizeof(ALGID_BITS) / sizeof(ALGID_BITS[0]); uint8_t algid = extract(frame_body(), ALGID_BITS, ALGID_BITS_SZ); return lookup(algid, ALGIDS, ALGIDS_SZ); } which seem to me to be rather lengthy but thats the way its done. So given that I have to do something like this for the another data_unit object, in order to pass the two missing values to the UI, do you still think I can escape this pickle issue? From steve at pearwood.info Wed Jun 26 03:12:39 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Jun 2013 11:12:39 +1000 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51C9E1C9.1000003@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <51C9C62E.5060404@nycap.rr.com> <51C9E1C9.1000003@nycap.rr.com> Message-ID: <51CA4007.1030405@pearwood.info> On 26/06/13 04:30, Matt D wrote: > On 06/25/2013 01:54 PM, Alan Gauld wrote: >> On 25/06/13 17:32, Matt D wrote: >> >>> self.data = data >>> with open('mypicklelog.txt','ab') as log: # open in binary mode >>> pickle.dump(self.data, log) # serialize data and write to >>> file >>> >>> >>> And I still get nothing. >> >> Define 'nothing'. >> >> Does the file exist? >> Does it have anything in it? >> Does self.data exist - what does it look like if you print it? >> Are there any error messages? >> > Yeh nothing as in an empty file. The file is there but there is nothing > written in it. self.data exists. that the problem if have is printing > what is in it so i dont know what it looks like. No error messages > currently in the terminal. The obvious test is to confirm that you can see other output written to the log file. self.data = data with open('mypicklelog.txt','ab') as log: # open in binary mode log.write('before\n') pickle.dump(self.data, log) log.write('after\n') I still think it is silly to write pickled data to a log. Logs are for human-readable information, not arbitrary data. Even with text-mode pickle, it's still junk: py> import pickle py> data = {'a': None, 'b': 42} py> pickle.dumps(data, 0) "(dp0\nS'a'\np1\nNsS'b'\np2\nI42\ns." Why do you want to see rubbish like that inside your log file? Surely something like this is better? log.write("data = %r" % data) which will give you a line like this: data = {'a': None, 'b': 42} in your log, which is a million times more understandable than a pickle. -- Steven From marc.tompkins at gmail.com Wed Jun 26 03:25:17 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 25 Jun 2013 18:25:17 -0700 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51CA4007.1030405@pearwood.info> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <51C9C62E.5060404@nycap.rr.com> <51C9E1C9.1000003@nycap.rr.com> <51CA4007.1030405@pearwood.info> Message-ID: On Tue, Jun 25, 2013 at 6:12 PM, Steven D'Aprano wrote: > Why do you want to see rubbish like that inside your log file? Surely > something like this is better? > > log.write("data = %r" % data) > > which will give you a line like this: > > data = {'a': None, 'b': 42} > > > in your log, which is a million times more understandable than a pickle. > This conversation is starting to remind me of Arlo Guthrie's Motorcycle Song... http://www.youtube.com/watch?v=BvLtNBm1yyA "I don't want a pickle I just wanna ride on my motorcycle..." -------------- next part -------------- An HTML attachment was scrubbed... URL: From md123 at nycap.rr.com Wed Jun 26 03:25:54 2013 From: md123 at nycap.rr.com (Matt D) Date: Tue, 25 Jun 2013 21:25:54 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474184DEA8A@SCACMX008.exchad.jpmchase.net> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <51C9C62E.5060404@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DE4A1@SCACMX008.exchad.jpmchase.net> <51C9F33F.8000708@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DEA8A@SCACMX008.exchad.jpmchase.net> Message-ID: <51CA4322.4000309@nycap.rr.com> > > I really think focusing on pickle is really a red herring and not > related to any bit you are interested in. > > I guess I was under the impression that if I could get a copy of what came in on the thread i could find a way to make some other panel to send the data, (which looks like it would be in, rcvd_pckq or msg, or de??) over the same thread that the Class traffic_watcher_thread gets the rcvd_pckq. And if that didnt work, I could try have the display_data part of the UI open the file. And I really want to lay eyes on it so that I can know exactly what the UI is receiving. I guess I will focus for now more on the logger, and the button for choosing a file for now because it is probably an easier way to get familiar with Python but sooner or later I have got to figure out this pickling process because i need to use it to pass more data into the UI from the c++ code. From md123 at nycap.rr.com Wed Jun 26 03:32:44 2013 From: md123 at nycap.rr.com (Matt D) Date: Tue, 25 Jun 2013 21:32:44 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51CA4007.1030405@pearwood.info> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <51C9C62E.5060404@nycap.rr.com> <51C9E1C9.1000003@nycap.rr.com> <51CA4007.1030405@pearwood.info> Message-ID: <51CA44BC.1020108@nycap.rr.com> > > I still think it is silly to write pickled data to a log. Logs are for > human-readable information, not arbitrary data. Even with text-mode > pickle, it's still junk: > > py> import pickle > py> data = {'a': None, 'b': 42} > py> pickle.dumps(data, 0) > "(dp0\nS'a'\np1\nNsS'b'\np2\nI42\ns." > > > Why do you want to see rubbish like that inside your log file? Surely > something like this is better? > > log.write("data = %r" % data) > > which will give you a line like this: > > data = {'a': None, 'b': 42} > > > in your log, which is a million times more understandable than a pickle. > > Yes the later would be better for my eyes to see whats going on there, and that is necessary for me. But I also want something that will mimic, or a copy of, what the UI is currently receiving not to look at, but to have, at a later time, the program open, or send to the program with another program, in order to test the functionality of the UI. From steve at pearwood.info Wed Jun 26 03:37:33 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Jun 2013 11:37:33 +1000 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51C9CD53.1010501@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DE2A9@SCACMX008.exchad.jpmchase.net> <51C9CD53.1010501@nycap.rr.com> Message-ID: <51CA45DD.8080605@pearwood.info> On 26/06/13 03:03, Matt D wrote: > meanwhile can you please take a look at this update() and tell me if you > see something wrong because ever sense I tried using the array for > logging the values from the TextCtrls the program is not updating > meaning when the program receives the c++ map, or the pickle, I get > nothing in the UI and I get nothing in the log. There got to be > something wrong with the loop that I can not see. I attached the file > so its not too much code here. Please don't dump big blobs of code on us, attachment or inline doesn't matter. Please follow the principles here: http://sscce.org/ 1) it will make you a better programmer, and 2) it will make it easier for us to help you. -- Steven From eryksun at gmail.com Wed Jun 26 04:33:30 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 25 Jun 2013 22:33:30 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51CA3737.70909@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DE2A9@SCACMX008.exchad.jpmchase.net> <51C9CD53.1010501@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DE5EC@SCACMX008.exchad.jpmchase.net> <51CA3737.70909@nycap.rr.com> Message-ID: On Tue, Jun 25, 2013 at 8:35 PM, Matt D wrote: > so that code above is the wrapper of what the code below makes, which is > pickled data?: > > string > pickle::to_string() const > { > size_t n = 1; > ostringstream os; > os << "(dp" << n++ << endl; > for(stringmap::const_iterator i(map_.begin()); i != map_.end(); ++i) { > os << "S'" << i->first << "'" << endl; > os << "p" << n++ << endl; > os << "S'" << i->second << "'" << endl; > os << "p" << n++ << endl << "s"; > } > os << "." << endl; > return os.str(); > } That's a protocol 0 dict. Between MARK "(" and STOP "." is a DICT "d". Each key/value is a STRING "S". After pushing a key/value pair on the stack they're added to the dict by SETITEM "s". The PUT "p" operations store the stack top into the 'memo' (scratch array), but they seem superfluous since there's no matching GET (g). For example: >>> pkl = "(dS'key1'\nS'val1'\nsS'key2'\nS'val2'\ns." >>> pickle.loads(pkl) {'key2': 'val2', 'key1': 'val1'} >>> pickletools.dis(pkl) 0: ( MARK 1: d DICT (MARK at 0) 2: S STRING 'key1' 10: S STRING 'val1' 18: s SETITEM 19: S STRING 'key2' 27: S STRING 'val2' 35: s SETITEM 36: . STOP highest protocol among opcodes = 0 FYI, this appears to be the repository for the above C++ (pickle::to_string, hdu::snapshot): http://op25.osmocom.org/trac/wiki.png/browser/trunk/blocks/src/lib But I've only glanced at the code and don't know GNU Radio from GNU Gnews. From cybervigilante at gmail.com Wed Jun 26 07:32:58 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 25 Jun 2013 22:32:58 -0700 Subject: [Tutor] commas on numeric input Message-ID: I thought I read somewhere that Py3 can be set to accept commas as part of numeric input, without needing to filter, but now I can't find the reference. Is there such a feature, which would be useful, or did I see it as part of some numeric module and misremember it? -- Jim Never run on gravel with a lightbulb in your mouth (personal experience - don't ask.) From __peter__ at web.de Wed Jun 26 08:23:17 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Jun 2013 08:23:17 +0200 Subject: [Tutor] commas on numeric input References: Message-ID: Jim Mooney wrote: > I thought I read somewhere that Py3 can be set to accept commas as > part of numeric input, without needing to filter, but now I can't find > the reference. Is there such a feature, which would be useful, or did > I see it as part of some numeric module and misremember it? You can set a locale that recognizes the comma as thousands separator: >>> locale.setlocale(locale.LC_ALL, "en_US.UTF-8") 'en_US.UTF-8' >>> locale.atoi("1,234,567") 1234567 >>> locale.atof("1,234.56") 1234.56 But be aware that this convention is not universal: >>> locale.setlocale(locale.LC_ALL, "de_DE.UTF-8") 'de_DE.UTF-8' >>> locale.atof("1,234.56") 1.23456 From eryksun at gmail.com Wed Jun 26 15:20:41 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 26 Jun 2013 09:20:41 -0400 Subject: [Tutor] commas on numeric input In-Reply-To: References: Message-ID: On Wed, Jun 26, 2013 at 2:23 AM, Peter Otten <__peter__ at web.de> wrote: > Jim Mooney wrote: > >> I thought I read somewhere that Py3 can be set to accept commas as >> part of numeric input, without needing to filter, but now I can't find >> the reference. Is there such a feature, which would be useful, or did >> I see it as part of some numeric module and misremember it? > > You can set a locale that recognizes the comma as thousands separator: > >>>> locale.setlocale(locale.LC_ALL, "en_US.UTF-8") > 'en_US.UTF-8' >>>> locale.atoi("1,234,567") > 1234567 >>>> locale.atof("1,234.56") > 1234.56 On Windows this locale is "enu_usa". You can also specify one of Microsoft's code pages, such as 1252 (Western European): >>> locale.setlocale(locale.LC_NUMERIC, 'enu_usa.1252') 'English_United States.1252' >>> locale.atof('1,234') 1234.0 >>> locale.setlocale(locale.LC_NUMERIC, 'deu_deu.1252') 'German_Germany.1252' >>> locale.atof('1,234') 1.234 There are variations allowed, such as "english_us", or the long form that you see in the result, but generally you can use the 3-letter language/country abbreviations in the last two columns of the table found here: http://msdn.microsoft.com/en-us/goglobal/bb896001 code pages: http://msdn.microsoft.com/en-us/library/dd317756 Note that you can't use code page 65001 (UTF-8) in a locale setting. As to the conversion, locale.atof() is simple enough to include here: def atof(string, func=float): "Parses a string as a float according to the locale settings." #First, get rid of the grouping ts = localeconv()['thousands_sep'] if ts: string = string.replace(ts, '') #next, replace the decimal point with a dot dd = localeconv()['decimal_point'] if dd: string = string.replace(dd, '.') #finally, parse the string return func(string) def atoi(str): "Converts a string to an integer according to the locale settings." return atof(str, int) Notice the undocumented argument for the result type: >>> locale.atof('1,234', decimal.Decimal) Decimal('1234') >>> locale.atof('1,234', fractions.Fraction) Fraction(1234, 1) I'd advise writing your own function instead of relying on an undocumented argument. For locale-aware formatting there's the 'n' code: >>> format(1234, 'n') # like 'd' '1,234' >>> format(1234.1234, '.8n') # like 'g' '1,234.1234' From nsivaram.net at gmail.com Wed Jun 26 17:36:48 2013 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Wed, 26 Jun 2013 21:06:48 +0530 Subject: [Tutor] mapping header row to data rows in file Message-ID: <87d2r8dgtr.fsf@gmail.com> I have a file with 100s of columns going thus name age sex .... AA 23 M ... AB 26 M .... while I can read the first row as header = file.readline().split() how do I get to map each col name in header to the subsequent data rows? As in name = AA age = 23 sex = M when processing the first data record and then refreshing it with the 2nd data row after I process it in a loop? Is the zip function, the way to go? sivaram -- From __peter__ at web.de Wed Jun 26 18:10:47 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Jun 2013 18:10:47 +0200 Subject: [Tutor] mapping header row to data rows in file References: <87d2r8dgtr.fsf@gmail.com> Message-ID: Sivaram Neelakantan wrote: > I have a file with 100s of columns going thus > > name age sex .... > AA 23 M ... > AB 26 M .... > > while I can read the first row as > > header = file.readline().split() > > how do I get to map each col name in header to the subsequent data rows? > As in > name = AA > age = 23 > sex = M > > when processing the first data record and then refreshing it with the 2nd > data row after I process it in a loop? Is the zip function, the way to > go? zip() is a good starting point if you want to put the rows into dicts: def reader(instream): rows = (line.split() for line in instream) names = next(rows) return (dict(zip(names, values)) for values in rows) with open(FILENAME, "r") as f: for row in reader(f): print row["name"] If you are sure that the column headers are valid python identifiers you can alternatively use a namedtuple: from collections import namedtuple def reader(instream): rows = (line.split() for line in instream) names = next(rows) Row = namedtuple("Row", names) return (Row(*values) for values in rows) with open(FILENAME, "r") as f: for row in reader(f): print row.name You might also have a look at csv.DictReader. From md123 at nycap.rr.com Wed Jun 26 18:34:18 2013 From: md123 at nycap.rr.com (Matt D) Date: Wed, 26 Jun 2013 12:34:18 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DE2A9@SCACMX008.exchad.jpmchase.net> <51C9CD53.1010501@nycap.rr.com> <5B80DD153D7D744689F57F4FB69AF474184DE5EC@SCACMX008.exchad.jpmchase.net> <51CA3737.70909@nycap.rr.com> Message-ID: <51CB180A.1020802@nycap.rr.com> On 06/25/2013 10:33 PM, eryksun wrote: > On Tue, Jun 25, 2013 at 8:35 PM, Matt D wrote: >> so that code above is the wrapper of what the code below makes, which is >> pickled data?: >> >> string >> pickle::to_string() const >> { >> size_t n = 1; >> ostringstream os; >> os << "(dp" << n++ << endl; >> for(stringmap::const_iterator i(map_.begin()); i != map_.end(); ++i) { >> os << "S'" << i->first << "'" << endl; >> os << "p" << n++ << endl; >> os << "S'" << i->second << "'" << endl; >> os << "p" << n++ << endl << "s"; >> } >> os << "." << endl; >> return os.str(); >> } > > That's a protocol 0 dict. Between MARK "(" and STOP "." is a DICT "d". > Each key/value is a STRING "S". After pushing a key/value pair on the > stack they're added to the dict by SETITEM "s". The PUT "p" operations > store the stack top into the 'memo' (scratch array), but they seem > superfluous since there's no matching GET (g). > > For example: > > >>> pkl = "(dS'key1'\nS'val1'\nsS'key2'\nS'val2'\ns." > > >>> pickle.loads(pkl) > {'key2': 'val2', 'key1': 'val1'} > > >>> pickletools.dis(pkl) > 0: ( MARK > 1: d DICT (MARK at 0) > 2: S STRING 'key1' > 10: S STRING 'val1' > 18: s SETITEM > 19: S STRING 'key2' > 27: S STRING 'val2' > 35: s SETITEM > 36: . STOP > highest protocol among opcodes = 0 > > > FYI, this appears to be the repository for the above C++ > (pickle::to_string, hdu::snapshot): > > http://op25.osmocom.org/trac/wiki.png/browser/trunk/blocks/src/lib > > But I've only glanced at the code and don't know GNU Radio from GNU Gnews. > Thanks! Yes I am working with a decoder used in GNU radio. Python is used for the UI while the computationally intense stuff is done in C++ blocks. Trying to learn this hybrid C++/Python system really is a crash course. From nsivaram.net at gmail.com Wed Jun 26 19:51:56 2013 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Wed, 26 Jun 2013 23:21:56 +0530 Subject: [Tutor] mapping header row to data rows in file References: <87d2r8dgtr.fsf@gmail.com> Message-ID: <878v1wdakj.fsf@gmail.com> On Wed, Jun 26 2013,Peter Otten wrote: [snipped 22 lines] > zip() is a good starting point if you want to put the rows into dicts: > > def reader(instream): > rows = (line.split() for line in instream) > names = next(rows) > return (dict(zip(names, values)) for values in rows) > > with open(FILENAME, "r") as f: > for row in reader(f): > print row["name"] > > If you are sure that the column headers are valid python identifiers you can > alternatively use a namedtuple: > > from collections import namedtuple > > def reader(instream): > rows = (line.split() for line in instream) > names = next(rows) > Row = namedtuple("Row", names) > return (Row(*values) for values in rows) > > with open(FILENAME, "r") as f: > for row in reader(f): > print row.name > > You might also have a look at csv.DictReader. [snipped 7 lines] Thanks for your suggestions and examples, I'll try them out. sivaram -- From jacklittlemc at yahoo.com Wed Jun 26 20:23:26 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Wed, 26 Jun 2013 11:23:26 -0700 (PDT) Subject: [Tutor] Repeat Until Dead Message-ID: <1372271006.55888.YahooMailNeo@web124501.mail.ne1.yahoo.com> In a combat system, how would I have a certain raw_input repeat until the enemy is dead? Thanks a ton, Jack -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Wed Jun 26 20:28:46 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 26 Jun 2013 11:28:46 -0700 Subject: [Tutor] Repeat Until Dead In-Reply-To: <1372271006.55888.YahooMailNeo@web124501.mail.ne1.yahoo.com> References: <1372271006.55888.YahooMailNeo@web124501.mail.ne1.yahoo.com> Message-ID: On Wed, Jun 26, 2013 at 11:23 AM, Jack Little wrote: > In a combat system, how would I have a certain raw_input repeat until the > enemy is dead? > Sounds like a classic case for a "while" loop. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwpolska at gmail.com Wed Jun 26 20:30:56 2013 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Wed, 26 Jun 2013 20:30:56 +0200 Subject: [Tutor] Repeat Until Dead In-Reply-To: <1372271006.55888.YahooMailNeo@web124501.mail.ne1.yahoo.com> References: <1372271006.55888.YahooMailNeo@web124501.mail.ne1.yahoo.com> Message-ID: On Wed, Jun 26, 2013 at 8:23 PM, Jack Little wrote: > In a combat system, how would I have a certain raw_input repeat until the > enemy is dead? > > > Thanks a ton, > Jack Something like this: while enemyalive: raw_input('Action? ') -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From dahlx335 at gmail.com Wed Jun 26 21:32:56 2013 From: dahlx335 at gmail.com (Justin Dahl) Date: Wed, 26 Jun 2013 14:32:56 -0500 Subject: [Tutor] Rbtg da sneak Message-ID: Invc. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dahlx335 at gmail.com Wed Jun 26 21:32:56 2013 From: dahlx335 at gmail.com (Justin Dahl) Date: Wed, 26 Jun 2013 14:32:56 -0500 Subject: [Tutor] Nf Message-ID: Bl u -------------- next part -------------- An HTML attachment was scrubbed... URL: From dahlx335 at gmail.com Wed Jun 26 21:32:56 2013 From: dahlx335 at gmail.com (Justin Dahl) Date: Wed, 26 Jun 2013 14:32:56 -0500 Subject: [Tutor] Hnoddlgfob Message-ID: Ce xnocr u -------------- next part -------------- An HTML attachment was scrubbed... URL: From bicofino at gmail.com Thu Jun 27 00:07:33 2013 From: bicofino at gmail.com (Danilo Chilene) Date: Wed, 26 Jun 2013 19:07:33 -0300 Subject: [Tutor] Repeat Until Dead In-Reply-To: References: <1372271006.55888.YahooMailNeo@web124501.mail.ne1.yahoo.com> Message-ID: Hello, Try something like this: coin = raw_input('Insert coins:\n') while(coin > 0): coin = int(coin)-1 print 'You have {0} coin(s)'.format(coin) $ python teste.py Insert coins: 2 You have 1 coin(s) You have 0 coin(s) On Wed, Jun 26, 2013 at 3:30 PM, Chris ?Kwpolska? Warrick < kwpolska at gmail.com> wrote: > On Wed, Jun 26, 2013 at 8:23 PM, Jack Little > wrote: > > In a combat system, how would I have a certain raw_input repeat until the > > enemy is dead? > > > > > > Thanks a ton, > > Jack > > Something like this: > > while enemyalive: > raw_input('Action? ') > > -- > Kwpolska | GPG KEY: 5EAAEA16 > stop html mail | always bottom-post > http://asciiribbon.org | http://caliburn.nl/topposting.html > _______________________________________________ > 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 alan.gauld at btinternet.com Thu Jun 27 01:23:52 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 27 Jun 2013 00:23:52 +0100 Subject: [Tutor] Repeat Until Dead In-Reply-To: References: <1372271006.55888.YahooMailNeo@web124501.mail.ne1.yahoo.com> Message-ID: On 26/06/13 23:07, Danilo Chilene wrote: > Hello, > > Try something like this: > > coin = raw_input('Insert coins:\n') > > while(coin > 0): > coin = int(coin)-1 > print 'You have {0} coin(s)'.format(coin) Note you did not convert the original raw_input value to an int. Also you keep on converting coins to int inside the loop even though it already is one after the first iteration. However... This only loops for as many times as coin is set at the beginning. The OP needs the raw_input inside the loop so it would need to look like this: coin = int( raw_input('Insert coins:\n') ) while(coin > 0): print 'You have {0} coin(s)'.format(coin) coin = int( raw_input('Insert coins:\n') ) What we don't know, because the OP didn't tell us, is how he detects "death"... I hope he can adapt... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From datar at wisc.edu Wed Jun 26 19:05:42 2013 From: datar at wisc.edu (Makarand Datar) Date: Wed, 26 Jun 2013 12:05:42 -0500 Subject: [Tutor] using python for parsing Message-ID: Hi, I know practically nothing about python. I know how to install it and all that kind of stuff. I want to use python for parsing a text file. The task is to read in a text file, and write out another text file that is written in some particular way using the data from the file that was read in. The question is how do I go about this? What part of python documentation, or a book I should read etc. I dont want to start reading a python book from the first page. I just want to do this parsing task and I will learn about whatever I need to as I encounter it. Thank you for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From khosrodarroudi102 at msn.com Wed Jun 26 22:45:30 2013 From: khosrodarroudi102 at msn.com (kdarroud) Date: Wed, 26 Jun 2013 13:45:30 -0700 (PDT) Subject: [Tutor] Typing 'h', 'e', 'l', 'p', 'Enter' in a window Message-ID: <1372279530013-5022574.post@n6.nabble.com> In our Windows machine, we have several windows open. Using Python, how can I type 'h', 'e', 'l', 'p', 'Enter' in a specific window that is open? Thank you -- View this message in context: http://python.6.x6.nabble.com/Typing-h-e-l-p-Enter-in-a-window-tp5022574.html Sent from the Python - tutor mailing list archive at Nabble.com. From li.wanbo.ulg at gmail.com Wed Jun 26 11:56:16 2013 From: li.wanbo.ulg at gmail.com (Wanbo Li) Date: Wed, 26 Jun 2013 11:56:16 +0200 Subject: [Tutor] Install BTrees Message-ID: <5C245A88-D98B-499B-928D-51B4BD57042B@gmail.com> Dear all, I am trying to install BTrees package on Mac OS X 10.7.5. And my python version is 2.7.3 So I used 'easy_install ZODB' and 'easy_install BTrees' to install the packages. Then when I import modules from the package, I encounter the following error: >>> from BTrees.OOBTree import OOBTree Traceback (most recent call last): File "", line 1, in File "/Users/wanbo/Library/Python/2.7/lib/python/site-packages/BTrees-4.0.8-py2.7-macosx-10.6-intel.egg/BTrees/__init__.py", line 16, in import BTrees.Interfaces File "/Users/wanbo/Library/Python/2.7/lib/python/site-packages/BTrees-4.0.8-py2.7-macosx-10.6-intel.egg/BTrees/Interfaces.py", line 511, in from ZODB.POSException import BTreesConflictError File "/Users/wanbo/Library/Python/2.7/lib/python/site-packages/ZODB-4.0.0b3-py2.7.egg/ZODB/__init__.py", line 28, in from ZODB.DB import DB, connection File "/Users/wanbo/Library/Python/2.7/lib/python/site-packages/ZODB-4.0.0b3-py2.7.egg/ZODB/DB.py", line 23, in from ZODB.broken import find_global File "/Users/wanbo/Library/Python/2.7/lib/python/site-packages/ZODB-4.0.0b3-py2.7.egg/ZODB/broken.py", line 30, in class Broken(object): File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/zope/interface/declarations.py", line 495, in __call__ raise TypeError("Can't use implementer with classes. Use one of " TypeError: Can't use implementer with classes. Use one of the class-declaration functions instead. Anyone has experience with BTrees? Best regards, Wanbo From s.seshadri.raja at gmail.com Tue Jun 25 12:41:51 2013 From: s.seshadri.raja at gmail.com (Seshadri Raja) Date: Tue, 25 Jun 2013 03:41:51 -0700 Subject: [Tutor] Question about python for web In-Reply-To: References: Message-ID: Dear Dat, Sorry for the late reply. The path of the python should be #!/usr/bin/python (or) #!/usr/bin/env python. Forward Slash(/) is missing in your CGI script. ?Enable the ExecCGI for your DocumentRoot Ref: http://httpd.apache.org/docs/current/howto/cgi.html? ? Options +ExecCGI ? Kindly try and let us know the details. Kind Regards :: S. Seshadri Raja :: On Sun, Jun 23, 2013 at 6:12 PM, Dat Huynh wrote: > Dear all, > > I have a very simple question about running a simple web application with > apache on MacOS. > > Step 1: Copy the file mod_wsgi.so from the link > > http://code.google.com/p/modwsgi/downloads/detail?name=mod_wsgi-macosx106-ap22py26-3.3.so > into the folder "/usr/libexec/apache2" > > > Step 2: Add the following line: > > LoadModule wsgi_module libexec/apache2/mod_wsgi.so > into the file "/etc/apache2/httpd.conf" > > > Step 3: Edit a file "test.py" as below and copy the file to the folder > "/Library/WebServer/Documents". > > #!usr/bin/python > print "Content-type: text/html" > print > print "" > print "" > print "" > print "Test Page" > print "" > > When I type the following url "http://localhost/test.py" on my browser, I > see exactly the content of the file, NOT the text "Test Page" only. > > I think I miss something in the procedure. > What should I do to make my browser process the received HTML data? > > Thank you very much. > > Sincerely, > Dat. > > _______________________________________________ > 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 alan.gauld at btinternet.com Thu Jun 27 01:42:36 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 27 Jun 2013 00:42:36 +0100 Subject: [Tutor] using python for parsing In-Reply-To: References: Message-ID: On 26/06/13 18:05, Makarand Datar wrote: > I know practically nothing about python. I know how to install it and > all that kind of stuff. I want to use python for parsing a text file. So far so good. Do you know how to program in any other language? It will help us direct you to a source if we know your level of prior knowledge. > The task is to read in a text file, and write out another text file that > is written in some particular way using the data from the file that was > read in. Again, so far so good. > The question is how do I go about this? What part of python > documentation, or a book I should read etc. I dont want to start reading > a python book from the first page. I just want to do this parsing task > and I will learn about whatever I need to as I encounter it. Unless you are already very familiar with another programming language then that is a very inefficient way to learn. However if you really have the time to bounce about looking up random references so you can understand one chapter you can try the Handling Files topic in my tutorial. It does however assume you've read the preceding topics.... As a matter of interest, if you wanted to play a tune on guitar would you ask to learn only how to play the specific notes in that tune? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Jun 27 01:45:22 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 27 Jun 2013 00:45:22 +0100 Subject: [Tutor] Install BTrees In-Reply-To: <5C245A88-D98B-499B-928D-51B4BD57042B@gmail.com> References: <5C245A88-D98B-499B-928D-51B4BD57042B@gmail.com> Message-ID: On 26/06/13 10:56, Wanbo Li wrote: > Dear all, > > I am trying to install BTrees package on Mac OS X 10.7.5. And my python version is 2.7.3 > > So I used 'easy_install ZODB' and 'easy_install BTrees' to install the packages. This list is for people learning the Python language and its standard library. Since this appears to be Zope related you should probably try a Zope forum/list. However, you may be lucky and somebody here might actually know how to help you... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jacklittlemc at yahoo.com Thu Jun 27 02:32:56 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Wed, 26 Jun 2013 17:32:56 -0700 (PDT) Subject: [Tutor] While problem Message-ID: <1372293176.26535.YahooMailNeo@web124505.mail.ne1.yahoo.com> I have a small problem with the while function.It prints an odd variable that has nothing to do with the function. It prints "Squad One!". Here is my code for the 3 def's that have something to do with the while function. def tcombat(): ? ? c1am=10 ? ? c2am=10 ? ? enam="Qasi" ? ? ehealth=15 ? ? edam=random.choice([5,6,7,8,9]) ? ? thealth=20 ? ? tdam=random.choice([6,7,8,9,10]) ? ? enemyalive=True ? ? while enemyalive==True: ?? ? ? ? ? t2=raw_input(">>") ? ? ? ? if t2.lower=="FIRE CANNON 1": ? ? ? ? ? ? c1am-=c1am-1 ? ? ? ? ? ? ehealth-tdam ? ? ? ? ? ? print "Cannon Fired!" ? ? ? ? ? ? print "Enemy Health=", ehealth ? ? ? ? ? ?? ? ? ? ? elif t2.lower=="FIRE CANNON 2": ? ? ? ? ? ? c2am=c2am-1 ? ? ? ? ? ? ehealth-tdam ? ? ? ? ? ? print "Cannon Fired!" ? ? ? ? ? ? print "Enemy Health=", ehealth ? ? print "Good Job!" ? ? print "You beat the training dummy." ? ? print "Nothing like real combat" ? ? print "But screw you, here you go!" ? ? print "(Into real combat)" ? ? lvl3() def lvl2_2(): ? ? print "Squad Nine" ? ? print "This team looks very....umm..Dumb." ? ? print "There is one guy sitting on a stool" ? ? print "he has a star sticker on his chest." ? ? print "The other guy is vomiting on his" ? ? print "pants." ? ? print "BEGIN TRAINING" ? ? print "TRAINING: When you are roaming around the skies, you type 'Engage [Ship Name]'" ? ? print "TRAINING: While in combat, type 'Fire [Cannon Number (not spelt)]' to fire a cannon at a ship" ? ? print "All entries must be in lower caps!" ? ? print "TRAINING: There may be consequences for firing upon certain ships." ? ? print "--BEGIN TRAINING--" ? ? print "There is a ship near yours, the Qasi. It is flying" ? ? print "the enemy flag." ? ? print "There are 2 cannons on your ship." ? ? c1am=10 ? ? c2am=10 ? ? enam="Qasi" ? ? ehealth=15 ? ? edam=random.choice([5,6,7,8,9]) ? ? thealth=20 ? ? tdam=random.choice([6,7,8,9,10]) ? ? enemyalive=True ? ? if ehealth==0: ? ? ? ? enemyalive=False ? ? t1=raw_input(">>") ? ? if t1.lower=="engage qasi": ? ? ? ? print enam ,"Engaged in Combat" ? ? ? ? tcombat() ? ? ? ?? def lvl2_1(): ? ? print "Squad One" ? ? print "This team looks much more able than Squad Nine." ? ? print "TYRONE:Hi! I'm Tyrone, he's James, she's Ashley, and that guy over there," ? ? print "he's Bob." ? ? print "BEGIN TRAINING" ? ? print "TRAINING: When you are roaming around the skies, you type 'Engage [Ship Name]'" ? ? print "TRAINING: While in combat, type 'Fire [Cannon Number (not spelt)]' to fire a cannon at a ship" ? ? print "TRAINING: There may be consequences for firing upon certain ships." ? ? print "--BEGIN TRAINING--" ? ? print "There is a ship near yours, the Qasi. It is flying" ? ? print "the enemy flag." ? ? print "There are 2 cannons on your ship." ? ? c1am=10 ? ? c2am=10 ? ? enam="Qasi" ? ? ehealth=15 ? ? edam=random.choice([5,6,7,8,9]) ? ? thealth=20 ? ? tdam=random.choice([6,7,8,9,10]) ? ? enemyalive=True ? ? if ehealth==0: ? ? ? ? enemyalive=False ? ? t1=raw_input(">>") ? ? if t1.lower=="ENGAGE QASI": ? ? ? ? print "Engaged in Combat" ? ? ? ? tcombat() Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Jun 27 02:46:22 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 27 Jun 2013 10:46:22 +1000 Subject: [Tutor] using python for parsing In-Reply-To: References: Message-ID: <51CB8B5E.7020107@pearwood.info> On 27/06/13 03:05, Makarand Datar wrote: > Hi, > > I know practically nothing about python. I know how to install it and all > that kind of stuff. I want to use python for parsing a text file. The task > is to read in a text file, and write out another text file that is written > in some particular way using the data from the file that was read in. The > question is how do I go about this? What part of python documentation, or a > book I should read etc. I dont want to start reading a python book from the > first page. I just want to do this parsing task and I will learn about > whatever I need to as I encounter it. That depends on what you mean by "written in some particular way". It also depends on what version of Python, and what operating system. (I assume Windows, since Python is nearly always pre-installed on Linux.) The simplest, most basic way is to do this is something like this: filename = "C:/path/to/some/file.txt" f = open(filename, 'r') for line in f: print(line) f.close() In more recent versions, this is perhaps better written as: filename = "C:/path/to/some/file.txt" with open(filename, 'r') as f: for line in f: print(line) Don't forget that indentation is significant. Instead of print(line), a more realistic example would parse the line in some way, and that depends on the "particular way" you mention above. For example, given some line, I might split it into words, then print the first word, the second word, and the last letter of the third word: words = line.split() print(words[0], words[1], words[2][-1]) -- Steven From breamoreboy at yahoo.co.uk Thu Jun 27 02:59:01 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 27 Jun 2013 01:59:01 +0100 Subject: [Tutor] While problem In-Reply-To: <1372293176.26535.YahooMailNeo@web124505.mail.ne1.yahoo.com> References: <1372293176.26535.YahooMailNeo@web124505.mail.ne1.yahoo.com> Message-ID: On 27/06/2013 01:32, Jack Little wrote: > I have a small problem with the while function.It prints an odd variable > that has nothing to do with the function. It prints "Squad One!". Here > is my code for the 3 def's that have something to do with the while > function. > if t2.lower=="FIRE CANNON 1": There is one glaring error and one rather more subtle error in the line above which is repeated throughout your code. Your assignment, should you decide to take it on, is to find and fix both errors :) -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From davea at davea.name Thu Jun 27 03:04:32 2013 From: davea at davea.name (Dave Angel) Date: Wed, 26 Jun 2013 21:04:32 -0400 Subject: [Tutor] While problem In-Reply-To: <1372293176.26535.YahooMailNeo@web124505.mail.ne1.yahoo.com> References: <1372293176.26535.YahooMailNeo@web124505.mail.ne1.yahoo.com> Message-ID: <51CB8FA0.8090905@davea.name> On 06/26/2013 08:32 PM, Jack Little wrote: > I have a small problem with the while function.It prints an odd variable What variable is that? > that has nothing to do with the function. It prints "Squad One!". Here is my code for the 3 def's that have something to do with the while function. > > It's not at all clear what you want from us. There aren't any while functions (since that would be a syntax error), though I do see a while statement in the tcombat() function. Is that the one you're referring to? I also see calls to functions you didn't provide, and since the logic makes no sense to me, it's not obvious whether they matter or not. Nothing here calls lvl2_1(), so should we assume it's dead code? For that matter, neither of the references to tcombat() will ever actually call it, so it's dead too? Are you just looking for someone to correct your obvious mistakes? Like the if statement and the elif statement that will never fire, because you forgot parentheses on the t2.lower method call ? (And once you fix that, they'll still never fire, since you're then comparing uppercase to lowercase, and obviously they're different). Because of that, the while statement will never terminate, just repeatedly asking for raw_input (with a prompt of ">>") and getting stuck till the user creates an exception, like Ctrl-C. > > def tcombat(): > c1am=10 > c2am=10 > enam="Qasi" > ehealth=15 > edam=random.choice([5,6,7,8,9]) > thealth=20 > tdam=random.choice([6,7,8,9,10]) > enemyalive=True > while enemyalive==True: > t2=raw_input(">>") > if t2.lower=="FIRE CANNON 1": > c1am-=c1am-1 > ehealth-tdam > print "Cannon Fired!" > print "Enemy Health=", ehealth > > elif t2.lower=="FIRE CANNON 2": > c2am=c2am-1 > ehealth-tdam > print "Cannon Fired!" > print "Enemy Health=", ehealth > print "Good Job!" > print "You beat the training dummy." > print "Nothing like real combat" > print "But screw you, here you go!" > print "(Into real combat)" > lvl3() Does lvl3() look anything like lvl2_2() below? If so, you're looking for trouble, recursively calling between tcombat() and the various other functions. Eventually, the stack fills up. A function call is not a goto statement. > > def lvl2_2(): > print "Squad Nine" > print "This team looks very....umm..Dumb." > print "There is one guy sitting on a stool" > print "he has a star sticker on his chest." > print "The other guy is vomiting on his" > print "pants." > print "BEGIN TRAINING" > print "TRAINING: When you are roaming around the skies, you type 'Engage [Ship Name]'" > print "TRAINING: While in combat, type 'Fire [Cannon Number (not spelt)]' to fire a cannon at a ship" > print "All entries must be in lower caps!" > print "TRAINING: There may be consequences for firing upon certain ships." > print "--BEGIN TRAINING--" > print "There is a ship near yours, the Qasi. It is flying" > print "the enemy flag." > print "There are 2 cannons on your ship." > c1am=10 > c2am=10 > enam="Qasi" > ehealth=15 > edam=random.choice([5,6,7,8,9]) > thealth=20 > tdam=random.choice([6,7,8,9,10]) You never use the values of edam, thealth, and tdam. So why calculate them? > enemyalive=True > if ehealth==0: > enemyalive=False This statement and the similar one above did nothing useful. You never check the value of enemyalive in this function. > t1=raw_input(">>") > if t1.lower=="engage qasi": > print enam ,"Engaged in Combat" > tcombat() > > > > def lvl2_1(): > print "Squad One" > print "This team looks much more able than Squad Nine." > print "TYRONE:Hi! I'm Tyrone, he's James, she's Ashley, and that guy over there," > print "he's Bob." > print "BEGIN TRAINING" > print "TRAINING: When you are roaming around the skies, you type 'Engage [Ship Name]'" > print "TRAINING: While in combat, type 'Fire [Cannon Number (not spelt)]' to fire a cannon at a ship" > print "TRAINING: There may be consequences for firing upon certain ships." > print "--BEGIN TRAINING--" > print "There is a ship near yours, the Qasi. It is flying" > print "the enemy flag." > print "There are 2 cannons on your ship." > c1am=10 > c2am=10 > enam="Qasi" You never use enam. It looks useful, so how did you expect to be using it? > ehealth=15 > edam=random.choice([5,6,7,8,9]) > thealth=20 > tdam=random.choice([6,7,8,9,10]) > enemyalive=True > if ehealth==0: > enemyalive=False This local variable is never referenced. So why set it? Of course that doesn't really matter, since ehealth is not going to be zero; it's initialized right above to 15. > t1=raw_input(">>") > if t1.lower=="ENGAGE QASI": This will never be equal, so the following never happens. > print "Engaged in Combat" > tcombat() > > > -- DaveA From steve at pearwood.info Thu Jun 27 03:16:52 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 27 Jun 2013 11:16:52 +1000 Subject: [Tutor] While problem In-Reply-To: <1372293176.26535.YahooMailNeo@web124505.mail.ne1.yahoo.com> References: <1372293176.26535.YahooMailNeo@web124505.mail.ne1.yahoo.com> Message-ID: <51CB9284.8060106@pearwood.info> On 27/06/13 10:32, Jack Little wrote: > I have a small problem with the while function.It prints an odd variable that has nothing to do with the function. It prints "Squad One!". Here is my code for the 3 def's that have something to do with the while function. But you don't actually show us the while loop that prints "Squad One!". That's rather less than useful. How do you expect us to fix the broken code without seeing it? "Hello Mr Mechanic, I have a car that is making a strange noise when I turn left. Rather than bring that car in for you to look at, I thought I'd bring in the three cars that are parked next to it, just in case the problem is with them..." :-) Some unrelated comments below: > def tcombat(): > c1am=10 > c2am=10 > enam="Qasi" > ehealth=15 > edam=random.choice([5,6,7,8,9]) "edam"? Like the cheese? > thealth=20 > tdam=random.choice([6,7,8,9,10]) > enemyalive=True > while enemyalive==True: You don't need to say "while enemyalive == True", since enemyalive is already a true or false value. Just say "while enemyalive:". > t2=raw_input(">>") > if t2.lower=="FIRE CANNON 1": This cannot every succeed, since you are comparing the *method* (like a function) t2.lower with the *string* "FIRE CANNON 1". You need to actually *call* the method, to get a result: if t2.lower() == "FIRE CANNON 1": which of course also can never succeed, since you're comparing a lowercase string with an UPPERCASE string. You need one of these instead: if t2.lower() == "fire cannon 1": if t2.upper() == "FIRE CANNON 1": > c1am-=c1am-1 If you think about this mathematically, you will see that this cannot fail to set c1am to 1. If that's what you intended, just write "c1am = 1". Or if you meant to subtract 1 from c1am, then you can write either of these: c1am = c1am - 1 c1am -= 1 My suggestion is that you are less likely to make these sorts of errors if you put spaces around equal signs and other operators. Spaces make things easier to read, or another way to put it, notusingspacesmakesthingsmuchhardertoread. (By the way, I hope these variable names mean something to you, because most of them mean absolutely nothing to me. "c1am"? WTH does that stand for?) > ehealth-tdam This line is useless, since it just calculates the value ehealth - tdam, then throws the result away unused. Perhaps you meant this? ehealth -= tdam > print "Cannon Fired!" > print "Enemy Health=", ehealth > > elif t2.lower=="FIRE CANNON 2": The same flaw applies here as above. > c2am=c2am-1 > ehealth-tdam Likewise. > print "Cannon Fired!" > print "Enemy Health=", ehealth > print "Good Job!" > print "You beat the training dummy." > print "Nothing like real combat" > print "But screw you, here you go!" > print "(Into real combat)" > lvl3() > > def lvl2_2(): > print "Squad Nine" > print "This team looks very....umm..Dumb." > print "There is one guy sitting on a stool" > print "he has a star sticker on his chest." > print "The other guy is vomiting on his" > print "pants." > print "BEGIN TRAINING" > print "TRAINING: When you are roaming around the skies, you type 'Engage [Ship Name]'" > print "TRAINING: While in combat, type 'Fire [Cannon Number (not spelt)]' to fire a cannon at a ship" > print "All entries must be in lower caps!" "Lower caps"? Do you mean lower case? ALL CAPS? > print "TRAINING: There may be consequences for firing upon certain ships." Oh good. Consequences. Are they good consequences or bad consequences? By the way, your code contains an awful lot of duplicated code. You should pull out the duplicated code and put it into functions, then pass an appropriate variable to the function. A simplified example follows. Instead of this duplicated code: def squad_one(): print "This is squad one." print "You're training" print "Do this" print "Do that" print "Do something else" def squad_two(): print "This is squad two." print "You're training" print "Do this" print "Do that" print "Do something else" if squad == "squad one": squad_one() else: squad_two() you can instead do this: def squad(name): print "This is Squad %s." % name print "You're training" print "Do this" print "Do that" print "Do something else" if squad == "squad one": squad("one") else: squad("two") -- Steven From marc.tompkins at gmail.com Thu Jun 27 04:16:45 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 26 Jun 2013 19:16:45 -0700 Subject: [Tutor] Typing 'h', 'e', 'l', 'p', 'Enter' in a window In-Reply-To: <1372279530013-5022574.post@n6.nabble.com> References: <1372279530013-5022574.post@n6.nabble.com> Message-ID: On Wed, Jun 26, 2013 at 1:45 PM, kdarroud wrote: > In our Windows machine, we have several windows open. > Using Python, how can I type 'h', 'e', 'l', 'p', 'Enter' in a specific > window that is open? > In general, Python out-of-the-box doesn't know about OS-specific things like interacting with other windows; you need to interact with the operating system to do that. In the case of Windows, there's a module called pywin - http://sourceforge.net/projects/pywin32/ - that provides a Python-accessible wrapper around the Windows API. Basically, you need to find the Windows API call(s) you need in order to achieve your goal (definitely not a Python question; some folks on this list might be able to help you, but there are better resources for Windows programmers), and then call them via pywin. The pywin documentation is very, very minimal - _all_ that pywin does is provide a Python binding for Windows API calls. If you have questions about invoking pywin after you've downloaded and installed it, or general Python questions, this list is the place. For everything else... not so much. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nsivaram.net at gmail.com Thu Jun 27 05:19:53 2013 From: nsivaram.net at gmail.com (Sivaram Neelakantan) Date: Thu, 27 Jun 2013 08:49:53 +0530 Subject: [Tutor] mapping header row to data rows in file References: <87d2r8dgtr.fsf@gmail.com> Message-ID: <874nckck9y.fsf@gmail.com> On Wed, Jun 26 2013,Peter Otten wrote: [snipped 36 lines] > from collections import namedtuple > > def reader(instream): > rows = (line.split() for line in instream) > names = next(rows) > Row = namedtuple("Row", names) > return (Row(*values) for values in rows) > > with open(FILENAME, "r") as f: > for row in reader(f): > print row.name > I get these errors with the code above Row = namedtuple("Row", names) File "/usr/lib/python2.7/collections.py", line 278, in namedtuple raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name) ValueError: Type names and field names can only contain alphanumeric characters and underscores: 'Symbol,Series,Date,Prev_Close' --8<---------------cut here---------------start------------->8--- Symbol,Series,Date,Prev_Close STER,EQ,22-Nov-2012, 9 STER,EQ,29-Nov-2012, 10 STER,EQ,06-Dec-2012, 11 STER,EQ,06-Jun-2013, 9 STER,EQ,07-Jun-2013, 9 def reader(instream): rows = (line.split() for line in instream) names = next(rows) Row = namedtuple("Row", names) return (Row(*values) for values in rows) with open("AA.csv", "r") as f: for row in reader(f): print row.name --8<---------------cut here---------------end--------------->8--- sivaram -- From cybervigilante at gmail.com Thu Jun 27 08:40:08 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 26 Jun 2013 23:40:08 -0700 Subject: [Tutor] unwanted 'zero' ending Message-ID: I've been staring at this program for hours, which otherwise seems to work fine - converting numbers to their words - but the one glaring error is that final hundreds have a 'zero' appended, such as hundred zero, two hundred zero, (See the very end of the test output, which ends in four hundred zero, instead of four hundred, as it should.) I'm sure this is right in front of me but I must be getting fuzzy ;') By the way, how large is Python's standard GUI input allowed to be, and can you expand it without resorting to tkinter? #Using C:\Python33\python.exe on Win 7 in c:\python33\jimprogs def numstonames(inp): ''' Return names for positive integer input, up to 10**36-1. You can separate input with spaces (not commas) to avoid confusion. ''' multipliers = ('thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nontillion', 'dectillion','') singles = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'} lownums = {'00': 'zero', '01': 'one', '02': 'two', '03': 'three', '04': 'four', '05': 'five', '06':'six', '07': 'seven', '08': 'eight', '09': 'nine','10': 'ten', '11': 'eleven', '12': 'twelve', '13': 'thirteen', '14': 'fourteen', '15': 'fifteen', '16': 'sixteen', '17': 'seventeen', '18': 'eighteen', '19': 'nineteen'} twenty_to_90 = {'2': 'twenty', '3': 'thirty', '4': 'forty', '5': 'fifty', '6': 'sixty', '7': 'seventy', '8': 'eighty', '9': 'ninety'} def twenty_to_99(inp): ''' Return name for numbers from 20 to 99''' last_two = twenty_to_90.get(inp[0]) if inp[1] != '0': last_two += '-' + singles.get(inp[1]) return last_two inp = str(inp) inlen = len(inp) triplet_name = '' first_digit = '' last_two = '' numword = '' # left-pad input with zeros so it's a multiple of 3, and we get all triplets. padnum = (3 - inlen % 3) if padnum != 3: inp = inp.zfill(padnum + inlen) # Break input into triplets triplets = [inp[i:i+3] for i in range(0,len(inp),3)] get_multiplier = len(triplets) - 2 for triplet in triplets: last_two = lownums.get(triplet[1:]) # Get last two numwords in triplet, if 0 to 19 if last_two == None: last_two = twenty_to_99(triplet[1:]) # or get larger numword # Get first digit of triplet, if non-zero, which will be in the hundreds if triplet[0] != '0': first_digit = singles.get(triplet[0]) + ' hundred ' triplet_name = first_digit + last_two numword += triplet_name + ' '# concatenate the triplets # Append the proper multiplier: thousands, millions, billions, etc. numword += multipliers[get_multiplier] + ' ' get_multiplier -= 1 return numword number_candidate = input("input positive integer to convert, space separated or not") numlist = number_candidate.split() actual_number = ''.join(numlist) print(numstonames(actual_number)) # Test input: 123 456 700 543 928 103 953 262 950 681 161 400 '''Output: one hundred twenty-three dectillion four hundred fifty-six nontillion seven hundred zero octillion five hundred forty-three septillion nine hundred twenty-eight sextillion one hundred three quintillion nine hundred fifty-three quadrillion two hundred sixty-two trillion nine hundred fifty billion six hundred eighty-one million one hundred sixty-one thousand four hundred zero ''' -- Jim Never run on gravel with a lightbulb in your mouth (personal experience - don't ask.) From __peter__ at web.de Thu Jun 27 08:50:01 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Jun 2013 08:50:01 +0200 Subject: [Tutor] mapping header row to data rows in file References: <87d2r8dgtr.fsf@gmail.com> <874nckck9y.fsf@gmail.com> Message-ID: Sivaram Neelakantan wrote: > On Wed, Jun 26 2013,Peter Otten wrote: > > > [snipped 36 lines] > >> from collections import namedtuple >> >> def reader(instream): >> rows = (line.split() for line in instream) >> names = next(rows) >> Row = namedtuple("Row", names) >> return (Row(*values) for values in rows) >> >> with open(FILENAME, "r") as f: >> for row in reader(f): >> print row.name >> > I get these errors with the code above > > Row = namedtuple("Row", names) > File "/usr/lib/python2.7/collections.py", line 278, in namedtuple > raise ValueError('Type names and field names can only contain alphanumeric > characters and underscores: %r' % name) ValueError: Type names and field > names can only contain alphanumeric characters and underscores: > 'Symbol,Series,Date,Prev_Close' > > > > --8<---------------cut here---------------start------------->8--- > > Symbol,Series,Date,Prev_Close > STER,EQ,22-Nov-2012, 9 > STER,EQ,29-Nov-2012, 10 > STER,EQ,06-Dec-2012, 11 > STER,EQ,06-Jun-2013, 9 > STER,EQ,07-Jun-2013, 9 The format of the above table differes from the one you posted originally. line.split() splits the line on whitespace: >>> "alpha beta\tgamma\n".split() ['alpha', 'beta', 'gamma'] To split the line on commas you can use line.split(","). This preserves the surrounding whitespace, though: >>> "alpha, beta,gamma\n".split(",") ['alpha', ' beta', 'gamma\n'] I'd prefer a csv.reader(), and if you have control over the table format you should remove the extra whitespace in the source data. def reader(instream): rows = csv.reader(instream) # will remove newline at the # end of the line, # but not other whitespace # Optional: remove surrounding whitespace from the fields rows = ([field.strip() for field in row] for row in rows) ... # as before > def reader(instream): > rows = (line.split() for line in instream) > names = next(rows) > Row = namedtuple("Row", names) > return (Row(*values) for values in rows) > > with open("AA.csv", "r") as f: > for row in reader(f): > print row.name From __peter__ at web.de Thu Jun 27 09:19:32 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Jun 2013 09:19:32 +0200 Subject: [Tutor] unwanted 'zero' ending References: Message-ID: Jim Mooney wrote: > I've been staring at this program for hours, which otherwise seems to > work fine - converting numbers to their words - but the one glaring > error is that final hundreds have a 'zero' appended, such as hundred > zero, two hundred zero, (See the very end of the test output, which > ends in four hundred zero, instead of four hundred, as it should.) I'm > sure this is right in front of me but I must be getting fuzzy ;') I'd try skipping (i. e. not producing any output for) "000" triplets. That should (untested) reduce the number of incorrect results to a single one. Can you guess which one I have in mind? If my assumption is correct you can easily deal with that value by special- casing. > By the way, how large is Python's standard GUI input allowed to be, > and can you expand it without resorting to tkinter? > > #Using C:\Python33\python.exe on Win 7 in c:\python33\jimprogs > def numstonames(inp): > ''' Return names for positive integer input, up to 10**36-1. You > can separate input > with spaces (not commas) to avoid confusion. > ''' > multipliers = ('thousand', 'million', 'billion', 'trillion', > 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', > 'nontillion', 'dectillion','') > > singles = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': > 'five', '6': 'six', > '7': 'seven', '8': 'eight', '9': 'nine'} > > lownums = {'00': 'zero', '01': 'one', '02': 'two', '03': 'three', > '04': 'four', > '05': 'five', '06':'six', '07': 'seven', '08': 'eight', '09': > 'nine','10': 'ten', > '11': 'eleven', '12': 'twelve', '13': 'thirteen', '14': > 'fourteen', '15': 'fifteen', > '16': 'sixteen', '17': 'seventeen', '18': 'eighteen', '19': > 'nineteen'} > > twenty_to_90 = {'2': 'twenty', '3': 'thirty', '4': 'forty', '5': > 'fifty', '6': 'sixty', '7': 'seventy', '8': 'eighty', '9': 'ninety'} > > def twenty_to_99(inp): > ''' Return name for numbers from 20 to 99''' > last_two = twenty_to_90.get(inp[0]) > if inp[1] != '0': last_two += '-' + singles.get(inp[1]) > return last_two > > inp = str(inp) > inlen = len(inp) > triplet_name = '' > first_digit = '' > last_two = '' > numword = '' > > # left-pad input with zeros so it's a multiple of 3, and we get > all triplets. > padnum = (3 - inlen % 3) > if padnum != 3: > inp = inp.zfill(padnum + inlen) > > # Break input into triplets > triplets = [inp[i:i+3] for i in range(0,len(inp),3)] > get_multiplier = len(triplets) - 2 > for triplet in triplets: > last_two = lownums.get(triplet[1:]) # Get last two numwords in > triplet, if 0 to 19 > if last_two == None: last_two = twenty_to_99(triplet[1:]) # or > get larger numword > > # Get first digit of triplet, if non-zero, which will be in the > # hundreds > if triplet[0] != '0': first_digit = singles.get(triplet[0]) + > ' hundred ' > triplet_name = first_digit + last_two > numword += triplet_name + ' '# concatenate the triplets > > # Append the proper multiplier: thousands, millions, billions, > # etc. > numword += multipliers[get_multiplier] + ' ' > get_multiplier -= 1 > > return numword > > number_candidate = input("input positive integer to convert, space > separated or not") > numlist = number_candidate.split() > actual_number = ''.join(numlist) > print(numstonames(actual_number)) > > # Test input: 123 456 700 543 928 103 953 262 950 681 161 400 > '''Output: > one hundred twenty-three dectillion four hundred fifty-six nontillion > seven hundred zero octillion five hundred forty-three septillion > nine hundred twenty-eight sextillion one hundred three quintillion > nine hundred fifty-three quadrillion two hundred sixty-two trillion > nine hundred fifty billion six hundred eighty-one million > one hundred sixty-one thousand four hundred zero ''' > From alan.gauld at btinternet.com Thu Jun 27 09:43:07 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 27 Jun 2013 08:43:07 +0100 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: References: Message-ID: On 27/06/13 07:40, Jim Mooney wrote: > I've been staring at this program for hours, I'm not surprised. It's very cluttered. Take the constant definitions out of the function. Take the internal function out of the function. Create a few more helper functions and then get rid of the "helpful comments" that only describe what a function should be doing (get triplets etc) Then there is a confusion of how you print stuff. The bigger multiples (thousand up) are defined in data but the hundreds are defined inline. And I never did find where zero got printed because it was all too confusing. > By the way, how large is Python's standard GUI input allowed to be, > and can you expand it without resorting to tkinter? TKinter *is* Python's standard GUI toolkit. What do you mean? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cybervigilante at gmail.com Thu Jun 27 09:52:26 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Thu, 27 Jun 2013 00:52:26 -0700 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: References: Message-ID: On 27 June 2013 00:43, Alan Gauld > TKinter *is* Python's standard GUI toolkit. > What do you mean? I just meant, how many characters are allowed on the input screen you normally get when you put input() in a program, and can you change that? Jim From cybervigilante at gmail.com Thu Jun 27 10:09:30 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Thu, 27 Jun 2013 01:09:30 -0700 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: References: Message-ID: On 27 June 2013 00:43, Alan Gauld wrote: > Take the constant definitions out of the function.... Since the program has an error And needs simplification (no doubt interdependent), but it would be hard to do both at once, this brings up a good general question: Is it best, in such cases, to correct the error, then simplify, or simplify, then correct the error? -- Jim It is better to ask forgiveness than permission, but it is best if they don't find out at all ;') From alan.gauld at btinternet.com Thu Jun 27 10:10:53 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 27 Jun 2013 09:10:53 +0100 (BST) Subject: [Tutor] unwanted 'zero' ending In-Reply-To: References: Message-ID: <1372320653.23939.YahooMailNeo@web186004.mail.ir2.yahoo.com> > > TKinter *is* Python's standard GUI toolkit. > > What do you mean? > > I just meant, how many characters are allowed on the input screen you > normally get when you put? input() in a program,? There is no "input screen" in normal use, it appears on stdout in? the console.?How are you running your Python programs? Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From zachary.ware+pytut at gmail.com Thu Jun 27 10:15:25 2013 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Thu, 27 Jun 2013 03:15:25 -0500 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: References: Message-ID: <8296ac19-cff6-4a0e-aabe-f8cc1bf6979e@email.android.com> Jim Mooney wrote: >On 27 June 2013 00:43, Alan Gauld wrote: >> Take the constant definitions out of the function.... > >Since the program has an error And needs simplification (no doubt >interdependent), but it would be hard to do both at once, this brings >up a good general question: Is it best, in such cases, to correct the >error, then simplify, or simplify, then correct the error? Simplify, and the error may disappear on its own. From alan.gauld at btinternet.com Thu Jun 27 10:14:05 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 27 Jun 2013 09:14:05 +0100 (BST) Subject: [Tutor] unwanted 'zero' ending In-Reply-To: References: Message-ID: <1372320845.26258.YahooMailNeo@web186005.mail.ir2.yahoo.com> > Since the program has an error And needs simplification (no doubt > interdependent), but it would be hard to do both at once, this brings > up a good general question: Is it best, in such cases, to correct the > error, then simplify, or simplify, then correct the error? In general I'd simplify first since that will help me see the wood? from the trees and help me find the error. Indeed simplifying the? code may remove the error... But once simplified - including writing helper functions - you can? then test each subfunction independently without having to test the? whole program in one go. That alone makes it easier to find the error. Alan g. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Thu Jun 27 10:30:05 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Thu, 27 Jun 2013 01:30:05 -0700 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: <1372320653.23939.YahooMailNeo@web186004.mail.ir2.yahoo.com> References: <1372320653.23939.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: On 27 June 2013 01:10, ALAN GAULD wrote: > > There is no "input screen" in normal use, it appears on stdout in > the console. How are you running your Python programs? > > Alan G. In windows, from the PyScripter IDE. Ah, no such thing in the DOS box. I was looking at the small size of the GUI box in windows. Looks like there is no end to what I can put in DOS. Most users want a GUI these days, but you're right. If it doesn't appear in DOS I have to build it. I just got used to PyScripter calling the GUI for input-- Jim John Dillinger, where are you now that we need you? From __peter__ at web.de Thu Jun 27 10:30:51 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Jun 2013 10:30:51 +0200 Subject: [Tutor] unwanted 'zero' ending References: Message-ID: Jim Mooney wrote: > On 27 June 2013 00:43, Alan Gauld wrote: >> Take the constant definitions out of the function.... > > Since the program has an error And needs simplification (no doubt > interdependent), but it would be hard to do both at once, this brings > up a good general question: Is it best, in such cases, to correct the > error, then simplify, or simplify, then correct the error? That depends. Ideally you'd have unittests to ensure that you aren't introducing new errors with the simplification process. So if you don't have them already now is the time to formalize your ad-hoc tests. Then, as you already tried and didn't find the error you should simplify your code and split it into multiple functions. For example def triplet_to_text(triplet): ... has only 100 possible args and 100 possible results. It's one of the rare birds for that you can write exhaustive tests. Once you have a correct implementation -- whether simple and clean, convoluted, or just a big dict doesn't matter -- you can use it as a building block for numstonames() and never look at it again. Now you can attack the next problem, splitting a number into triplets. You can't do exhaustive tests for that, but try to add tests for a wide range of sizes and to cover all corner cases. With these building blocks the final implementation of numstonames() -- I suggest number_to_name(n) as a sane name -- should become fairly simple, and errors should become easier to debug and fix. Because you know you can rely on the helper functions the amount of code you need to check has become smaller -- and ideally simpler, too. From eryksun at gmail.com Thu Jun 27 11:54:15 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 27 Jun 2013 05:54:15 -0400 Subject: [Tutor] mapping header row to data rows in file In-Reply-To: References: <87d2r8dgtr.fsf@gmail.com> <874nckck9y.fsf@gmail.com> Message-ID: On Thu, Jun 27, 2013 at 2:50 AM, Peter Otten <__peter__ at web.de> wrote: > > I'd prefer a csv.reader(), and if you have control over the table format you > should remove the extra whitespace in the source data. Say you AA.csv opened as f: >>> import csv >>> reader = csv.DictReader(f, skipinitialspace=1) >>> next(reader) {'Date': '22-Nov-2012', 'Series': 'EQ', 'Symbol': 'STER', 'Prev_Close': '9'} >>> next(reader) {'Date': '29-Nov-2012', 'Series': 'EQ', 'Symbol': 'STER', 'Prev_Close': '10'} and so on. From __peter__ at web.de Thu Jun 27 12:26:56 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Jun 2013 12:26:56 +0200 Subject: [Tutor] mapping header row to data rows in file References: <87d2r8dgtr.fsf@gmail.com> <874nckck9y.fsf@gmail.com> Message-ID: eryksun wrote: > On Thu, Jun 27, 2013 at 2:50 AM, Peter Otten <__peter__ at web.de> wrote: >> >> I'd prefer a csv.reader(), and if you have control over the table format >> you should remove the extra whitespace in the source data. > > Say you AA.csv opened as f: > > >>> import csv > >>> reader = csv.DictReader(f, skipinitialspace=1) > > >>> next(reader) > {'Date': '22-Nov-2012', 'Series': 'EQ', 'Symbol': 'STER', > {'Prev_Close': '9'} > >>> next(reader) > {'Date': '29-Nov-2012', 'Series': 'EQ', 'Symbol': 'STER', > 'Prev_Close': '10'} > > and so on. >From your previous posts I got the impression that I need to read the source some more ;) Now I'll have to extend that on the docs. And it is not even a new feature... Thanks for the update. From chigga101 at gmail.com Thu Jun 27 14:10:23 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 27 Jun 2013 13:10:23 +0100 Subject: [Tutor] Windows Linux Popen Message-ID: i have more than 1 issue all involving things in the title. 1st i use windows vista and was following along the pytest tutorial. the 1st issue is with windows and SubProcess.Popen(). Everytime i run the test which includes this line: p = subprocess.Popen( ['python3', 'echo_server.py']) i get this error pytest error: E WindowsError: [Error 2] The system cannot find the file specified ..\..\..\lib\subprocess.py:856: WindowsError I will include the full program at the end i just want to show my issues 1st. I asked for help at irc #python and they told me to try these 2 lines: subprocess.Popen(['python3', 'echo_server.py']) and subprocess.check_output(['python3', 'echo_server.py']) i get the same subprocess windows error for both lines. Someone told me the code was fine, and that windows supports Popen and that it might be another issue on my system. Which leads to my 2nd problem. I downloaded ubuntu on VM just to test this out. as i have never used linux i wasnt sure where and how to install pytest. I did pip install .. it worked. "IT INSTALLED" and i ran the code and pytest returned with no errors but it ignored every test on the file so i tried again. it then said pytest was not installed "HUH?" and that i should use: sudo apt-get install maybe im typing it wrong but i haven't managed to be able to install it, even though strangely it installed the 1st time as i explained? i tried those 2 lines that were failing on windows just to see if subprocess worked on linux. subprocess.Popen(['python3', 'echo_server.py']) and subprocess.check_output(['python3', 'echo_server.py']) and they both gave me the output of "python3". great it works on linux but still i cant install pytest on linux. And as windows is my main OS, the windows error is still my biggest concern. The actual code to my program is split between 2 files which i will indicate in comments when i paste it. I was also told the issue isnt with the code, but feel free to inspect it just incase, especially if you have windows. Here it is: http://bpaste.net/show/LaZBOwDlzBRkoWg5mM5Q/ From __peter__ at web.de Thu Jun 27 14:37:10 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Jun 2013 14:37:10 +0200 Subject: [Tutor] Windows Linux Popen References: Message-ID: Matthew Ngaha wrote: > i have more than 1 issue all involving things in the title. 1st i use > windows vista and was following along the pytest tutorial. the 1st > issue is with windows and SubProcess.Popen(). Everytime i run the test > which includes this line: > > p = subprocess.Popen( > ['python3', 'echo_server.py']) > > i get this error pytest error: > E WindowsError: [Error 2] The system cannot find the file > specified > > ..\..\..\lib\subprocess.py:856: WindowsError Your working directory may differ from the directory containing echo_server.py. Try specifying the full path, e. g. SCRIPT = 'c:\\path\to\\echo_server.py' # replace with your actual path p = subprocess.Popen( ['python3', SCRIPT]) From eryksun at gmail.com Thu Jun 27 14:41:58 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 27 Jun 2013 08:41:58 -0400 Subject: [Tutor] Windows Linux Popen In-Reply-To: References: Message-ID: On Thu, Jun 27, 2013 at 8:10 AM, Matthew Ngaha wrote: > i have more than 1 issue all involving things in the title. 1st i use > windows vista and was following along the pytest tutorial. the 1st > issue is with windows and SubProcess.Popen(). Everytime i run the test > which includes this line: > > p = subprocess.Popen( > ['python3', 'echo_server.py']) > > WindowsError: [Error 2] The system cannot find the file specified The error is telling you that Windows can't find "python3". The exe is named python.exe on Windows, not python3.exe, and it will have to be on your system PATH to be invoked like that. If you want to run the script with the current interpreter, you can use sys.executable. For example: >>> subprocess.Popen( ... [sys.executable, '-c', r'print("spam")']).wait() spam 0 From steve at pearwood.info Thu Jun 27 14:38:38 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 27 Jun 2013 22:38:38 +1000 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: References: Message-ID: <51CC324E.5000903@pearwood.info> On 27/06/13 18:30, Peter Otten wrote: > Jim Mooney wrote: > >> On 27 June 2013 00:43, Alan Gauld wrote: >>> Take the constant definitions out of the function.... >> >> Since the program has an error And needs simplification (no doubt >> interdependent), but it would be hard to do both at once, this brings >> up a good general question: Is it best, in such cases, to correct the >> error, then simplify, or simplify, then correct the error? > > That depends. Ideally you'd have unittests to ensure that you aren't > introducing new errors with the simplification process. > > So if you don't have them already now is the time to formalize your ad-hoc > tests. Unit tests are great, but the learning curve is rather steep. I recommend that you start with doctests. When you write a function, add a docstring ("documentation string") that explains what the function does. Include examples showing how it is expected to work: def num_to_name(number): """Return the English name of int number. >>> num_to_name(42) 'forty-two' >>> num_to_name(3579) 'three thousand five hundred and seventy-nine' """ [code goes here as normal] The examples must be formatted as if they were copied and pasted from the standard Python interpreter, complete with leading >>> prompt. The doctest module will detect those examples, run them, and report on any errors. From the shell: python -m doctest "C:/path/to/module/to/test.py" If there are no errors, doctest won't print anything, otherwise it will print any errors. An error is: * anything that raises an exception; * anything that returns something other than the example shown. To see all the tests as they run: python -m doctest "C:/path/to/module/to/test.py" --verbose Once you get used to the quirks of doctest, and there are a few, I hope you will love it as much as I do. They make both great documentation and good tests! -- Steven From jacklittlemc at yahoo.com Thu Jun 27 15:27:06 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Thu, 27 Jun 2013 06:27:06 -0700 (PDT) Subject: [Tutor] True to False and Other things! Message-ID: <1372339626.95018.YahooMailNeo@web124506.mail.ne1.yahoo.com> In my game, I am trying to make it so when the enemy's health equals 0, the player advances. I used a while statement and a true or false variable. When the enemy health is less than or equal to 0, the program exits the while statement. It does not work. It keeps going. How could I fix this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Jun 27 15:45:51 2013 From: davea at davea.name (Dave Angel) Date: Thu, 27 Jun 2013 09:45:51 -0400 Subject: [Tutor] True to False and Other things! In-Reply-To: <1372339626.95018.YahooMailNeo@web124506.mail.ne1.yahoo.com> References: <1372339626.95018.YahooMailNeo@web124506.mail.ne1.yahoo.com> Message-ID: <51CC420F.2000807@davea.name> On 06/27/2013 09:27 AM, Jack Little wrote: > In my game, I am trying to make it so when the enemy's health equals 0, the player advances. I used a while statement and a true or false variable. When the enemy health is less than or equal to 0, the program exits the while statement. It does not work. It keeps going. How could I fix this? > > You could try changing the value of that true/false variable inside the loop. Have you made the dozens of changes suggested by various people here? And as another hint, do you understand what local variables are, and that local variables in one function do not normally have any effect on local variables in another? I suggest you temporarily forget the larger program, and write a small one that demonstrates your symptom. Write a while-loop inside a function that tests some variable. Write a body of that loop which changes the variable, presumably when some condition changes. And see if it ever terminates. If it shows the same symptom, and you cannot see the reason, then post it here. The entire program. And explain clearly what you expected and in what way it did something different. In case you can't tell, the explanation you gave above was not clear. You said that the program exits the loop, and then you said the loop kept going. Presumably one of them was an EXPECTATION and the other was reality. Of course, there are some other things you could have meant, like that the program kept going after the loop. But I doubt it. -- DaveA From md123 at nycap.rr.com Thu Jun 27 16:36:36 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 27 Jun 2013 10:36:36 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51C8C0E4.9040508@davea.name> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> Message-ID: <51CC4DF4.3020205@nycap.rr.com> > > You asked about a "save-as" feature. Why isn't that as simple as > copying the current contents of the saved csv file? Or do you not know > how you would go about copying? > Hi. So I have the logger working, meaning the correct data is being written to the 'internal' file 'logfile.txt' which is opened like this: self.logfile = open('logfile.txt', 'a') And I have the button that starts the file dialog like this: #open file dialog ----------------------------- def openFile(self, evt): with wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.*", wx.OPEN) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() mypath = os.path.basename(path) with open(mypath, "a") as f: Is there a simple way to copy what is in the 'internal' logfile.txt to the file that the user chooses from the button? Thanks! From md123 at nycap.rr.com Thu Jun 27 16:52:19 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 27 Jun 2013 10:52:19 -0400 Subject: [Tutor] Need help printing a pickled data In-Reply-To: <51C9C62E.5060404@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8C2B1.3030907@nycap.rr.com> <51C8E60D.20709@nycap.rr.com> <51C9C62E.5060404@nycap.rr.com> Message-ID: <51CC51A3.1050606@nycap.rr.com> im really sorry guys. i must have had some copy and paste mistake. I didnt want put all that stuff here. From md123 at nycap.rr.com Thu Jun 27 16:55:50 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 27 Jun 2013 10:55:50 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CC4DF4.3020205@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> Message-ID: <51CC5276.2080807@nycap.rr.com> On 06/27/2013 10:36 AM, Matt D wrote: > >> >> You asked about a "save-as" feature. Why isn't that as simple as >> copying the current contents of the saved csv file? Or do you not know >> how you would go about copying? >> > > Hi. So I have the logger working, meaning the correct data is being > written to the 'internal' file 'logfile.txt' which is opened like this: > > self.logfile = open('logfile.txt', 'a') > > And I have the button that starts the file dialog like this: > > #open file dialog ----------------------------- > def openFile(self, evt): > with wx.FileDialog(self, "Choose a file", os.getcwd(), "", > "*.*", wx.OPEN) as dlg: > if dlg.ShowModal() == wx.ID_OK: > path = dlg.GetPath() > mypath = os.path.basename(path) > with open(mypath, "a") as f: > > > Is there a simple way to copy what is in the 'internal' logfile.txt to > the file that the user chooses from the button? > Thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I forgot to mention i have the 'with open(mypath, "a") as f: commented out because it was making an indentation error that i could not fix. From chigga101 at gmail.com Thu Jun 27 17:32:10 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 27 Jun 2013 16:32:10 +0100 Subject: [Tutor] Windows Linux Popen In-Reply-To: References: Message-ID: On Thu, Jun 27, 2013 at 1:41 PM, eryksun wrote: > The error is telling you that Windows can't find "python3". The exe is > named python.exe on Windows, not python3.exe, and it will have to be > on your system PATH to be invoked like that. If you want to run the > script with the current interpreter, you can use sys.executable. For > example: > > >>> subprocess.Popen( > ... [sys.executable, '-c', r'print("spam")']).wait() > spam > 0 i really don't know what to say. no one on irc could resolve my issue and in 1 go you spot where i went wrong. The small change of making 'python3', 'python' has fixed the issue. Thanks you very much:) From chigga101 at gmail.com Thu Jun 27 17:39:00 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 27 Jun 2013 16:39:00 +0100 Subject: [Tutor] Windows Linux Popen In-Reply-To: References: Message-ID: On Thu, Jun 27, 2013 at 1:37 PM, Peter Otten <__peter__ at web.de> wrote: > Your working directory may differ from the directory containing > echo_server.py. Try specifying the full path, e. g. > > SCRIPT = 'c:\\path\to\\echo_server.py' # replace with your actual path > p = subprocess.Popen( > ['python3', SCRIPT]) > oh for some reason i didnt see this message. Thanks i will try this out also From __peter__ at web.de Thu Jun 27 17:55:42 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Jun 2013 17:55:42 +0200 Subject: [Tutor] Windows Linux Popen References: Message-ID: Matthew Ngaha wrote: > On Thu, Jun 27, 2013 at 1:37 PM, Peter Otten <__peter__ at web.de> wrote: > >> Your working directory may differ from the directory containing >> echo_server.py. Try specifying the full path, e. g. >> >> SCRIPT = 'c:\\path\to\\echo_server.py' # replace with your actual path >> p = subprocess.Popen( >> ['python3', SCRIPT]) >> > oh for some reason i didnt see this message. Thanks i will try this out > also I'm sorry, I was wrong. I figured "echo_server.py" wasn't found when it was actually "python3". From davea at davea.name Thu Jun 27 17:55:46 2013 From: davea at davea.name (Dave Angel) Date: Thu, 27 Jun 2013 11:55:46 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CC5276.2080807@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> Message-ID: <51CC6082.4060102@davea.name> On 06/27/2013 10:55 AM, Matt D wrote: > On 06/27/2013 10:36 AM, Matt D wrote: >> >>> >>> You asked about a "save-as" feature. Why isn't that as simple as >>> copying the current contents of the saved csv file? Or do you not know >>> how you would go about copying? >>> >> >> Hi. So I have the logger working, meaning the correct data is being >> written to the 'internal' file 'logfile.txt' which is opened like this: >> >> self.logfile = open('logfile.txt', 'a') >> >> And I have the button that starts the file dialog like this: >> >> #open file dialog ----------------------------- >> def openFile(self, evt): >> with wx.FileDialog(self, "Choose a file", os.getcwd(), "", >> "*.*", wx.OPEN) as dlg: >> if dlg.ShowModal() == wx.ID_OK: >> path = dlg.GetPath() >> mypath = os.path.basename(path) >> with open(mypath, "a") as f: >> >> >> Is there a simple way to copy what is in the 'internal' logfile.txt to >> the file that the user chooses from the button? >> Thanks! shutil.copy(src, dst) See: http://docs.python.org/2/library/shutil.html#shutil.copy > I forgot to mention i have the 'with open(mypath, "a") as f: commented > out because it was making an indentation error that i could not fix. It was indented, and should not have been. The extra indentation FOLLOWS the with statement, it's not correct to indent the line itself. Line it up with mypath= Isn't the rule for indentation simple enough? If a line ends with a colon, you indent the next line. And keep indenting till the scope of that colon ends. I don't know of any exceptions, but if there are any, they're rare. Anyway, when the compiler complains, there aren't many choices on how to change the line, so experimentation should teach you pretty quickly. Maybe you're getting confused about indentation because your editor doesn't handle tabs correctly. If you mix tabs and spaces, you'll drive yourself crazy, at least with 2.x Python 3 tells you about it with a new error. The easy answer (and my strong preference) is to never use tabs in Python sources. Expand all your existing tabs (to 4 column intervals), and tell your editor to always expand the tab key when entering. I suggest you fix this problem first, and understand the fix, before going off and using shutil.copy(). -- DaveA From md123 at nycap.rr.com Thu Jun 27 18:33:40 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 27 Jun 2013 12:33:40 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CC6082.4060102@davea.name> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> Message-ID: <51CC6964.4040704@nycap.rr.com> > > >> I forgot to mention i have the 'with open(mypath, "a") as f: commented >> out because it was making an indentation error that i could not fix. > > It was indented, and should not have been. The extra indentation > FOLLOWS the with statement, it's not correct to indent the line itself. > > Line it up with mypath= > > Isn't the rule for indentation simple enough? If a line ends with a > colon, you indent the next line. And keep indenting till the scope of > that colon ends. I don't know of any exceptions, but if there are any, > they're rare. Anyway, when the compiler complains, there aren't many > choices on how to change the line, so experimentation should teach you > pretty quickly. > > Maybe you're getting confused about indentation because your editor > doesn't handle tabs correctly. If you mix tabs and spaces, you'll drive > yourself crazy, at least with 2.x Python 3 tells you about it with a > new error. The easy answer (and my strong preference) is to never use > tabs in Python sources. Expand all your existing tabs (to 4 column > intervals), and tell your editor to always expand the tab key when > entering. > > I suggest you fix this problem first, and understand the fix, before > going off and using shutil.copy(). > > Thanks! I do have 'with open(mypath, "a") as f:' lined up with the mypath line above (not sure why it indented with the paste to email) and I already replaced all tabs with spaces. seriously there is not one single tab in the whole program. but when that line is not commented out the program bails with the indentation error, other wise its fine. . So i don't know what i can do about that. Thanks! From eryksun at gmail.com Thu Jun 27 18:50:49 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 27 Jun 2013 12:50:49 -0400 Subject: [Tutor] Windows Linux Popen In-Reply-To: References: Message-ID: On Thu, Jun 27, 2013 at 11:32 AM, Matthew Ngaha wrote: > On Thu, Jun 27, 2013 at 1:41 PM, eryksun wrote: > >> The error is telling you that Windows can't find "python3". The exe is >> named python.exe on Windows, not python3.exe, and it will have to be >> on your system PATH to be invoked like that. If you want to run the >> script with the current interpreter, you can use sys.executable. For >> example: >> >> >>> subprocess.Popen( >> ... [sys.executable, '-c', r'print("spam")']).wait() >> spam >> 0 > > i really don't know what to say. no one on irc could resolve my issue > and in 1 go you spot where i went wrong. The small change of making > 'python3', 'python' has fixed the issue. Thanks you very much:) Actually, the part about python.exe needing to be on system PATH isn't correct. On Windows, Popen uses CreateProcess, and I forgot that this searches the application directory first. Here's the complete search order: The directory from which the application loaded. The current directory for the parent process. The 32-bit Windows system directory. The 16-bit Windows system directory. The Windows directory. The directories that are listed in the PATH environment variable. This assume you aren't using the "executable" argument of Popen. The latter maps to the lpApplicationName argument of CreateProcess: The string can specify the full path and file name of the module to execute or it can specify a partial name. In the case of a partial name, the function uses the current drive and current directory to complete the specification. The function will not use the search path. This parameter must include the file name extension; no default extension is assumed. sys.executable works here, also. source: http://msdn.microsoft.com/en-us/library/ms682425 From davea at davea.name Thu Jun 27 18:54:18 2013 From: davea at davea.name (Dave Angel) Date: Thu, 27 Jun 2013 12:54:18 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CC6964.4040704@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> Message-ID: <51CC6E3A.8020609@davea.name> On 06/27/2013 12:33 PM, Matt D wrote: > >> >> >>> I forgot to mention i have the 'with open(mypath, "a") as f: commented >>> out because it was making an indentation error that i could not fix. >> >> It was indented, and should not have been. The extra indentation >> FOLLOWS the with statement, it's not correct to indent the line itself. >> >> Line it up with mypath= >> >> Isn't the rule for indentation simple enough? If a line ends with a >> colon, you indent the next line. And keep indenting till the scope of >> that colon ends. I don't know of any exceptions, but if there are any, >> they're rare. Anyway, when the compiler complains, there aren't many >> choices on how to change the line, so experimentation should teach you >> pretty quickly. >> >> Maybe you're getting confused about indentation because your editor >> doesn't handle tabs correctly. If you mix tabs and spaces, you'll drive >> yourself crazy, at least with 2.x Python 3 tells you about it with a >> new error. The easy answer (and my strong preference) is to never use >> tabs in Python sources. Expand all your existing tabs (to 4 column >> intervals), and tell your editor to always expand the tab key when >> entering. >> >> I suggest you fix this problem first, and understand the fix, before >> going off and using shutil.copy(). >> >> > Thanks! I do have 'with open(mypath, "a") as f:' lined up with the > mypath line above (not sure why it indented with the paste to email) and > I already replaced all tabs with spaces. seriously there is not one > single tab in the whole program. but when that line is not commented out > the program bails with the indentation error, other wise its fine. . > So i don't know what i can do about that. > Thanks! What text editor are you using? Can you literally move the cursor one column at a time and see what column each of those two lines are in? It's a little hard to imagine your email program converting all those spaces to tabs. If it were my file, and I got to this point, I'd be using a dump program to look at the actual file. Or I'd configure my text editor for 40-column tabs, to make them very visible and very obnoxious. In Linux, use tweak, or any of dozens of others. Likewise there are lots in Windows -- no idea what one to suggest. -- DaveA From david at yomtobian.com Thu Jun 27 18:49:57 2013 From: david at yomtobian.com (David Yomtobian) Date: Thu, 27 Jun 2013 12:49:57 -0400 Subject: [Tutor] Tutor Digest, Vol 112, Issue 135 In-Reply-To: References: Message-ID: <534D65ED-7EA9-43C8-939B-6D44E34E4038@yomtobian.com> Remove Sent from my iPhone On Jun 27, 2013, at 11:56 AM, tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Need help appending data to a logfile (Matt D) > 2. Re: Need help printing a pickled data (Matt D) > 3. Re: Need help appending data to a logfile (Matt D) > 4. Re: Windows Linux Popen (Matthew Ngaha) > 5. Re: Windows Linux Popen (Matthew Ngaha) > 6. Re: Windows Linux Popen (Peter Otten) > 7. Re: Need help appending data to a logfile (Dave Angel) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 27 Jun 2013 10:36:36 -0400 > From: Matt D > To: Dave Angel > Cc: "tutor at python.org" > Subject: Re: [Tutor] Need help appending data to a logfile > Message-ID: <51CC4DF4.3020205 at nycap.rr.com> > Content-Type: text/plain; charset=UTF-8 > > >> >> You asked about a "save-as" feature. Why isn't that as simple as >> copying the current contents of the saved csv file? Or do you not know >> how you would go about copying? > > Hi. So I have the logger working, meaning the correct data is being > written to the 'internal' file 'logfile.txt' which is opened like this: > > self.logfile = open('logfile.txt', 'a') > > And I have the button that starts the file dialog like this: > > #open file dialog ----------------------------- > def openFile(self, evt): > with wx.FileDialog(self, "Choose a file", os.getcwd(), "", > "*.*", wx.OPEN) as dlg: > if dlg.ShowModal() == wx.ID_OK: > path = dlg.GetPath() > mypath = os.path.basename(path) > with open(mypath, "a") as f: > > > Is there a simple way to copy what is in the 'internal' logfile.txt to > the file that the user chooses from the button? > Thanks! > > > ------------------------------ > > Message: 2 > Date: Thu, 27 Jun 2013 10:52:19 -0400 > From: Matt D > To: tutor at python.org > Subject: Re: [Tutor] Need help printing a pickled data > Message-ID: <51CC51A3.1050606 at nycap.rr.com> > Content-Type: text/plain; charset=ISO-8859-1 > > im really sorry guys. i must have had some copy and paste mistake. I > didnt want put all that stuff here. > > > > ------------------------------ > > Message: 3 > Date: Thu, 27 Jun 2013 10:55:50 -0400 > From: Matt D > To: tutor at python.org > Subject: Re: [Tutor] Need help appending data to a logfile > Message-ID: <51CC5276.2080807 at nycap.rr.com> > Content-Type: text/plain; charset=ISO-8859-1 > > On 06/27/2013 10:36 AM, Matt D wrote: >> >>> >>> You asked about a "save-as" feature. Why isn't that as simple as >>> copying the current contents of the saved csv file? Or do you not know >>> how you would go about copying? >> >> Hi. So I have the logger working, meaning the correct data is being >> written to the 'internal' file 'logfile.txt' which is opened like this: >> >> self.logfile = open('logfile.txt', 'a') >> >> And I have the button that starts the file dialog like this: >> >> #open file dialog ----------------------------- >> def openFile(self, evt): >> with wx.FileDialog(self, "Choose a file", os.getcwd(), "", >> "*.*", wx.OPEN) as dlg: >> if dlg.ShowModal() == wx.ID_OK: >> path = dlg.GetPath() >> mypath = os.path.basename(path) >> with open(mypath, "a") as f: >> >> >> Is there a simple way to copy what is in the 'internal' logfile.txt to >> the file that the user chooses from the button? >> Thanks! >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > I forgot to mention i have the 'with open(mypath, "a") as f: commented > out because it was making an indentation error that i could not fix. > > > > ------------------------------ > > Message: 4 > Date: Thu, 27 Jun 2013 16:32:10 +0100 > From: Matthew Ngaha > To: eryksun > Cc: "tutor at python.org" > Subject: Re: [Tutor] Windows Linux Popen > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > > On Thu, Jun 27, 2013 at 1:41 PM, eryksun wrote: > >> The error is telling you that Windows can't find "python3". The exe is >> named python.exe on Windows, not python3.exe, and it will have to be >> on your system PATH to be invoked like that. If you want to run the >> script with the current interpreter, you can use sys.executable. For >> example: >> >>>>> subprocess.Popen( >> ... [sys.executable, '-c', r'print("spam")']).wait() >> spam >> 0 > > i really don't know what to say. no one on irc could resolve my issue > and in 1 go you spot where i went wrong. The small change of making > 'python3', 'python' has fixed the issue. Thanks you very much:) > > > ------------------------------ > > Message: 5 > Date: Thu, 27 Jun 2013 16:39:00 +0100 > From: Matthew Ngaha > To: Peter Otten <__peter__ at web.de> > Cc: "tutor at python.org" > Subject: Re: [Tutor] Windows Linux Popen > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > > On Thu, Jun 27, 2013 at 1:37 PM, Peter Otten <__peter__ at web.de> wrote: > >> Your working directory may differ from the directory containing >> echo_server.py. Try specifying the full path, e. g. >> >> SCRIPT = 'c:\\path\to\\echo_server.py' # replace with your actual path >> p = subprocess.Popen( >> ['python3', SCRIPT]) > oh for some reason i didnt see this message. Thanks i will try this out also > > > ------------------------------ > > Message: 6 > Date: Thu, 27 Jun 2013 17:55:42 +0200 > From: Peter Otten <__peter__ at web.de> > To: tutor at python.org > Subject: Re: [Tutor] Windows Linux Popen > Message-ID: > Content-Type: text/plain; charset="ISO-8859-1" > > Matthew Ngaha wrote: > >> On Thu, Jun 27, 2013 at 1:37 PM, Peter Otten <__peter__ at web.de> wrote: >> >>> Your working directory may differ from the directory containing >>> echo_server.py. Try specifying the full path, e. g. >>> >>> SCRIPT = 'c:\\path\to\\echo_server.py' # replace with your actual path >>> p = subprocess.Popen( >>> ['python3', SCRIPT]) >> oh for some reason i didnt see this message. Thanks i will try this out >> also > > I'm sorry, I was wrong. I figured "echo_server.py" wasn't found when it was > actually "python3". > > > > ------------------------------ > > Message: 7 > Date: Thu, 27 Jun 2013 11:55:46 -0400 > From: Dave Angel > To: tutor at python.org > Subject: Re: [Tutor] Need help appending data to a logfile > Message-ID: <51CC6082.4060102 at davea.name> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 06/27/2013 10:55 AM, Matt D wrote: >> On 06/27/2013 10:36 AM, Matt D wrote: >>> >>>> >>>> You asked about a "save-as" feature. Why isn't that as simple as >>>> copying the current contents of the saved csv file? Or do you not know >>>> how you would go about copying? >>> >>> Hi. So I have the logger working, meaning the correct data is being >>> written to the 'internal' file 'logfile.txt' which is opened like this: >>> >>> self.logfile = open('logfile.txt', 'a') >>> >>> And I have the button that starts the file dialog like this: >>> >>> #open file dialog ----------------------------- >>> def openFile(self, evt): >>> with wx.FileDialog(self, "Choose a file", os.getcwd(), "", >>> "*.*", wx.OPEN) as dlg: >>> if dlg.ShowModal() == wx.ID_OK: >>> path = dlg.GetPath() >>> mypath = os.path.basename(path) >>> with open(mypath, "a") as f: >>> >>> >>> Is there a simple way to copy what is in the 'internal' logfile.txt to >>> the file that the user chooses from the button? >>> Thanks! > > shutil.copy(src, dst) > > See: http://docs.python.org/2/library/shutil.html#shutil.copy > > >> I forgot to mention i have the 'with open(mypath, "a") as f: commented >> out because it was making an indentation error that i could not fix. > > It was indented, and should not have been. The extra indentation > FOLLOWS the with statement, it's not correct to indent the line itself. > > Line it up with mypath= > > Isn't the rule for indentation simple enough? If a line ends with a > colon, you indent the next line. And keep indenting till the scope of > that colon ends. I don't know of any exceptions, but if there are any, > they're rare. Anyway, when the compiler complains, there aren't many > choices on how to change the line, so experimentation should teach you > pretty quickly. > > Maybe you're getting confused about indentation because your editor > doesn't handle tabs correctly. If you mix tabs and spaces, you'll drive > yourself crazy, at least with 2.x Python 3 tells you about it with a > new error. The easy answer (and my strong preference) is to never use > tabs in Python sources. Expand all your existing tabs (to 4 column > intervals), and tell your editor to always expand the tab key when entering. > > I suggest you fix this problem first, and understand the fix, before > going off and using shutil.copy(). > > > -- > DaveA > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 112, Issue 135 > *************************************** From thudfoo at gmail.com Thu Jun 27 20:14:25 2013 From: thudfoo at gmail.com (xDog Walker) Date: Thu, 27 Jun 2013 11:14:25 -0700 Subject: [Tutor] Tutor Digest, Vol 112, Issue 135 In-Reply-To: <534D65ED-7EA9-43C8-939B-6D44E34E4038@yomtobian.com> References: <534D65ED-7EA9-43C8-939B-6D44E34E4038@yomtobian.com> Message-ID: <201306271114.26013.thudfoo@gmail.com> On Thursday 2013 June 27 09:49, David Yomtobian wrote: > Remove If you want to unsubscribe, navigate to: http://mail.python.org/mailman/listinfo/tutor and follow the instructions for Unsubscribing. -- Yonder nor sorghum stenches shut ladle gulls stopper torque wet strainers. From chigga101 at gmail.com Thu Jun 27 22:09:26 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 27 Jun 2013 21:09:26 +0100 Subject: [Tutor] Windows Linux Popen In-Reply-To: References: Message-ID: On Thu, Jun 27, 2013 at 5:50 PM, eryksun wrote: > Actually, the part about python.exe needing to be on system PATH isn't > correct. On Windows, Popen uses CreateProcess, and I forgot that this > searches the application directory first. Thanks for the detailed info and link. I have 1 last question. The exercise was using py.test and i have to say i don't really like it at all. Some of it seems really confusing. unittest seems a lot more straight forward and clear in detail. Is it ok to ignore the pythonic test framework and go with unitest?? or should i stick with py.test as it may be better in the long run? From oscar.j.benjamin at gmail.com Thu Jun 27 22:24:37 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 27 Jun 2013 21:24:37 +0100 Subject: [Tutor] Windows Linux Popen In-Reply-To: References: Message-ID: On 27 June 2013 21:09, Matthew Ngaha wrote: > I have 1 last question. The > exercise was using py.test and i have to say i don't really like it at > all. Some of it seems really confusing. unittest seems a lot more > straight forward and clear in detail. Is it ok to ignore the pythonic > test framework and go with unitest?? or should i stick with py.test as > it may be better in the long run? If you prefer unittest then use unittest. I don't consider either of unittest or py.test to be "pythonic". unittest is the standard library solution for unit-testing and is widely used so there's no reason not to use it if it's what you prefer. Oscar From md123 at nycap.rr.com Thu Jun 27 23:09:51 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 27 Jun 2013 17:09:51 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CC6E3A.8020609@davea.name> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> Message-ID: <51CCAA1F.2020808@nycap.rr.com> On 06/27/2013 12:54 PM, Dave Angel wrote: > On 06/27/2013 12:33 PM, Matt D wrote: >> >>> >>> >>>> I forgot to mention i have the 'with open(mypath, "a") as f: commented >>>> out because it was making an indentation error that i could not fix. >>> >>> It was indented, and should not have been. The extra indentation >>> FOLLOWS the with statement, it's not correct to indent the line itself. >>> >>> Line it up with mypath= >>> >>> Isn't the rule for indentation simple enough? If a line ends with a >>> colon, you indent the next line. And keep indenting till the scope of >>> that colon ends. I don't know of any exceptions, but if there are any, >>> they're rare. Anyway, when the compiler complains, there aren't many >>> choices on how to change the line, so experimentation should teach you >>> pretty quickly. >>> >>> Maybe you're getting confused about indentation because your editor >>> doesn't handle tabs correctly. If you mix tabs and spaces, you'll drive >>> yourself crazy, at least with 2.x Python 3 tells you about it with a >>> new error. The easy answer (and my strong preference) is to never use >>> tabs in Python sources. Expand all your existing tabs (to 4 column >>> intervals), and tell your editor to always expand the tab key when >>> entering. >>> >>> I suggest you fix this problem first, and understand the fix, before >>> going off and using shutil.copy(). >>> >>> >> Thanks! I do have 'with open(mypath, "a") as f:' lined up with the >> mypath line above (not sure why it indented with the paste to email) and >> I already replaced all tabs with spaces. seriously there is not one >> single tab in the whole program. but when that line is not commented out >> the program bails with the indentation error, other wise its fine. . >> So i don't know what i can do about that. >> Thanks! > > What text editor are you using? Can you literally move the cursor one > column at a time and see what column each of those two lines are in? > It's a little hard to imagine your email program converting all those > spaces to tabs. > > If it were my file, and I got to this point, I'd be using a dump program > to look at the actual file. Or I'd configure my text editor for > 40-column tabs, to make them very visible and very obnoxious. > > In Linux, use tweak, or any of dozens of others. Likewise there are > lots in Windows -- no idea what one to suggest. > I use gedit. Yes sir, its all spaces, I'm not putting you on there are no tabs in my .py file. none. I am pretty sure if i knew how to put the proper code after the 'with open()' thing, indented of course, that the indentation error would be gone. But Ive been looking at the shutil thing and i can not figure out how to write the right code to go after the 'open with()' that will make whats in 'logfile.txt' get appended into whatever file the user opens. From davea at davea.name Thu Jun 27 23:45:10 2013 From: davea at davea.name (Dave Angel) Date: Thu, 27 Jun 2013 17:45:10 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CCAA1F.2020808@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> Message-ID: <51CCB266.5050206@davea.name> On 06/27/2013 05:09 PM, Matt D wrote: > On 06/27/2013 12:54 PM, Dave Angel wrote: >> On 06/27/2013 12:33 PM, Matt D wrote: >>> >>>> >>>> >>>>> I forgot to mention i have the 'with open(mypath, "a") as f: commented >>>>> out because it was making an indentation error that i could not fix. >>>> >>>> It was indented, and should not have been. The extra indentation >>>> FOLLOWS the with statement, it's not correct to indent the line itself. >>>> >>>> Line it up with mypath= >>>> >>>> Isn't the rule for indentation simple enough? If a line ends with a >>>> colon, you indent the next line. And keep indenting till the scope of >>>> that colon ends. I don't know of any exceptions, but if there are any, >>>> they're rare. Anyway, when the compiler complains, there aren't many >>>> choices on how to change the line, so experimentation should teach you >>>> pretty quickly. >>>> >>>> Maybe you're getting confused about indentation because your editor >>>> doesn't handle tabs correctly. If you mix tabs and spaces, you'll drive >>>> yourself crazy, at least with 2.x Python 3 tells you about it with a >>>> new error. The easy answer (and my strong preference) is to never use >>>> tabs in Python sources. Expand all your existing tabs (to 4 column >>>> intervals), and tell your editor to always expand the tab key when >>>> entering. >>>> >>>> I suggest you fix this problem first, and understand the fix, before >>>> going off and using shutil.copy(). >>>> >>>> >>> Thanks! I do have 'with open(mypath, "a") as f:' lined up with the >>> mypath line above (not sure why it indented with the paste to email) and >>> I already replaced all tabs with spaces. seriously there is not one >>> single tab in the whole program. but when that line is not commented out >>> the program bails with the indentation error, other wise its fine. . >>> So i don't know what i can do about that. >>> Thanks! >> >> What text editor are you using? Can you literally move the cursor one >> column at a time and see what column each of those two lines are in? >> It's a little hard to imagine your email program converting all those >> spaces to tabs. >> >> If it were my file, and I got to this point, I'd be using a dump program >> to look at the actual file. Or I'd configure my text editor for >> 40-column tabs, to make them very visible and very obnoxious. >> >> In Linux, use tweak, or any of dozens of others. Likewise there are >> lots in Windows -- no idea what one to suggest. >> > I use gedit. Yes sir, its all spaces, I'm not putting you on there are > no tabs in my .py file. none. I am pretty sure if i knew how to put the > proper code after the 'with open()' thing, indented of course, that the > indentation error would be gone. But Ive been looking at the shutil > thing and i can not figure out how to write the right code to go after > the 'open with()' that will make whats in 'logfile.txt' get appended > into whatever file the user opens. So you're saying that the exception was on the following line? Why didn't you say so? I just assumed you had clipped the remaining lines of the function when you posted it. So, the way to get rid of this new indentation error is to add a pass statement inside the with clause. Indent it by 4 columns. If that works, then you'll know how to deal with it next time. As for the shutil.copy() function, how complex can it be? It takes two file names, source and destination. It does not need a with statement since it wants strings, not file handles. You might get into trouble on some OS's with the source file already open, but since you open it with append, it should be trivial to close and reopen it. -- DaveA From eryksun at gmail.com Thu Jun 27 23:55:34 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 27 Jun 2013 17:55:34 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CCAA1F.2020808@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> Message-ID: On Thu, Jun 27, 2013 at 5:09 PM, Matt D wrote: > I use gedit. Yes sir, its all spaces, I'm not putting you on there are > no tabs in my .py file. none. I am pretty sure if i knew how to put the > proper code after the 'with open()' thing, indented of course, that the > indentation error would be gone. But Ive been looking at the shutil > thing and i can not figure out how to write the right code to go after > the 'open with()' that will make whats in 'logfile.txt' get appended > into whatever file the user opens. The code you pasted earlier uses tabs, except for the last line: >>> print(src.replace('\t', 'tab>')) tab>def openFile(self, evt): tab>tab>with wx.FileDialog(self, "Choose a file", os.getcwd(), "", tab> "*.*", wx.OPEN) as dlg: tab>tab>tab>if dlg.ShowModal() == wx.ID_OK: tab>tab>tab>tab>path = dlg.GetPath() tab>tab>tab>tab>mypath = os.path.basename(path) with open(mypath, "a") as f: Maybe tabs are being replaced with 8 spaces, while the rest of your code uses 4-space indents. Note that the final "with open" is indented by 32 spaces instead of 16: >>> src.splitlines()[-1].find('with') 32 Just make sure you're indenting consistently. I use dotted indentation guides and visible spaces/tabs. It makes the edit window noisy, but I don't really notice it. From darinlh at gmail.com Thu Jun 27 23:57:36 2013 From: darinlh at gmail.com (Darin Lawson Hosking) Date: Thu, 27 Jun 2013 16:57:36 -0500 Subject: [Tutor] python / gtk / Webkit app wrapper. Message-ID: Greetings all, Was wondering if one of you fine python wizards could help me with trying to fix a python / gtk / Webkit app wrapper. Here is a simple version of what I am trying to do. http://pastebin.com/2zi0SgfT The HUGE hurdle I am having is activating the Webkit spell checker for forms. from gtkspellcheck import SpellChecker window = gtk.Window(gtk.WindowType(0)) view = gtk.TextView() spellchecker = SpellChecker(view) works fine for a text / editor type window but win = gtk.Window(gtk.WindowType(0)) web = webkit.WebView() spellchecker = SpellChecker(web) returns Traceback (most recent call last): File "main_wrapper.py", line 24, in spellchecker = SpellChecker(web) File "/usr/local/lib/python2.7/dist-packages/gtkspellcheck/spellcheck.py", line 222, in __init__ self.buffer_initialize() File "/usr/local/lib/python2.7/dist-packages/gtkspellcheck/spellcheck.py", line 258, in buffer_initialize self._buffer = self._view.get_buffer() AttributeError: 'webkit.WebView' object has no attribute 'get_buffer' I also tried this and it appears to run ie no errors BUT does not highlight misspellings? settings = webkit.WebSettings() settings.set_property('enable-spell-checking', True) Any help would be greatly appreciated Darin -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Fri Jun 28 00:06:42 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Thu, 27 Jun 2013 15:06:42 -0700 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: <51CC324E.5000903@pearwood.info> References: <51CC324E.5000903@pearwood.info> Message-ID: On 27 June 2013 05:38, Steven D'Aprano wrote: > Unit tests are great, but the learning curve is rather steep. I recommend > that you start with doctests. That sounds better. unittests look like overkill for the putzing around I'm doing at this level, but your example of doctests looks pretty simple. -- Jim Every time I buy "As Seen on TV" it turns out to be junk. From md123 at nycap.rr.com Fri Jun 28 00:19:30 2013 From: md123 at nycap.rr.com (Matt D) Date: Thu, 27 Jun 2013 18:19:30 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> Message-ID: <51CCBA72.8010408@nycap.rr.com> On 06/27/2013 05:55 PM, eryksun wrote: > On Thu, Jun 27, 2013 at 5:09 PM, Matt D wrote: >> I use gedit. Yes sir, its all spaces, I'm not putting you on there are >> no tabs in my .py file. none. I am pretty sure if i knew how to put the >> proper code after the 'with open()' thing, indented of course, that the >> indentation error would be gone. But Ive been looking at the shutil >> thing and i can not figure out how to write the right code to go after >> the 'open with()' that will make whats in 'logfile.txt' get appended >> into whatever file the user opens. > > The code you pasted earlier uses tabs, except for the last line: > > >>> print(src.replace('\t', 'tab>')) > tab>def openFile(self, evt): > tab>tab>with wx.FileDialog(self, "Choose a file", os.getcwd(), "", > tab> "*.*", wx.OPEN) as dlg: > tab>tab>tab>if dlg.ShowModal() == wx.ID_OK: > tab>tab>tab>tab>path = dlg.GetPath() > tab>tab>tab>tab>mypath = os.path.basename(path) > with open(mypath, "a") as f: > > Maybe tabs are being replaced with 8 spaces, while the rest of your > code uses 4-space indents. Note that the final "with open" is indented > by 32 spaces instead of 16: > > >>> src.splitlines()[-1].find('with') > 32 > > Just make sure you're indenting consistently. I use dotted indentation > guides and visible spaces/tabs. It makes the edit window noisy, but I > don't really notice it. > yeah its not like that in my .py file. i think im doing something weird when i paste into my email. is use only spaces in my .py file. and the 'with open()' is lined up with the 'mypath'. I get the indentation error because i dont have any code under the 'with open()' line to get done what i need. which is to copy logfile.txt into whatever file the user chooses in the file dialog. From eryksun at gmail.com Fri Jun 28 00:39:07 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 27 Jun 2013 18:39:07 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CCBA72.8010408@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCBA72.8010408@nycap.rr.com> Message-ID: On Thu, Jun 27, 2013 at 6:19 PM, Matt D wrote: > yeah its not like that in my .py file. i think im doing something weird > when i paste into my email. is use only spaces in my .py file. and the > 'with open()' is lined up with the 'mypath'. I get the indentation > error because i dont have any code under the 'with open()' line to get > done what i need. which is to copy logfile.txt into whatever file the > user chooses in the file dialog. Sorry, I didn't know what to make of the "the proper code after 'with open'". I should have asked. I assumed you still had a statement there, like what you had before, i.e. f.writelines(self.log_array). Compound statements (if/elif/else, try/except/finally, while, for, with, def, class) have a colon followed by one (not zero) or more statements. A simple statement can go on the same line after the colon. Otherwise use an indented block. In this case you can simply use: with open(mypath, "a") as f: pass From cybervigilante at gmail.com Fri Jun 28 01:39:25 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Thu, 27 Jun 2013 16:39:25 -0700 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: <51CC324E.5000903@pearwood.info> References: <51CC324E.5000903@pearwood.info> Message-ID: On 27 June 2013 05:38, Steven D'Aprano wrote: > Unit tests are great, but the learning curve is rather steep. I recommend that you start with doctests. I tried a simple one and it worked, but a puzzlement. Does it Only test what you've hard-coded? That is, here is a simple test: def doubler(inp): '''Return a doubled number or string >>> doubler(24) 48 >>> doubler('zark') 'zarkzark' ''' return inp * 2 This works on 24 or 'zark' as input when I run C:\Python33\Jimprogs>python -m doctest "C:/python33/jimprogs/docstringtest.py" --verbose' and doctest prints: 48 zarkzark And it fails if I put 'this doesn't work' as the return value of the function: 1 items had failures: 2 of 2 in docstringtest. ***Test Failed*** 2 failures. Although that doesn't tell me much. But it also works on different input --> 189 and 'plantagenet,' to print: 378 plantagenetplantagenet It's odd to me that it doesn't fail on what I haven't hardcoded. I don't see how docstring could figure what I might be doing, so I assume that although it returns anything valid, it Only tests on the hardcoded values, 24 and 'zark'. Is this correct? In which case it seems like a lot of hard coding would be needed unless you tested only endpoints or what might be problematic. Or is it doing something more? -- Jim Every time I buy "As Seen on TV" it turns out to be junk. From alan.gauld at btinternet.com Fri Jun 28 02:01:14 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Jun 2013 01:01:14 +0100 Subject: [Tutor] python / gtk / Webkit app wrapper. In-Reply-To: References: Message-ID: On 27/06/13 22:57, Darin Lawson Hosking wrote: > Greetings all, > > Was wondering if one of you fine python wizards could help me with > trying to fix a python / gtk / Webkit app wrapper. This list is for people learning the Python language and its standard library. For info on GTk and Webkit you should probably try more specialised fora or possibly the main Python mailing list/newsgroup. Otherwise its a matter of pure luck whether anyone here knows about those libraries. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at davea.name Fri Jun 28 02:05:31 2013 From: davea at davea.name (Dave Angel) Date: Thu, 27 Jun 2013 20:05:31 -0400 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: References: <51CC324E.5000903@pearwood.info> Message-ID: <51CCD34B.2030002@davea.name> On 06/27/2013 07:39 PM, Jim Mooney wrote: > On 27 June 2013 05:38, Steven D'Aprano wrote: > >> Unit tests are great, but the learning curve is rather steep. I recommend that you start with doctests. > > I tried a simple one and it worked, but a puzzlement. Does it Only > test what you've hard-coded? Precisely. There's no way that it could test anything else, since it has no way of reading your mind to see what you intended. > That is, here is a simple test: > > def doubler(inp): > '''Return a doubled number or string > >>> doubler(24) > 48 > >>> doubler('zark') > 'zarkzark' > ''' > return inp * 2 > > This works on 24 or 'zark' as input when I run > C:\Python33\Jimprogs>python -m doctest > "C:/python33/jimprogs/docstringtest.py" --verbose' > and doctest prints: > 48 > zarkzark > > And it fails if I put 'this doesn't work' as the return value of the function: > > 1 items had failures: > 2 of 2 in docstringtest. > ***Test Failed*** 2 failures. > > Although that doesn't tell me much. > > But it also works on different input --> 189 and 'plantagenet,' to print: > 378 > plantagenetplantagenet > > It's odd to me that it doesn't fail on what I haven't hardcoded. > > I don't see how docstring could figure what I might be doing, so I > assume that although it returns anything valid, it Only tests on the > hardcoded values, 24 and 'zark'. Is this correct? In which case it > seems like a lot of hard coding would be needed unless you tested only > endpoints or what might be problematic. > > Or is it doing something more? > Nope. it is limited to the tests you write. And those tests are necessarily fairly simple. That's why there are other testing frameworks which support much more, with a much higher learning curve. But you'd be surprised how much code that's written that gets no useful repeatable testing at all. Or how much software that has tests which are seldom run before a release. I've seen software released for which the source code didn't even exist, and couldn't readily exist... "Hack something together, just get it 'working'" That was when i was just transferring into a department, and it never happened again. -- DaveA From eryksun at gmail.com Fri Jun 28 02:07:03 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 27 Jun 2013 20:07:03 -0400 Subject: [Tutor] python / gtk / Webkit app wrapper. In-Reply-To: References: Message-ID: On Thu, Jun 27, 2013 at 5:57 PM, Darin Lawson Hosking wrote: > > I also tried this and it appears to run ie no errors BUT does not highlight > misspellings? > > settings = webkit.WebSettings() > settings.set_property('enable-spell-checking', True) Try: web = webkit.WebView() web.open('...') settings = web.get_settings() settings.set_property('enable-spell-checking', True) settings.set_property('spell-checking-languages', 'en_GB') Replace 'en_GB' with your desired language_country code. From oscar.j.benjamin at gmail.com Fri Jun 28 02:08:01 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 28 Jun 2013 01:08:01 +0100 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: References: <51CC324E.5000903@pearwood.info> Message-ID: On 28 June 2013 00:39, Jim Mooney wrote: > On 27 June 2013 05:38, Steven D'Aprano wrote: > >> Unit tests are great, but the learning curve is rather steep. I recommend that you start with doctests. I agree. I prefer them for smaller applications. > I tried a simple one and it worked, but a puzzlement. Does it Only > test what you've hard-coded? That is, here is a simple test: > > def doubler(inp): > '''Return a doubled number or string > >>> doubler(24) > 48 > >>> doubler('zark') > 'zarkzark' > ''' > return inp * 2 > > This works on 24 or 'zark' as input when I run > C:\Python33\Jimprogs>python -m doctest > "C:/python33/jimprogs/docstringtest.py" --verbose' > and doctest prints: > 48 > zarkzark > > And it fails if I put 'this doesn't work' as the return value of the function: > > 1 items had failures: > 2 of 2 in docstringtest. > ***Test Failed*** 2 failures. > > Although that doesn't tell me much. I've never run the docstringtest.py script before. I would do as Steven suggested and use python -m mymod.py: oscar at lwench:~/current/tmp/unit$ cat mymod.py # mymod.py def doubler(inp): '''Return a doubled number or string >>> doubler(24) 48 >>> doubler('zark') 'zarkzark' >>> doubler('foo') let's fail this test ''' return inp * 2 oscar at lwench:~/current/tmp/unit$ python -m doctest mymod.py ********************************************************************** File "mymod.py", line 9, in mymod.doubler Failed example: doubler('foo') Expected: let's fail this test Got: 'foofoo' ********************************************************************** 1 items had failures: 1 of 3 in mymod.doubler ***Test Failed*** 1 failures. oscar at lwench:~/current/tmp/unit$ The output there seems pretty well explained to me. > But it also works on different input --> 189 and 'plantagenet,' to print: > 378 > plantagenetplantagenet > > It's odd to me that it doesn't fail on what I haven't hardcoded. How would it know about things that you haven't hard-coded? > I don't see how docstring could figure what I might be doing, so I > assume that although it returns anything valid, it Only tests on the > hardcoded values, 24 and 'zark'. Is this correct? In which case it > seems like a lot of hard coding would be needed unless you tested only > endpoints or what might be problematic. > > Or is it doing something more? No. It tests the hard-coded values: that's the point. You, as the programmer, say I expect exactly this output from exactly this input and it tests that the code does what you wanted. If it did anything more clever it would defeat the point of unit tests which is that they enable you to be confident that exactly this input gives exactly that output for each of the cases that you carefully considered. Yes a lot of hard-coding is needed in any comprehensive set of unit tests. But sometimes comprehensive testing just isn't needed. For simple cases it's often enough just to check that it works for a couple of common cases and perhaps a few corner cases and then that's fine (if the tests pass). Oscar From darinlh at gmail.com Fri Jun 28 03:13:32 2013 From: darinlh at gmail.com (Darin Lawson Hosking) Date: Thu, 27 Jun 2013 20:13:32 -0500 Subject: [Tutor] python / gtk / Webkit app wrapper. In-Reply-To: References: Message-ID: Thank you both for the response Alan - This is my first python program (actually first anything, besides simple one line shell scripts) and if I broke protocol I do apologize. eryksun - that did it after pulling out the indention after I copy pasted :) BUT it is missing the (right click suggested spellings menu) Now off to find that :) if you happen to know of some docs on where I could find that I would appreciate a lead. Thank you again Darin On Thu, Jun 27, 2013 at 7:07 PM, eryksun wrote: > On Thu, Jun 27, 2013 at 5:57 PM, Darin Lawson Hosking > wrote: > > > > I also tried this and it appears to run ie no errors BUT does not > highlight > > misspellings? > > > > settings = webkit.WebSettings() > > settings.set_property('enable-spell-checking', True) > > Try: > > web = webkit.WebView() > web.open('...') > settings = web.get_settings() > settings.set_property('enable-spell-checking', True) > settings.set_property('spell-checking-languages', 'en_GB') > > Replace 'en_GB' with your desired language_country code. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Fri Jun 28 03:32:04 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Thu, 27 Jun 2013 18:32:04 -0700 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: <51CCD34B.2030002@davea.name> References: <51CC324E.5000903@pearwood.info> <51CCD34B.2030002@davea.name> Message-ID: On 27 June 2013 17:05, Dave Angel >Nope. it is limited to the tests you write. And those tests are necessarily fairly simple. Hmm, so it seems a lot of trouble for a few hardcoded tests I could run myself from the IDE interpreter window. Or better yet, I could code a loop with some random input, and some extreme cases, and work the function out myself. I guess there is no easy substitute for simply beating up your functions with a slew of garbage, since you're the one who understands them ;') Jim -- "When I use a word," Humpty Dumpty said, in rather a scornful tone, "it means just what I choose it to mean- neither more nor less." "The question is," said Alice, "whether you can make words mean so many different things." "The question is," said Humpty Dumpty, "which is to be master-that's all." From davea at davea.name Fri Jun 28 03:50:58 2013 From: davea at davea.name (Dave Angel) Date: Thu, 27 Jun 2013 21:50:58 -0400 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: References: <51CC324E.5000903@pearwood.info> <51CCD34B.2030002@davea.name> Message-ID: <51CCEC02.8070409@davea.name> On 06/27/2013 09:32 PM, Jim Mooney wrote: > On 27 June 2013 17:05, Dave Angel > >> Nope. it is limited to the tests you write. And those tests are necessarily fairly simple. > > Hmm, so it seems a lot of trouble for a few hardcoded tests I could > run myself from the IDE interpreter window. NO. You're completely missing the point. If you don't automate your tests, you'll be neither consistent nor thorough. You want tests that can be run identically three months from now when you're not sure you even remember what that function does. or ten minutes from now when you change some other function that breaks the way this one works. > Or better yet, I could > code a loop with some random input, and some extreme cases, and work > the function out myself. I guess there is no easy substitute for > simply beating up your functions with a slew of garbage, since you're > the one who understands them ;') > The only substitute for "beating up your functions" is hiring someone else to do it for you. They'll catch things you'll miss, simply because they aren't prejudiced by the "knowledge" that "it must be right." But if all they do is interactive testing, then you've still missed the boat. And you might be amazed what you can accomplish with "simple tests." Most trivial example could be a testing function, whose expected output is either pass or fail. You put a two-line doctest on it, and now your real function gets a real workout. But you can also call things inside a list comprehension, and test that all(mycomp) is True. And so on. Only when you outgrow doctest do you need a testing harness. And at that point, you might actually understand why you need it. -- DaveA From eryksun at gmail.com Fri Jun 28 05:06:26 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 27 Jun 2013 23:06:26 -0400 Subject: [Tutor] python / gtk / Webkit app wrapper. In-Reply-To: References: Message-ID: On Thu, Jun 27, 2013 at 9:13 PM, Darin Lawson Hosking wrote: > BUT it is missing the (right click suggested spellings menu) > Now off to find that :) if you happen to know of some docs on where I could > find that I would appreciate a lead. You have to first select the word to get the spelling suggestions, "Ignore Spelling", and "Learn Spelling" on the context menu. For docs the best I could come up with is the API reference: http://webkitgtk.org/reference/webkitgtk/stable From steve at pearwood.info Fri Jun 28 07:09:03 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 28 Jun 2013 15:09:03 +1000 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: References: <51CC324E.5000903@pearwood.info> <51CCD34B.2030002@davea.name> Message-ID: <51CD1A6F.4000800@pearwood.info> On 28/06/13 11:32, Jim Mooney wrote: > On 27 June 2013 17:05, Dave Angel > >> Nope. it is limited to the tests you write. And those tests are necessarily fairly simple. > > Hmm, so it seems a lot of trouble for a few hardcoded tests I could > run myself from the IDE interpreter window. Or better yet, I could > code a loop with some random input, and some extreme cases, and work > the function out myself. I guess there is no easy substitute for > simply beating up your functions with a slew of garbage, since you're > the one who understands them ;') I'm afraid that you've missed the point, sorry :-) Or actually, multiple points. Firstly, doctests are *documentation first*, and tests secondly. They show by example what the function does. It is a real pain reading five pages of documentation and at the end you say, "yes, but what does this function actually *do*???" Examples can help to make it clear. The only thing worse than no examples are examples that are wrong. >>> doubler("3.1415") 6.283 Do you see the subtle bug? If you write a wrong example, you may never realise it is wrong, and your users will be confused and distressed. Sometimes your users are *you*, and you wrote the software a long time ago and don't remember what it is supposed to do but you can't get it to work like the examples show... But if you do it as a doctest, you will find out that the example is wrong because the test will fail the first time you run it. Then you can fix the example while it is still fresh in your mind. Another point that you missed is that doctests are *automated*, which is much better than manual testing. Sure, you can always do your own testing at the interactive interpreter. For instance, I might sit down to test my statistics module. I can call up the interactive interpreter, and sit down for an hour and a half and run tests like this: import statistics statistics.mean([1, 2, 5, 4, 7, 1, 9, 2]) statistics.stdev([4, 7, 0, 1, 2, 3, 3, 3, 7, 3]) statistics.stdev([]) and so on. And then, tomorrow, when I've made some changes to the code, I have to do the whole thing again. Over and over again. Who the hell can be bothered? Certainly not me. That's why testing doesn't happen, or if it does happen, it's only the most ineffective, obvious, simple tests, the ones which are the least likely to pick up bugs. And of course I can't use my own module to test that my module is getting the right answers! Having to calculate the expected answers by hand (or at least using a different program) is a lot of work, and I don't want to have to do that work more than once. If I'm sensible, I'll write the answers down somewhere, together with the question of course. But then I'm likely to lose the paper, and even if I don't, I still have to re-type it into the interpreter. But with *automated tests*, I only need to pre-calculate the answers once, put them into a suite of tests, and the computer can run them over and over again. I can start off with one test, and then over time add more tests, until I have five hundred. And the computer can run all five hundred of them in the time I could manually do one or two. Instead of needing the discipline to spend an hour or three manually calculating results and comparing them to the module's results in an ad hoc manner, I only need the discipline to run a couple of simple commands such as: python -m doctest statistics.py python -m unittest statistics_tests.py or equivalent. Any tests are better than no tests, and doctest is a good way to get started with a few, low-impact, easy-to-use tests without the learning curve of unittest. -- Steven From cybervigilante at gmail.com Fri Jun 28 06:18:18 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Thu, 27 Jun 2013 21:18:18 -0700 Subject: [Tutor] multiple function returns Message-ID: What's the Pythonic standard on multiple returns from a function? It seems easiest to just return from the point where the function fails or succeeds, even it that's multiple points. Or is it considered best to defer everything to one return at the end? Jim -- "When I use a word," Humpty Dumpty said, in rather a scornful tone, "it means just what I choose it to mean- neither more nor less." "The question is," said Alice, "whether you can make words mean so many different things." "The question is," said Humpty Dumpty, "which is to be master-that's all." From zachary.ware+pytut at gmail.com Fri Jun 28 09:10:54 2013 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Fri, 28 Jun 2013 02:10:54 -0500 Subject: [Tutor] multiple function returns In-Reply-To: References: Message-ID: <7872a015-f2bb-4e9d-8d26-75bde933e918@email.android.com> Jim Mooney wrote: >What's the Pythonic standard on multiple returns from a function? It >seems easiest to just return from the point where the function fails >or succeeds, even it that's multiple points. Or is it considered best >to defer everything to one return at the end? > Essentially, return where you see fit. A lot of times, you'll see something like this: >>> def foo(x): ... if x: ... return True ... return False ... >>> foo(1) True >>> foo(0) False I'll leave it to you to work out why that works. It's very handy! Zach ---- Please excuse my phone-induced brevity. From __peter__ at web.de Fri Jun 28 09:31:07 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Jun 2013 09:31:07 +0200 Subject: [Tutor] unwanted 'zero' ending References: <51CC324E.5000903@pearwood.info> Message-ID: Steven D'Aprano wrote: > On 27/06/13 18:30, Peter Otten wrote: >> Jim Mooney wrote: >> >>> On 27 June 2013 00:43, Alan Gauld wrote: >>>> Take the constant definitions out of the function.... >>> >>> Since the program has an error And needs simplification (no doubt >>> interdependent), but it would be hard to do both at once, this brings >>> up a good general question: Is it best, in such cases, to correct the >>> error, then simplify, or simplify, then correct the error? >> >> That depends. Ideally you'd have unittests to ensure that you aren't >> introducing new errors with the simplification process. >> >> So if you don't have them already now is the time to formalize your >> ad-hoc tests. > > > Unit tests are great, but the learning curve is rather steep. I recommend > that you start with doctests. There is some overhead, e. g. to match your doctest you need import unittest from num_to_str import num_to_name class TestNumToName(unittest.TestCase): def test_valid(self): self.assertEquals( num_to_name(42), "forty-two") self.assertEquals( num_to_name(3579), "three thousand five hundred and seventy-nine") That and assertRaises() def test_invalid(self): self.assertRaises(ValueError, num_to_name, -1) self.assertRaises(TypeError, num_to_name, "7") self.assertRaises(TypeError, num_to_name, None) will take you a long way. doctest makes it easier to test functions that print def add(a, b): print a + b (look at to learn how this can be covered with unit tests) but I'd argue that mixing calculations and output is never a good idea anyway. Also, there's no need to use unittest exclusively. > When you write a function, add a docstring ("documentation string") that > explains what the function does. Include examples showing how it is > expected to work: > > > def num_to_name(number): > """Return the English name of int number. > > >>> num_to_name(42) > 'forty-two' > >>> num_to_name(3579) > 'three thousand five hundred and seventy-nine' > > """ > [code goes here as normal] While one illustrative example or two even improve the docstring once you add the corner cases it becomes too noisy for my taste. Whatever approach you pick, unittest, doctest, or a combination, your code will improve -- not just because you are verifying its correctness to some extent, but also because the inherent question "How can I test it?" will lead to a better overall structure. From alan.gauld at btinternet.com Fri Jun 28 09:40:01 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Jun 2013 08:40:01 +0100 Subject: [Tutor] python / gtk / Webkit app wrapper. In-Reply-To: References: Message-ID: On 28/06/13 02:13, Darin Lawson Hosking wrote: > Alan - This is my first python program (actually first anything, besides > simple one line shell scripts) and if I broke protocol I do apologize. Its not a matter of breaking protocol, just posting where you get the highest chance of getting a good answer. As it happens you got lucky but for non core Python stuff it's usually more helpful to try a more specialized forum. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Fri Jun 28 09:48:23 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Jun 2013 09:48:23 +0200 Subject: [Tutor] multiple function returns References: Message-ID: Jim Mooney wrote: > What's the Pythonic standard on multiple returns from a function? It > seems easiest to just return from the point where the function fails > or succeeds, even it that's multiple points. Or is it considered best > to defer everything to one return at the end? Well, if the function *fails* it is usually better to have it raise an exception: >>> def num_to_name(value): ... if value == 0: ... return "zero" ... if value < 0: ... return "minus " + num_to_name(-value) ... if value != 42: ... raise ValueError("Sorry, I cannot convert {!r}".format(value)) ... return "forty-two" ... >>> num_to_name(0) 'zero' >>> num_to_name(42) 'forty-two' >>> num_to_name(-42) 'minus forty-two' >>> num_to_name(7) Traceback (most recent call last): File "", line 1, in File "", line 7, in num_to_name ValueError: Sorry, I cannot convert 7 >>> num_to_name(None) Traceback (most recent call last): File "", line 1, in File "", line 5, in num_to_name TypeError: bad operand type for unary -: 'NoneType' You get the last exception for free -- for the price that the error message is not under your control. From alan.gauld at btinternet.com Fri Jun 28 09:44:55 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Jun 2013 08:44:55 +0100 Subject: [Tutor] multiple function returns In-Reply-To: References: Message-ID: On 28/06/13 05:18, Jim Mooney wrote: > What's the Pythonic standard on multiple returns from a function? There is no standard. Multiple returns are quite common but they come with all the usual caveats for using them, they can introduce complexity and hard to find bugs so use them sensibly. Computer Science purists don't like them for good theoretical reasons, but personally I find them one of the least offensive of the "rule breakers" and forcing a single exit can often involve ugly extra conditionals etc. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jun 28 09:52:28 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Jun 2013 08:52:28 +0100 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: References: <51CC324E.5000903@pearwood.info> <51CCD34B.2030002@davea.name> Message-ID: On 28/06/13 02:32, Jim Mooney wrote: > Hmm, so it seems a lot of trouble for a few hardcoded tests I could > run myself from the IDE interpreter window. The point is that you should write the doc strings before you write the code. Then anyone can test that your function does at least work for the original design cases. And if you change it you can run that minimum test set very easily and quickly. > the function out myself. I guess there is no easy substitute for > simply beating up your functions with a slew of garbage, since you're > the one who understands them ;') And that's precisely why the person who writes the code is the worst possible person to test it. If you know how it works you are usually blind sided to it's defects! Ideally all testing should be done by a third party, but in practice it's rarely possible. But it's one of the ideas behind the concept of pair-programming. But if you want comprehensive testing, regardless of who is doing it, you do need more than doctest. It's a useful sanity check and much better than nothing or even random hacking at the >>> prompt. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Fri Jun 28 12:26:24 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 28 Jun 2013 20:26:24 +1000 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: References: <51CC324E.5000903@pearwood.info> Message-ID: <51CD64D0.3040709@pearwood.info> On 28/06/13 17:31, Peter Otten wrote: > Whatever approach you pick, unittest, doctest, or a combination, your code > will improve -- not just because you are verifying its correctness to some > extent, but also because the inherent question "How can I test it?" will > lead to a better overall structure. Well said. -- Steven From steve at pearwood.info Fri Jun 28 13:19:53 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 28 Jun 2013 21:19:53 +1000 Subject: [Tutor] multiple function returns In-Reply-To: References: Message-ID: <51CD7159.50507@pearwood.info> On 28/06/13 14:18, Jim Mooney wrote: > What's the Pythonic standard on multiple returns from a function? It > seems easiest to just return from the point where the function fails > or succeeds, even it that's multiple points. Or is it considered best > to defer everything to one return at the end? The first. Python functions have one entry point, the top of the function. They can have multiple exit points, anywhere you have a return statement. Languages like Pascal enforce a single exit point, which means you end up writing rubbish code like this: # Using Python syntax instead of Pascal def function(arg): done = False result = some_calculation(arg) if condition(): done = True if not done: result = more_calculations() if condition(): done = True if not done: result = even_more_calculations() if condition(): done = True if not done: result = are_we_done_yet() return result compared to: def function(arg): result = some_calculation(arg) if condition(): return result result = more_calculations() if condition(): return result result = even_more_calculations() if condition(): return result return are_we_done_yet() -- Steven From md123 at nycap.rr.com Fri Jun 28 13:27:36 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 28 Jun 2013 07:27:36 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CCB266.5050206@davea.name> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> Message-ID: <51CD7328.8070407@nycap.rr.com> > > As for the shutil.copy() function, how complex can it be? It takes two > file names, source and destination. It does not need a with statement > since it wants strings, not file handles. > > You might get into trouble on some OS's with the source file already > open, but since you open it with append, it should be trivial to close > and reopen it. > > The problem here is that the, I am pretty sure that, using anything from shutil overwrite what is currently in the 'dst' file. So if I am starting and stopping the program, that file is going to lose everything. There has to be a way around this. From davea at davea.name Fri Jun 28 13:37:54 2013 From: davea at davea.name (Dave Angel) Date: Fri, 28 Jun 2013 07:37:54 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CD7328.8070407@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> Message-ID: <51CD7592.7030902@davea.name> On 06/28/2013 07:27 AM, Matt D wrote: > >> >> As for the shutil.copy() function, how complex can it be? It takes two >> file names, source and destination. It does not need a with statement >> since it wants strings, not file handles. >> >> You might get into trouble on some OS's with the source file already >> open, but since you open it with append, it should be trivial to close >> and reopen it. >> >> > The problem here is that the, I am pretty sure that, using anything from > shutil overwrite what is currently in the 'dst' file. So if I am > starting and stopping the program, that file is going to lose > everything. There has to be a way around this. And that's exactly what Save-As is supposed to do. If you want something different, you might have said so. -- DaveA From md123 at nycap.rr.com Fri Jun 28 14:29:32 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 28 Jun 2013 08:29:32 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CD7592.7030902@davea.name> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> Message-ID: <51CD81AC.5070608@nycap.rr.com> On 06/28/2013 07:37 AM, Dave Angel wrote: > On 06/28/2013 07:27 AM, Matt D wrote: >> >>> >>> As for the shutil.copy() function, how complex can it be? It takes two >>> file names, source and destination. It does not need a with statement >>> since it wants strings, not file handles. >>> >>> You might get into trouble on some OS's with the source file already >>> open, but since you open it with append, it should be trivial to close >>> and reopen it. >>> >>> >> The problem here is that the, I am pretty sure that, using anything from >> shutil overwrite what is currently in the 'dst' file. So if I am >> starting and stopping the program, that file is going to lose >> everything. There has to be a way around this. > > > And that's exactly what Save-As is supposed to do. If you want > something different, you might have said so. > > Right. I am thinking something like this: opening the logfile.txt in 'w' so that can overwrite each time the program is run and that data will only be what has been logged in that run. And open the 'mypath' in 'a' and somehow append whats in 'logfile' into 'mypath'. I have been unable to find any sort of example of this. From md123 at nycap.rr.com Fri Jun 28 15:18:56 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 28 Jun 2013 09:18:56 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CD7592.7030902@davea.name> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> Message-ID: <51CD8D40.4000700@nycap.rr.com> On 06/28/2013 07:37 AM, Dave Angel wrote: > On 06/28/2013 07:27 AM, Matt D wrote: >> >>> >>> As for the shutil.copy() function, how complex can it be? It takes two >>> file names, source and destination. It does not need a with statement >>> since it wants strings, not file handles. >>> >>> You might get into trouble on some OS's with the source file already >>> open, but since you open it with append, it should be trivial to close >>> and reopen it. >>> >>> >> The problem here is that the, I am pretty sure that, using anything from >> shutil overwrite what is currently in the 'dst' file. So if I am >> starting and stopping the program, that file is going to lose >> everything. There has to be a way around this. > > > And that's exactly what Save-As is supposed to do. If you want > something different, you might have said so. > > what if i did some thing like this i saw on stackoverflow: f = open("bigfile.txt", "w") for tempfile in tempfiles: while True: data = tempfile.read(65536) if data: f.write(data) else: break could i make the 'logfile.txt. a tempfile? and could the f.write be changed to f.append? From steve at pearwood.info Fri Jun 28 15:42:33 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 28 Jun 2013 23:42:33 +1000 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CD8D40.4000700@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> Message-ID: <51CD92C9.6040303@pearwood.info> On 28/06/13 23:18, Matt D wrote: > what if i did some thing like this i saw on stackoverflow: > > f = open("bigfile.txt", "w") That clears any existing content of bigfile.txt, and opens it for writing. Do you intend to clear the content? > for tempfile in tempfiles: What is in tempfiles? A list of files opened for reading? Where does this list come from? > while True: > data = tempfile.read(65536) > if data: > f.write(data) > else: > break This copies the content of each tempfile into bigfile.txt. > could i make the 'logfile.txt. a tempfile? I don't know. What do you mean by tempfile? > and could the f.write be changed to f.append? No, files do not have an append method. Open the file in append mode, then all writes will append to the end of the file. -- Steven From md123 at nycap.rr.com Fri Jun 28 16:10:15 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 28 Jun 2013 10:10:15 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CD92C9.6040303@pearwood.info> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> Message-ID: <51CD9947.3010907@nycap.rr.com> On 06/28/2013 09:42 AM, Steven D'Aprano wrote: > On 28/06/13 23:18, Matt D wrote: > >> what if i did some thing like this i saw on stackoverflow: >> >> f = open("bigfile.txt", "w") > > That clears any existing content of bigfile.txt, and opens it for > writing. Do you intend to clear the content? > > >> for tempfile in tempfiles: > > What is in tempfiles? A list of files opened for reading? Where does > this list come from? > > >> while True: >> data = tempfile.read(65536) >> if data: >> f.write(data) >> else: >> break > > This copies the content of each tempfile into bigfile.txt. > > >> could i make the 'logfile.txt. a tempfile? > > I don't know. What do you mean by tempfile? > > >> and could the f.write be changed to f.append? > > No, files do not have an append method. Open the file in append mode, > then all writes will append to the end of the file. > > just to be clear here. this how i open and the file for logging data: # open a file named "logfile.txt" in "a" append mode; self.logfile = open('logfile.txt', 'a') and i have a loop that writes 8 comma separated values in row with this: self.logfile.write('%s,'%(str(f)) currently this is how the user can open a file from the UI: #open file dialog ----------------------------- def openFile(self, evt): with wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.*", wx.OPEN) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() mypath = os.path.basename(path) #with open(mypath, "a") as f: but i havnt figured a way to get what is in the 'logfile.txt' into the file the user opens with the file dialog. so. . . i was looking at the documentation for tempfile, stuff like 'tempfile.TemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]])'. I was thinking that if i could have my program log data to a temp file (in place of 'logfile.txt') on each run and then the tempfile would be deleted. but before the tempfile was deleted on program stop, the contents of the tempfile could be appended into the file the user opened from the UI. So "bigfile.txt" would be the file the user opens with the file dialog, here it would be 'mypath'. and the 'logfile.txt' would be the temporary file, i would have to replace in my program 'logfile.txt' with 'tempfile'? Not sure if this doable and if so how i would go about writing this code. From cybervigilante at gmail.com Fri Jun 28 17:49:06 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 28 Jun 2013 08:49:06 -0700 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: <51CD1A6F.4000800@pearwood.info> References: <51CC324E.5000903@pearwood.info> <51CCD34B.2030002@davea.name> <51CD1A6F.4000800@pearwood.info> Message-ID: On 27 June 2013 22:09, Steven D'Aprano wrote: > I'm afraid that you've missed the point, sorry :-) If I didn't miss points I'd be teaching here instead of learning ;') Okay, it's now clear that doctests are heavier on the documentation-you're-going-to-forget-otherwise side, than the testing side. That's fine and a good idea But does that mean doctests stay in forever rather than as a test? The reason I ask is that most of the py programs I've seen, even in the py distributions, don't have doctests in them - so it doesn't appear to be a common practice. They have comments, which could easily become doctests, but use the hashmark. (Actually, I've decided to use triple quotes at the top of all functions anyway. Why not?) Jim -- "When I use a word," Humpty Dumpty said, in rather a scornful tone, "it means just what I choose it to mean- neither more nor less." "The question is," said Alice, "whether you can make words mean so many different things." "The question is," said Humpty Dumpty, "which is to be master-that's all." From cybervigilante at gmail.com Fri Jun 28 18:06:35 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 28 Jun 2013 09:06:35 -0700 Subject: [Tutor] multiple function returns In-Reply-To: <7872a015-f2bb-4e9d-8d26-75bde933e918@email.android.com> References: <7872a015-f2bb-4e9d-8d26-75bde933e918@email.android.com> Message-ID: >>>> def foo(x): > ... if x: > ... return True > ... return False > > I'll leave it to you to work out why that works. It's very handy! > Hey, it saves typing an "else" and as you know, I'm the Lazy Typist. My program to make dicts, lists, etc from a single string, using no special characters, has saved me so much little-finger typing already I'd never part with it, flawed as it is. It's good-enough ;') Jim From kwpolska at gmail.com Fri Jun 28 18:12:29 2013 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Fri, 28 Jun 2013 18:12:29 +0200 Subject: [Tutor] multiple function returns In-Reply-To: References: <7872a015-f2bb-4e9d-8d26-75bde933e918@email.android.com> Message-ID: On Fri, Jun 28, 2013 at 6:06 PM, Jim Mooney wrote: >>>>> def foo(x): >> ... if x: >> ... return True >> ... return False >> >> I'll leave it to you to work out why that works. It's very handy! >> > Hey, it saves typing an "else" and as you know, I'm the Lazy Typist. > My program to make dicts, lists, etc from a single string, using no > special characters, has saved me so much little-finger typing already > I'd never part with it, flawed as it is. It's good-enough ;') The Lazy Typist would actually do: def foo(x): return bool(x) Or even: foo = lambda x: bool(x) -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From s.shall at virginmedia.com Fri Jun 28 18:21:44 2013 From: s.shall at virginmedia.com (Sydney Shall) Date: Fri, 28 Jun 2013 18:21:44 +0200 Subject: [Tutor] multiple function returns In-Reply-To: References: <7872a015-f2bb-4e9d-8d26-75bde933e918@email.android.com> Message-ID: <51CDB818.6040406@virginmedia.com> On 28/06/2013 18:06, Jim Mooney wrote: >>>>> def foo(x): >> ... if x: >> ... return True >> ... return False Does one need the last line? > return False >> >> I'll leave it to you to work out why that works. It's very handy! >> > Hey, it saves typing an "else" and as you know, I'm the Lazy Typist. > My program to make dicts, lists, etc from a single string, using no > special characters, has saved me so much little-finger typing already > I'd never part with it, flawed as it is. It's good-enough ;') > > Jim > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Sydney Shall From breamoreboy at yahoo.co.uk Fri Jun 28 18:55:02 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Jun 2013 17:55:02 +0100 Subject: [Tutor] multiple function returns In-Reply-To: <51CDB818.6040406@virginmedia.com> References: <7872a015-f2bb-4e9d-8d26-75bde933e918@email.android.com> <51CDB818.6040406@virginmedia.com> Message-ID: On 28/06/2013 17:21, Sydney Shall wrote: > On 28/06/2013 18:06, Jim Mooney wrote: >>>>>> def foo(x): >>> ... if x: >>> ... return True >>> ... return False > Does one need the last line? > Yes otherwise the default of None is returned, although in this situation it might not make much difference. Then again explicit is better than implicit :) -- "Steve is going for the pink ball - and for those of you who are watching in black and white, the pink is next to the green." Snooker commentator 'Whispering' Ted Lowe. Mark Lawrence From __peter__ at web.de Fri Jun 28 19:09:22 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Jun 2013 19:09:22 +0200 Subject: [Tutor] mapping header row to data rows in file References: <87d2r8dgtr.fsf@gmail.com> <874nckck9y.fsf@gmail.com> Message-ID: Sivaram Neelakantan wrote: > I apologise for mailing you directly but this one seems to work but I > don't seem to understand it. Could you please explain this? [I don't see anything private about your questions, so I'm taking the liberty do bring this back on list] > a) for row in reader(f)... > reader(f) is called 6 times or not? No, the reader() function is called once before the first iteration of the loop. You can think of for x in expr(): ... as syntactic sugar for tmp = iter(expr()) while True: try: x = next(tmp) except StopIteration: break ... > b) why isn't the print in reader() not printing each row each time > reader() is called It is called just once. The function returns a "generator" built from the "generator expression" (Row(*values) for values in rows) which corresponds to the "tmp" variable in the long version of the for-loop above. A generator lazily produces one value when you call its next() method: >>> g = (i*i for i in [1, 2, 3]) >>> next(g) # same as g.next() in Python 2 or g.__next__() in Python 3 1 >>> next(g) 4 >>> next(g) 9 >>> next(g) Traceback (most recent call last): File "", line 1, in StopIteration There is an alternative way to create a generator that is perhaps easier to grasp: >>> def f(): ... for i in [1, 2, 3]: ... yield i*i ... >>> g = f() >>> next(g) 1 >>> next(g) 4 >>> next(g) 9 >>> next(g) Traceback (most recent call last): File "", line 1, in StopIteration On each next() call the code in f() is executed until it encounters a "yield". > c) what does Row(*values) do? It unpacks the values sequence. For example, if values is a list of length 3 like values = ["a", "b", "c"] then Row(*values) is equivalent to Row(values[0], values[1], values[2]) or Row("a", "b", "c") > > --8<---------------cut here---------------start------------->8--- > def reader(instream): > rows = csv.reader(instream) > # rows = (line.split(",") for line in instream) > rows = ([field.strip() for field in row] for row in rows) > print type(rows) > names = next(rows) > print names > Row = namedtuple("Row", names) > return (Row(*values) for values in rows) > > with open("AA.csv", "r") as f: > for row in reader(f): > print row > > $ python csvproc.py > > ['Symbol', 'Series', 'Date', 'Prev_Close'] > Row(Symbol='STER', Series='EQ', Date='22-Nov-2012', Prev_Close='9') > Row(Symbol='STER', Series='EQ', Date='29-Nov-2012', Prev_Close='10') > Row(Symbol='STER', Series='EQ', Date='06-Dec-2012', Prev_Close='11') > Row(Symbol='STER', Series='EQ', Date='06-Jun-2013', Prev_Close='9') > Row(Symbol='STER', Series='EQ', Date='07-Jun-2013', Prev_Close='9') From davea at davea.name Fri Jun 28 19:21:25 2013 From: davea at davea.name (Dave Angel) Date: Fri, 28 Jun 2013 13:21:25 -0400 Subject: [Tutor] multiple function returns In-Reply-To: References: <7872a015-f2bb-4e9d-8d26-75bde933e918@email.android.com> Message-ID: <51CDC615.2000303@davea.name> On 06/28/2013 12:06 PM, Jim Mooney wrote: >>>>> def foo(x): >> ... if x: >> ... return True >> ... return False >> >> I'll leave it to you to work out why that works. It's very handy! >> > Hey, it saves typing an "else" and as you know, I'm the Lazy Typist. > My program to make dicts, lists, etc from a single string, using no > special characters, has saved me so much little-finger typing already > I'd never part with it, flawed as it is. It's good-enough ;') > If one were trying to save keystrokes here, one would just use foo = bool and be done with it. Or at least, def foo(x): return bool(x) But saving keystrokes should seldom be the goal, unless you're dealing with a disability. In most cases, the comments and the testing code will be much bigger than the actual running code. -- DaveA From wayne at waynewerner.com Fri Jun 28 20:25:23 2013 From: wayne at waynewerner.com (Wayne Werner) Date: Fri, 28 Jun 2013 13:25:23 -0500 (CDT) Subject: [Tutor] multiple function returns In-Reply-To: <51CD7159.50507@pearwood.info> References: <51CD7159.50507@pearwood.info> Message-ID: On Fri, 28 Jun 2013, Steven D'Aprano wrote: > On 28/06/13 14:18, Jim Mooney wrote: >> What's the Pythonic standard on multiple returns from a function? It >> seems easiest to just return from the point where the function fails >> or succeeds, even it that's multiple points. Or is it considered best >> to defer everything to one return at the end? > > > The first. Python functions have one entry point, the top of the function. > They can have multiple exit points, anywhere you have a return statement. If you consider exceptions to be a function return, then every line has at *least* one return point ;) -Wayne From cybervigilante at gmail.com Fri Jun 28 20:51:56 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Fri, 28 Jun 2013 11:51:56 -0700 Subject: [Tutor] multiple function returns In-Reply-To: References: <7872a015-f2bb-4e9d-8d26-75bde933e918@email.android.com> Message-ID: On 28 June 2013 09:12, Chris ?Kwpolska? Warrick > Or even: > > foo = lambda x: bool(x) Now you'll make me learn what lambda is. Ah, it's like an anonymous function in jQuery, which I found very handy when I hacked around with it to get kewl stuff on to web pages. Although it looks a bit obfuscated for Python - I guess one could get Too lazy. ;') Jim From malaclypse2 at gmail.com Fri Jun 28 21:50:39 2013 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 28 Jun 2013 15:50:39 -0400 Subject: [Tutor] multiple function returns In-Reply-To: References: Message-ID: On Fri, Jun 28, 2013 at 12:18 AM, Jim Mooney wrote: > What's the Pythonic standard on multiple returns from a function? It > seems easiest to just return from the point where the function fails > or succeeds, even it that's multiple points. Or is it considered best > to defer everything to one return at the end? My personal preference depends on how big the function is. If the function is short enough to fit on one screen or so in my editor, then I just go ahead and return wherever it makes sense to do so -- in multiple places if that makes sense for the particular function. On the other hand, if the function is longer than that, I prefer to figure out my result along the way, then do a single return at the end of the function. For me, this practice helps to increase the maintainability of my code. Any function short enough to fit on one screen is usually short enough to fit in my mind all at once too, so the multiple returns don't get confusing. For longer functions, I can't always take in how the whole thing works in a single go, and having the single exit point at the end seems to help me when I trace through the code. Again, this is a personal preference. I know some teams prefer to have everything in either one style or the other for the sake of consistency. Experience is the only way for you to figure out what works best with your debugging style. -- Jerry From md123 at nycap.rr.com Fri Jun 28 21:54:48 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 28 Jun 2013 15:54:48 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CD92C9.6040303@pearwood.info> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> Message-ID: <51CDEA08.6060407@nycap.rr.com> On 06/28/2013 09:42 AM, Steven D'Aprano wrote: > On 28/06/13 23:18, Matt D wrote: > >> what if i did some thing like this i saw on stackoverflow: >> >> f = open("bigfile.txt", "w") > > That clears any existing content of bigfile.txt, and opens it for > writing. Do you intend to clear the content? > > >> for tempfile in tempfiles: > > What is in tempfiles? A list of files opened for reading? Where does > this list come from? > > >> while True: >> data = tempfile.read(65536) >> if data: >> f.write(data) >> else: >> break > > This copies the content of each tempfile into bigfile.txt. > > >> could i make the 'logfile.txt. a tempfile? > > I don't know. What do you mean by tempfile? > > >> and could the f.write be changed to f.append? > > No, files do not have an append method. Open the file in append mode, > then all writes will append to the end of the file. > > So what i tried was this: import tempfile #self.logfile = open('logfile.txt', 'a') self.logfile = tempfile.NamedTemporaryFile() obviously i commented out the old way i opened the log file. my idea is that the new temporary self.logfile will behave exactly as the old self.logfile. then to get the temporary self.logfile into the file the user chooses i decided to try this: #open file dialog ----------------------------- def openFile(self, evt): with wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.txt*", wx.SAVE) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() mypath = os.path.basename(path) with open(mypath, "a") as f: f.write(self.logfile) self.logfile.close() my idea was that everytime the user clicked the button the temporary self.logfile would be writen to to 'f' and then self.logfile would be destroyed. sense 'f' is opened in append; and the self.logfile is destroyed after each push of the button, then every time the button is pushed only new data will be appended to file the user chooses. But its not working. nothing gets put in the user opened file 'f'?? What am I missing or is the approach totally wrong? Thanks! From alan.gauld at btinternet.com Fri Jun 28 22:31:25 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Jun 2013 21:31:25 +0100 Subject: [Tutor] multiple function returns In-Reply-To: References: <7872a015-f2bb-4e9d-8d26-75bde933e918@email.android.com> Message-ID: On 28/06/13 19:51, Jim Mooney wrote: > Now you'll make me learn what lambda is. > > Ah, it's like an anonymous function in jQuery, That's the idea but Python lambdas are a bit crippled so its really an anonymous expression... :-( But if you know JQuery then lambdas should be easy to pick up. And they are really useful in GUI and Functional programming contexts. In summary: foo = lambda : return is equivalent to def foo(paramList): return expression HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jun 28 22:43:16 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 28 Jun 2013 21:43:16 +0100 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CDEA08.6060407@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> Message-ID: On 28/06/13 20:54, Matt D wrote: > def openFile(self, evt): > with wx.FileDialog(self, "Choose a file", os.getcwd(), "", > "*.txt*", wx.SAVE) as dlg: > if dlg.ShowModal() == wx.ID_OK: > path = dlg.GetPath() > mypath = os.path.basename(path) > with open(mypath, "a") as f: > f.write(self.logfile) > self.logfile.close() It's not clear what state self.logfile is in but assuming you have been writing to it the cursor will be at the end of the file so you can't write anything from it. You would need to do a seek(0) first. But f.write(self.logfile) will not write the contents of logfile. You will need to read that first so I think you need: with open(mypath, "a") as f: self.logfile.seek(0) # go to beginning of the file f.write(self.logfile.read()) # write the contents self.logfile.close() # close but do not delete But I must say this seems like an inordinately complicated way of doing things and quite out of the norm for other applications. Can you back up several steps and explain again what exactly you are trying to achieve? What is the user experience supposed to be? What is being recorded where and why? How does a user interact with it? Logging is such a well established process for most applications that one of a very few patterns are usually followed. You seem to be trying to invent a whole new paradigm here? (And that may not be a bad thing, but we should at least understand why it's needed!) hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wayne at waynewerner.com Fri Jun 28 23:05:54 2013 From: wayne at waynewerner.com (Wayne Werner) Date: Fri, 28 Jun 2013 16:05:54 -0500 (CDT) Subject: [Tutor] Need help appending data to a logfile In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> Message-ID: On Fri, 28 Jun 2013, Alan Gauld wrote: > On 28/06/13 20:54, Matt D wrote: > >> def openFile(self, evt): >> with wx.FileDialog(self, "Choose a file", os.getcwd(), "", >> "*.txt*", wx.SAVE) as dlg: >> if dlg.ShowModal() == wx.ID_OK: >> path = dlg.GetPath() >> mypath = os.path.basename(path) >> with open(mypath, "a") as f: >> f.write(self.logfile) >> self.logfile.close() > > > But I must say this seems like an inordinately complicated way > of doing things and quite out of the norm for other applications. > Can you back up several steps and explain again what exactly you > are trying to achieve? What is the user experience supposed to > be? What is being recorded where and why? How does a user > interact with it? > > Logging is such a well established process for most applications that > one of a very few patterns are usually followed. You seem to be > trying to invent a whole new paradigm here? (And that may not be > a bad thing, but we should at least understand why it's needed!) Especially when the Python standard library has an extremely powerful logging module. Or logbook. -W From md123 at nycap.rr.com Fri Jun 28 23:25:18 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 28 Jun 2013 17:25:18 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> Message-ID: <51CDFF3E.8030308@nycap.rr.com> > But I must say this seems like an inordinately complicated way > of doing things and quite out of the norm for other applications. > Can you back up several steps and explain again what exactly you > are trying to achieve? What is the user experience supposed to > be? What is being recorded where and why? How does a user > interact with it? > > Logging is such a well established process for most applications that > one of a very few patterns are usually followed. You seem to be > trying to invent a whole new paradigm here? (And that may not be > a bad thing, but we should at least understand why it's needed!) > Sure. so to to be perfectly clear here, about what i am doing and what i where i want to get to. currently i have a little code that logs (I say logging but its not the debugging thing) data that gets sent to the Python UI. I have a thread that waits on new data and when it comes in it gets displayed in TextCtrl fields. every time this happens my logger puts those values into a text file one row at a time. this how i open and the file for logging data: # open a file named "logfile.txt" in "a" append mode; self.logfile = open('logfile.txt', 'a') and i have a loop that writes 8 comma separated values in row with this: self.logfile.write('%s,'%(str(f)) however, using this setup the user cannot select the file to save the log to, it just gets written into the home folder. so i came up with this is to allow the user can open a file from the UI: #open file dialog ----------------------------- def openFile(self, evt): with wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.*", wx.OPEN) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() mypath = os.path.basename(path) #with open(mypath, "a") as f: but i hadn't figured a way to get what is in the 'logfile.txt' into the file the user opens with the file dialog. so i was trying this: import tempfile self.logfile = tempfile.NamedTemporaryFile() to open the tempfile hoping it would behave exactly as the old 'self.logfile' did in terms of getting the data written to it. And i tried what you already saw to get the contents of the temporary file 'self.logfile' copied or written into the file the user opens from the UI. Now I am testing your suggestion: def openFile(self, evt): with wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.txt*", wx.SAVE) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() mypath = os.path.basename(path) with open(mypath, "a") as f: self.logfile.seek(0)#start at beginning f.write(self.logfile.read()) self.logfile.close() i am trying to allow the user to open a file and then have whats in the temp logfile written into the file the user selected from the file dialog. or appended actually. and then obviously the tempfile is closed which i was under the impression would destroy the file automatically and free up the memory. I have been trying for a while to find some standard why of achieving this functionality but have been unable to find any examples. Thanks! From md123 at nycap.rr.com Sat Jun 29 00:02:44 2013 From: md123 at nycap.rr.com (Matt D) Date: Fri, 28 Jun 2013 18:02:44 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> Message-ID: <51CE0804.40500@nycap.rr.com> > > Especially when the Python standard library has an extremely powerful > logging module. Or logbook. > how would i use the logging module to get strings that are displayed in text cntrl fields into a text file. one time/date stamped row of 7 values at a time? i was under the impression that the logging module is a debugging thing? From alan.gauld at btinternet.com Sat Jun 29 02:04:53 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Jun 2013 01:04:53 +0100 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CDFF3E.8030308@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> <51CDFF3E.8030308@nycap.rr.com> Message-ID: On 28/06/13 22:25, Matt D wrote: > Python UI. I have a thread that waits on new data and when it comes in > it gets displayed in TextCtrl fields. every time this happens my logger > puts those values into a text file one row at a time. > > this how i open and the file for logging data: > > # open a file named > "logfile.txt" in "a" append mode; > self.logfile = open('logfile.txt', 'a') What I don't understand is why you are using a hard coded filename? Why not use the user generated filename here when you first open the file? You can either set it as part of user preferences in a config file or prompt the user if one hasn't been set or use a default value if they don't set it. But however it gets set it shouldn't need to be hard coded. > and i have a loop that writes 8 comma separated values in row with this: > > self.logfile.write('%s,'%(str(f)) It might be better to build the string and then write it out once to the file. But that's a minor matter. > however, using this setup the user cannot select the file to save the > log to, it just gets written into the home folder. so i came up with > this is to allow the user can open a file from the UI: > > #open file dialog ----------------------------- > def openFile(self, evt): > with wx.FileDialog(self, "Choose a file", os.getcwd(), "", > "*.*", wx.OPEN) as dlg: > if dlg.ShowModal() == wx.ID_OK: > path = dlg.GetPath() > mypath = os.path.basename(path) > #with open(mypath, "a") as f: > > but i hadn't figured a way to get what is in the 'logfile.txt' into the > file the user opens with the file dialog. so i was trying this: OK, There is nothing special about that its just copying data into a new file. The bit I don't understand is why continue to log the data in the hardcoded name? Why not change the name of the log file? If need be you can copy any existing logfile(or rename it) into the user supplied name but then all new log entries go to the new file. Its this strange business of maintaining two files I don't understand. > ...the tempfile is closed > which i was under the impression would destroy the file automatically > and free up the memory. It destroys the file object in memory but that does nothing to the file on disk. After all if you closed a file in your editor you wouldn't expect it to be deleted from your hard drive! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at davea.name Sat Jun 29 02:15:11 2013 From: davea at davea.name (Dave Angel) Date: Fri, 28 Jun 2013 20:15:11 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> <51CDFF3E.8030308@nycap.rr.com> Message-ID: <51CE270F.2050302@davea.name> On 06/28/2013 08:04 PM, Alan Gauld wrote: > On 28/06/13 22:25, Matt D wrote: > >> Python UI. I have a thread that waits on new data and when it comes in >> it gets displayed in TextCtrl fields. every time this happens my logger >> puts those values into a text file one row at a time. >> >> this how i open and the file for logging data: >> >> # open a file named >> "logfile.txt" in "a" append mode; >> self.logfile = open('logfile.txt', 'a') > > What I don't understand is why you are using a hard coded filename? > Why not use the user generated filename here when you first open the > file? You can either set it as part of user preferences in a config file > or prompt the user if one hasn't been set or use a default value if they > don't set it. But however it gets set it shouldn't need to > be hard coded. > >> and i have a loop that writes 8 comma separated values in row with this: >> >> self.logfile.write('%s,'%(str(f)) > > It might be better to build the string and then write it out once to the > file. But that's a minor matter. > >> however, using this setup the user cannot select the file to save the >> log to, it just gets written into the home folder. so i came up with >> this is to allow the user can open a file from the UI: >> >> #open file dialog ----------------------------- >> def openFile(self, evt): >> with wx.FileDialog(self, "Choose a file", os.getcwd(), "", >> "*.*", wx.OPEN) as dlg: >> if dlg.ShowModal() == wx.ID_OK: >> path = dlg.GetPath() >> mypath = os.path.basename(path) >> #with open(mypath, "a") as f: >> >> but i hadn't figured a way to get what is in the 'logfile.txt' into the >> file the user opens with the file dialog. so i was trying this: > > OK, There is nothing special about that its just copying data into a new > file. The bit I don't understand is why continue to log the data in the > hardcoded name? Why not change the name of the log file? If need be you > can copy any existing logfile(or rename it) into the user supplied name > but then all new log entries go to the new file. > > Its this strange business of maintaining two files I don't understand. > >> ...the tempfile is closed >> which i was under the impression would destroy the file automatically >> and free up the memory. > > It destroys the file object in memory but that does nothing > to the file on disk. > > After all if you closed a file in your editor you wouldn't > expect it to be deleted from your hard drive! > Matt probably read somewhere about an interface like tempfile.TemporaryFile where the file has no explicit name, and will be deleted from disk, and the space reused as soon as it is closed. I don't believe he's using such an interface, however. -- DaveA From kbailey at howlermonkey.net Sat Jun 29 06:32:00 2013 From: kbailey at howlermonkey.net (Kirk Bailey) Date: Sat, 29 Jun 2013 00:32:00 -0400 Subject: [Tutor] Robot Radio in a linux Raspberry Pi Message-ID: <51CE6340.5010704@howlermonkey.net> ok, some months back I wrote about the program I wrote to perform the office of being a robot radio station in my windows desktop PC. well, I got it done and posted the program FOR WINDOWS on this list, and shut up. Then I got interested in the Raspberry Pi, which has adopted python as it's language of preference. And I soon not to thinking that this little wonder with a st of amplified speakers and a 16Gb SD card in an old cabinet would be hell on small dogs as a old time radio recreation. So now i am starting to meddle with what already works, and convert it to Raspbian Linux for installation in a Raspberry Pi. there is a nice command line program called mpg123 that plays mp3 files easy pasy, but mayhaps someone knows of another way that is a touch simpler to invoke from inside a python script? natch, I could do it from an sh script.. but that's not python, is it? Anyone who wants to stick an oar in this water, wade in to the thread. -- -Shaboom. Kirk Bailey CEO, Freehold Marketing LLC http://www.OneBuckHosting.com/ Fnord! From davea at davea.name Sat Jun 29 13:55:22 2013 From: davea at davea.name (Dave Angel) Date: Sat, 29 Jun 2013 07:55:22 -0400 Subject: [Tutor] Robot Radio in a linux Raspberry Pi In-Reply-To: <51CE6340.5010704@howlermonkey.net> References: <51CE6340.5010704@howlermonkey.net> Message-ID: <51CECB2A.4020206@davea.name> On 06/29/2013 12:32 AM, Kirk Bailey wrote: > ok, some months back I wrote about the program I wrote to perform the > office of being a robot radio station in my windows desktop PC. well, I > got it done and posted the program FOR WINDOWS on this list, and shut up. > > Then I got interested in the Raspberry Pi, which has adopted python as > it's language of preference. And I soon not to thinking that this little > wonder with a st of amplified speakers and a 16Gb SD card in an old > cabinet would be hell on small dogs as a old time radio recreation. > > So now i am starting to meddle with what already works, and convert it > to Raspbian Linux for installation in a Raspberry Pi. there is a nice > command line program called mpg123 that plays mp3 files easy pasy, but > mayhaps someone knows of another way that is a touch simpler to invoke > from inside a python script? natch, I could do it from an sh script.. > but that's not python, is it? > > Anyone who wants to stick an oar in this water, wade in to the thread. > I've not used Raspberry Pi, but look into the following links. http://pymedia.org/tut/ http://www.filetransit.com/freeware.php?name=Python_Library -- DaveA From md123 at nycap.rr.com Sat Jun 29 14:26:02 2013 From: md123 at nycap.rr.com (Matt D) Date: Sat, 29 Jun 2013 08:26:02 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CE270F.2050302@davea.name> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> <51CDFF3E.8030308@nycap.rr.com> <51CE270F.2050302@davea.name> Message-ID: <51CED25A.9070807@nycap.rr.com> >> > > Matt probably read somewhere about an interface like > > tempfile.TemporaryFile > > where the file has no explicit name, and will be deleted from disk, and > the space reused as soon as it is closed. > > I don't believe he's using such an interface, however. > Yes that is what i was using. with tempfile.NamedTemporaryFile('a+t',) as tf: self.logfile = tf or what i have now: self.f = tempfile.NamedTemporaryFile() 'f' is the file the user opens but it has to be named up by the main class constructor or the program gives this error: ValueError: I/O operation on closed file so i cant just pass the 'f' from the file dialog into the loop that writes the data i need. at least i have been unable to find a way to do this. From davea at davea.name Sat Jun 29 15:15:35 2013 From: davea at davea.name (Dave Angel) Date: Sat, 29 Jun 2013 09:15:35 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CED25A.9070807@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> <51CDFF3E.8030308@nycap.rr.com> <51CE270F.2050302@davea.name> <51CED25A.9070807@nycap.rr.com> Message-ID: <51CEDDF7.60107@davea.name> On 06/29/2013 08:26 AM, Matt D wrote: > >>> >> >> Matt probably read somewhere about an interface like >> >> tempfile.TemporaryFile >> >> where the file has no explicit name, and will be deleted from disk, and >> the space reused as soon as it is closed. >> >> I don't believe he's using such an interface, however. >> > Yes that is what i was using. > > with tempfile.NamedTemporaryFile('a+t',) as tf: > self.logfile = tf > > or what i have now: > > self.f = tempfile.NamedTemporaryFile() > > 'f' is the file the user opens but it has to be named up by the main > class constructor or the program gives this error: > > ValueError: I/O operation on closed file > > so i cant just pass the 'f' from the file dialog into the loop that > writes the data i need. at least i have been unable to find a way to do > this. > Look at the keyword arguments to NamedTemporaryFile(), and see if you can guess which one you can pass to tell it NOT to delete itself. Or much better, figure out why you're getting that ValueError exception. Does your file dialog automatically create the file, and only give you the open handle? Or can it be told to return a name string, which you'll use where you need it? Passing an open file handle around in an event-driven system is problematic. Especially using the with-statement semantics. -- DaveA From md123 at nycap.rr.com Sat Jun 29 17:00:52 2013 From: md123 at nycap.rr.com (Matt D) Date: Sat, 29 Jun 2013 11:00:52 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CEDDF7.60107@davea.name> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> <51CDFF3E.8030308@nycap.rr.com> <51CE270F.2050302@davea.name> <51CED25A.9070807@nycap.rr.com> <51CEDDF7.60107@davea.name> Message-ID: <51CEF6A4.9060901@nycap.rr.com> On 06/29/2013 09:15 AM, Dave Angel wrote: > On 06/29/2013 08:26 AM, Matt D wrote: >> >>>> >>> >>> Matt probably read somewhere about an interface like >>> >>> tempfile.TemporaryFile >>> >>> where the file has no explicit name, and will be deleted from disk, and >>> the space reused as soon as it is closed. >>> >>> I don't believe he's using such an interface, however. >>> >> Yes that is what i was using. >> >> with tempfile.NamedTemporaryFile('a+t',) as tf: >> self.logfile = tf >> >> or what i have now: >> >> self.f = tempfile.NamedTemporaryFile() >> >> 'f' is the file the user opens but it has to be named up by the main >> class constructor or the program gives this error: >> >> ValueError: I/O operation on closed file >> >> so i cant just pass the 'f' from the file dialog into the loop that >> writes the data i need. at least i have been unable to find a way to do >> this. >> > > Look at the keyword arguments to NamedTemporaryFile(), and see if you > can guess which one you can pass to tell it NOT to delete itself. > > Or much better, figure out why you're getting that ValueError exception. > Does your file dialog automatically create the file, and only give you > the open handle? Or can it be told to return a name string, which > you'll use where you need it? > > Passing an open file handle around in an event-driven system is > problematic. Especially using the with-statement semantics. > So i should tell it NOT to delete itself? i was under the impression that having it delete itself upon program close is a good thing. i thought the point of not using variables for this sort of thing is to save memory space. there will be a time when this program is left running for days if not weeks. the value error is from trying to write to a file that is not open. apparently the file dialog is not opening the file in way that i can use like that. having the file dialog be able to return the file name that the user opens and having that file available to the loop that writes the data would be ideal. trying to figure a way to do this has been the source of my frustration for a long time now. From alan.gauld at btinternet.com Sun Jun 30 02:51:55 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Jun 2013 01:51:55 +0100 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CEF6A4.9060901@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> <51CDFF3E.8030308@nycap.rr.com> <51CE270F.2050302@davea.name> <51CED25A.9070807@nycap.rr.com> <51CEDDF7.60107@davea.name> <51CEF6A4.9060901@nycap.rr.com> Message-ID: On 29/06/13 16:00, Matt D wrote: >>> with tempfile.NamedTemporaryFile('a+t',) as tf: >>> self.logfile = tf This could give problems. with guarantees to close the file at the end of the block. But you have assigned it to self.logfile. So when the file is closed (and tempfile then deletes the file on disk) your self.logfile points at... nothing?! If you are going to assign to self.logfile I'd probably recommend not using 'with' since in this case you want the file to hang around after the 'with' block ends. >>> or what i have now: >>> >>> self.f = tempfile.NamedTemporaryFile() But this is totally different since it needs an explicit close. >>> 'f' is the file the user opens but it has to be named up by the main >>> class constructor or the program gives this error: >>> >>> ValueError: I/O operation on closed file I have no idea what that means. You don;t pass in a name from the user? I'm not sure what you mean by the "main class constructor" And I can't really know what the error is saying without a full stacktrace. > So i should tell it NOT to delete itself? i was under the impression > that having it delete itself upon program close is a good thing. It usually is but I understood it was on FILE close not PROGRAM close. Very different things... > thought the point of not using variables for this sort of thing is to > save memory space. variables in Python are just names so take up very little memory. But the objects in memory that they refer to can be very big. But a file object is not big even when the file on disk is huge. So storing the log data in a file is sensible but you still want variables to point to the file object. And that object needs to be open for you to write to it. > the value error is from trying to write to a file that is not open. > apparently the file dialog is not opening the file in way that i can use > like that. Or maybe its getting closed again immediately? > having the file dialog be able to return the file name that > the user opens and having that file available to the loop that writes > the data would be ideal. That is the usual way of doing it. Just store the filename and use it to open the logfile as needed for writing. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From phil_lor at bigpond.com Sun Jun 30 00:36:31 2013 From: phil_lor at bigpond.com (Phil) Date: Sun, 30 Jun 2013 08:36:31 +1000 Subject: [Tutor] Self and class functions Message-ID: <51CF616F.8060300@bigpond.com> Thank you for reading this. I'm attempting to access the GUI widgets. The buttonClicked slot does what I want but I'd like to access the widgets outside of the class. My function setLabel doesn't work because self and ui are not known. I have a second class named Frame that includes a function named dummy. Accessing that function is not a problem. ------------------------------------- from mainwindow import Ui_MainWindow from PySide import QtCore, QtGui from frame import Frame class DrawTest(QtGui.QMainWindow): def __init__(self, parent=None): super(DrawTest, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) def buttonClicked(self): print("clicked") self.ui.pushButton.setText("test") self.ui.label.setText("Testing") def setLabel(self): self.ui.label.setText("Bingo") DrawTest.setLabel(self) DrawTest.ui.label.setText("Bingo") The two lines above don't work, so my question is how do access the setText function? And, what do I do about the self parameter in the setLabel function? Accessing the Frame class is not a problem. Frame.dummy() I have spent the better part of a day searching the Internet for an answer and I have attempted to find an answer from two other mailing lists but they don't entertain low level questions. -- Regards, Phil From steve at pearwood.info Sun Jun 30 03:38:04 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 30 Jun 2013 11:38:04 +1000 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> <51CDFF3E.8030308@nycap.rr.com> <51CE270F.2050302@davea.name> <51CED25A.9070807@nycap.rr.com> <51CEDDF7.60107@davea.name> <51CEF6A4.9060901@nycap.rr.com> Message-ID: <51CF8BFC.2090608@pearwood.info> On 30/06/13 10:51, Alan Gauld wrote: > On 29/06/13 16:00, Matt D wrote: >>>> with tempfile.NamedTemporaryFile('a+t',) as tf: >>>> self.logfile = tf > > This could give problems. > > with guarantees to close the file at the end of the block. > But you have assigned it to self.logfile. > So when the file is closed (and tempfile then deletes the > file on disk) your self.logfile points at... nothing?! No, it points to a closed file object, which is perfectly legal. And in fact, so does tf. py> with tempfile.NamedTemporaryFile('a+t',) as tf: ... pass ... py> tf ', mode 'a+t' at 0xb7f9cd30> A file object is just a bunch of data such as file name, file mode, pointer to a file, etc. When you close the file, the pointer becomes invalid but the rest of the file object doesn't disappear, it just gets flagged as "closed". >>>> ValueError: I/O operation on closed file > > I have no idea what that means. It means that Matt is trying to do something input/output related on a closed file that can only be done on an open file, like write to it. I haven't read this entire thread, but the bits I have read lead me to think that Matt has tangled himself up in a total confused mess. It's *not this hard* to write status messages to a log file, the log module does all the work. Can anyone who has read the thread summarise what Matt is attempting to do? -- Steven From davea at davea.name Sun Jun 30 03:41:38 2013 From: davea at davea.name (Dave Angel) Date: Sat, 29 Jun 2013 21:41:38 -0400 Subject: [Tutor] Self and class functions In-Reply-To: <51CF616F.8060300@bigpond.com> References: <51CF616F.8060300@bigpond.com> Message-ID: <51CF8CD2.50509@davea.name> On 06/29/2013 06:36 PM, Phil wrote: > Thank you for reading this. You should be telling us some things. I'll guess for you: You're using Python 3.3 with Qt for a gui, and Linux 12.04 for an OS. > > I'm attempting to access the GUI widgets. The buttonClicked slot does > what I want but I'd like to access the widgets outside of the class. My > function setLabel doesn't work because self and ui are not known. > > I have a second class named Frame that includes a function named dummy. > Accessing that function is not a problem. The function is called a method if it's actually part of a class. You don't show us the code for that class and method. But according to the call below, the method must be a staticmethod or equivalent. Perhaps like the following: class Frame: @staticmethod def dummy(): return 42 Static methods are strange because they have no self or cls arguments. In other words, they're just ordinary functions which happen to be defined inside a class. So it's in a different namespace, but has no special arguments. The other "strange" method is a classmethod, which takes a cls (class) parameter instead of a self parameter. The methods below are ordinary methods, and thus need a self parameter. Normally that's obtained by creating an instance of the class. > > ------------------------------------- > > from mainwindow import Ui_MainWindow > from PySide import QtCore, QtGui > from frame import Frame > > class DrawTest(QtGui.QMainWindow): > def __init__(self, parent=None): > super(DrawTest, self).__init__(parent) > > self.ui = Ui_MainWindow() > self.ui.setupUi(self) > > def buttonClicked(self): > print("clicked") > self.ui.pushButton.setText("test") > self.ui.label.setText("Testing") > > def setLabel(self): > self.ui.label.setText("Bingo") > > DrawTest.setLabel(self) > DrawTest.ui.label.setText("Bingo") > > The two lines above don't work, You generally should specify in what way they don't work. In your case they don't work because 'self' is unbound in top-level code. You could use self if you were already inside a method of the same class and were calling a different one. > so my question is how do access the > setText function? And, what do I do about the self parameter in the > setLabel function? > Normally, you create an instance of the class. For example, you might do: mywindow = DrawTest(parent) Then, now you have the object, you can call the method: mywindow.setLabel() I have no idea about ui.label, I don't know QT. > Accessing the Frame class is not a problem. > > Frame.dummy() > > I have spent the better part of a day searching the Internet for an > answer and I have attempted to find an answer from two other mailing > lists but they don't entertain low level questions. > You need to play with classes using a simple Python tutorial, before you try to even understand a GUI. -- DaveA From chigga101 at gmail.com Sun Jun 30 03:47:25 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 30 Jun 2013 02:47:25 +0100 Subject: [Tutor] Self and class functions In-Reply-To: <51CF616F.8060300@bigpond.com> References: <51CF616F.8060300@bigpond.com> Message-ID: On Sat, Jun 29, 2013 at 11:36 PM, Phil wrote: > def setLabel(self): > self.ui.label.setText("Bingo") > > DrawTest.setLabel(self) > DrawTest.ui.label.setText("Bingo") > > The two lines above don't work, so my question is how do access the setText > function? And, what do I do about the self parameter in the setLabel > function? u need to create an instance. those 2 above lines do the same thing it seems From davea at davea.name Sun Jun 30 03:56:13 2013 From: davea at davea.name (Dave Angel) Date: Sat, 29 Jun 2013 21:56:13 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CF8BFC.2090608@pearwood.info> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> <51CDFF3E.8030308@nycap.rr.com> <51CE270F.2050302@davea.name> <51CED25A.9070807@nycap.rr.com> <51CEDDF7.60107@davea.name> <51CEF6A4.9060901@nycap.rr.com> <51CF8BFC.2090608@pearwood.info> Message-ID: <51CF903D.6040900@davea.name> On 06/29/2013 09:38 PM, Steven D'Aprano wrote: > > I haven't read this entire thread, but the bits I have read lead me to > think that Matt has tangled himself up in a total confused mess. It's > *not this hard* to write status messages to a log file, the log module > does all the work. Can anyone who has read the thread summarise what > Matt is attempting to do? > I've been trying to follow the whole thread, and some others before it. But the rules/goals keep changing, and I can't summarize it in any way that seems rational. There are at least 5 files in this system, some temporary, some growing, some with pickle stuff. And none of them is a log file. So I've been answering individual issues instead. -- DaveA From steve at pearwood.info Sun Jun 30 04:04:34 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 30 Jun 2013 12:04:34 +1000 Subject: [Tutor] Self and class functions In-Reply-To: <51CF616F.8060300@bigpond.com> References: <51CF616F.8060300@bigpond.com> Message-ID: <51CF9232.9000301@pearwood.info> On 30/06/13 08:36, Phil wrote: > Thank you for reading this. > > I'm attempting to access the GUI widgets. The buttonClicked slot does what I want but I'd like to access the widgets outside of the class. My function setLabel doesn't work because self and ui are not known. What does "doesn't work" mean? - when you call setLabel, the computer has a Blue Screen Of Death and crashes; - you get a dialog box on the screen with the error message "The application 'Python' experienced an unexpected problem and must exit"; - the computer locks up and stops responding until you turn the power off and on; - the application just closes without warning; - you get a Python stacktrace, starting with the line "Traceback (most recent call last)" and ending with a error message; - no error is shown, but the label you are trying to set doesn't change; - your printer suddenly starts printing dozens of pages with the letter "a" in the top left corner; - something else? Only you know for sure what "doesn't work" means in this context, so you need to tell us. Please keep that in mind for any future questions. However, in this case I can *guess* what is happening from context, hopefully correctly, so I'll try to answer. See below. > from mainwindow import Ui_MainWindow > from PySide import QtCore, QtGui > from frame import Frame > > class DrawTest(QtGui.QMainWindow): > def __init__(self, parent=None): > super(DrawTest, self).__init__(parent) > self.ui = Ui_MainWindow() > self.ui.setupUi(self) > > def buttonClicked(self): > print("clicked") > self.ui.pushButton.setText("test") > self.ui.label.setText("Testing") > > def setLabel(self): > self.ui.label.setText("Bingo") > > DrawTest.setLabel(self) > DrawTest.ui.label.setText("Bingo") > > The two lines above don't work, so my question is how do access the setText function? And, what do I do about the self parameter in the setLabel function? You have created a class called DrawTest, but generally speaking you don't operate on the class directly. First you have to create a specific instance of the class. By analogy, you don't take the general class of "dogs" for a walk in the park, you take a specific dog, say, Rover, for a walk. So in this case, you will need something like draw_win = DrawTest() # you may need to provide a parent window? draw_win.setLabel() I don't know enough about QT to tell you whether DrawTest can be a standalone window, or whether it needs a parent. If the above doesn't work, don't make us guess what error you get, copy and paste the complete Python traceback and show us. -- Steven From md123 at nycap.rr.com Sun Jun 30 05:41:54 2013 From: md123 at nycap.rr.com (Matt D) Date: Sat, 29 Jun 2013 23:41:54 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CF8BFC.2090608@pearwood.info> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> <51CDFF3E.8030308@nycap.rr.com> <51CE270F.2050302@davea.name> <51CED25A.9070807@nycap.rr.com> <51CEDDF7.60107@davea.name> <51CEF6A4.9060901@nycap.rr.com> <51CF8BFC.2090608@pearwood.info> Message-ID: <51CFA902.4090509@nycap.rr.com> > I haven't read this entire thread, but the bits I have read lead me to > think that Matt has tangled himself up in a total confused mess. It's > *not this hard* to write status messages to a log file, the log module > does all the work. Can anyone who has read the thread summarise what > Matt is attempting to do? > Sure np. So i have a program that gets pickled data from a thread and displays the data (9 strings) in TextCtrl fields in the UI. When the pickle is received it is processed like this: def display_data(self,event): message = event.data pickled_dict = message.to_string() attrs = pickle.loads(pickled_dict) self.update(attrs) attrs is passed into the update function: def update(self, field_values): # logger code---------- self.logfile.write('\n') self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", localtime())))) for k,v in self.fields.items(): f = field_values.get(k, None) if f: self.logfile.write('%s,'%(str(f))) #end logger code ---------------- This loop writes to the text file so it is formatted like this: time,val1,val2,va3,val4,val5,val6,val7,val8,val9, time,val1,val2,va3,val4,val5,val6,val7,val8,val9, time,val1,val2,va3,val4,val5,val6,val7,val8,val9, so i have the logfile.txt formatted in a was that is very useful for later inspection with time series analysis. I just read the logging module doc including the tutorials and the cookbook, and i have not seen a way to, in less than 6 lines, create a log file formatted as shown above. up near the main class constructor the log file is opened like this: self.logfile = open('logfile.txt', 'a') it is stored in the home folder and gets appended every time the program is run. Only problem is i need multiple log files and the user needs to be able to choose the file from the UI. So I put a button on the UI that and 'binded' to this: def openFile(self, evt): with wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.txt*", wx.OPEN) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() mypath = os.path.basename(path) uf = open(mypath, "a") uf.write(self.logfile) I have been unable to get the logfile.txt written into the user opened file. That is the short version of whats going on in this thread. most of the posts that were seemingly off topic were dead end attempts to allow the user to choose what file the information in 'logfile.txt' gets appended. Thanks! From phil_lor at bigpond.com Sun Jun 30 06:10:07 2013 From: phil_lor at bigpond.com (Phil) Date: Sun, 30 Jun 2013 14:10:07 +1000 Subject: [Tutor] Self and class functions In-Reply-To: <51CF8CD2.50509@davea.name> References: <51CF616F.8060300@bigpond.com> <51CF8CD2.50509@davea.name> Message-ID: <51CFAF9F.8090603@bigpond.com> On 30/06/13 11:41, Dave Angel wrote: Thank you Dave, Matthew and Steven for taking the time to reply. All hints are greatly appreciated. >> I'm attempting to access the GUI widgets. The buttonClicked slot does >> what I want but I'd like to access the widgets outside of the class. My >> function setLabel doesn't work because self and ui are not known. >> Perhaps my "doesn't work" statement was a bit cryptic. The error message read "name self is not defined" and the same for ui. I have attempted to create an instance of the DrawTest class although I had not tried DrawTest(parent) and in this case the error message is once again: Traceback (most recent call last): File "/home/phil/Python/Qt_draw_sub/draw_test.py", line 52, in draw = DrawTest(parent) NameError: name 'parent' is not defined >> I have a second class named Frame that includes a function named dummy. >> Accessing that function is not a problem. Creating an instance of the Frame class is not a problem, although accessing it's attributes without a function call is causing me to scratch my head. This is not possible under C++ unless the classes are friends but I thought that I'd read somewhere that, under Python, attributes are accessible directly. Anyway, this is a side issue and I only included that in my previous call for help to show that I understand the need to create an instance of the class. > > The function is called a method if it's actually part of a class. > > You don't show us the code for that class and method. But according to > the call below, the method must be a staticmethod or equivalent. Perhaps > like the following: > > class Frame: > @staticmethod > def dummy(): > return 42 > Yes, much like that. > Static methods are strange because they have no self or cls arguments. > In other words, they're just ordinary functions which happen to be > defined inside a class. So it's in a different namespace, but has no > special arguments. > > The other "strange" method is a classmethod, which takes a cls (class) > parameter instead of a self parameter. > > The methods below are ordinary methods, and thus need a self parameter. > Normally that's obtained by creating an instance of the class. > > >> >> ------------------------------------- >> >> from mainwindow import Ui_MainWindow >> from PySide import QtCore, QtGui >> from frame import Frame >> >> class DrawTest(QtGui.QMainWindow): >> def __init__(self, parent=None): >> super(DrawTest, self).__init__(parent) >> >> self.ui = Ui_MainWindow() >> self.ui.setupUi(self) >> >> def buttonClicked(self): >> print("clicked") >> self.ui.pushButton.setText("test") >> self.ui.label.setText("Testing") >> >> def setLabel(self): >> self.ui.label.setText("Bingo") >> >> DrawTest.setLabel(self) >> DrawTest.ui.label.setText("Bingo") >> >> The two lines above don't work, > > You generally should specify in what way they don't work. In your case > they don't work because 'self' is unbound in top-level code. You could > use self if you were already inside a method of the same class and were > calling a different one. > >> so my question is how do access the >> setText function? And, what do I do about the self parameter in the >> setLabel function? >> > > Normally, you create an instance of the class. For example, you might do: > mywindow = DrawTest(parent) > > Then, now you have the object, you can call the method: > > mywindow.setLabel() > See above, "parent not defined". What should the defined parameter be? That's really what I was asking. > > You need to play with classes using a simple Python tutorial, before you > try to even understand a GUI. > I done little else over the weekend but play with classes. It's been eight or nine years since I've done any programming at all and then it was strictly C++ and Qt. Extending that experience to PyQt or PySide is not completely straight forward especially as the old memory fades. Although it doesn't seem relevant to the question, I'm programming with Python 3 and, on this particular computer, the OS is Kububtu 13.04. -- Regards, Phil From davea at davea.name Sun Jun 30 08:36:32 2013 From: davea at davea.name (Dave Angel) Date: Sun, 30 Jun 2013 02:36:32 -0400 Subject: [Tutor] Self and class functions In-Reply-To: <51CFAF9F.8090603@bigpond.com> References: <51CF616F.8060300@bigpond.com> <51CF8CD2.50509@davea.name> <51CFAF9F.8090603@bigpond.com> Message-ID: <51CFD1F0.3080000@davea.name> On 06/30/2013 12:10 AM, Phil wrote: > On 30/06/13 11:41, Dave Angel wrote: > > Thank you Dave, Matthew and Steven for taking the time to reply. All > hints are greatly appreciated. > >>> I'm attempting to access the GUI widgets. The buttonClicked slot does >>> what I want but I'd like to access the widgets outside of the class. My >>> function setLabel doesn't work because self and ui are not known. >>> > > Perhaps my "doesn't work" statement was a bit cryptic. The error message > read "name self is not defined" and the same for ui. That's part of the error message, and it's paraphrased. In this case, we can guess the rest. But in many cases there are lots of clues in the whole error message. The whole error message is called a traceback, and usually looks something like the one you paste below. > > I have attempted to create an instance of the DrawTest class although I > had not tried DrawTest(parent) and in this case the error message is > once again: > > Traceback (most recent call last): > File "/home/phil/Python/Qt_draw_sub/draw_test.py", line 52, in > draw = DrawTest(parent) > NameError: name 'parent' is not defined > > >>> I have a second class named Frame that includes a function named dummy. >>> Accessing that function is not a problem. > > Creating an instance of the Frame class is not a problem, although > accessing it's attributes without a function call is causing me to > scratch my head. This is not possible under C++ unless the classes are > friends but I thought that I'd read somewhere that, under Python, > attributes are accessible directly. They are. So what's the problem? Again, be specific. Once you have the instance object 'draw', you can access the instance attributes. The only one visible in your code below is called ui. So you do draw.ui to access it. Previously you tried Drawtest.ui, which would access class attributes instead. There are undoubtedly many other attributes inherited from QMainWindow, but I wouldn't know what they are. dir(draw) will tell you the attributes of the instance object draw. Anyway, this is a side issue and I > only included that in my previous call for help to show that I > understand the need to create an instance of the class. > >> >> The function is called a method if it's actually part of a class. >> >> You don't show us the code for that class and method. But according to >> the call below, the method must be a staticmethod or equivalent. Perhaps >> like the following: >> >> class Frame: >> @staticmethod >> def dummy(): >> return 42 >> > > Yes, much like that. > >> Static methods are strange because they have no self or cls arguments. >> In other words, they're just ordinary functions which happen to be >> defined inside a class. So it's in a different namespace, but has no >> special arguments. >> >> The other "strange" method is a classmethod, which takes a cls (class) >> parameter instead of a self parameter. >> >> The methods below are ordinary methods, and thus need a self parameter. >> Normally that's obtained by creating an instance of the class. >> >> >>> >>> ------------------------------------- >>> >>> from mainwindow import Ui_MainWindow >>> from PySide import QtCore, QtGui >>> from frame import Frame >>> >>> class DrawTest(QtGui.QMainWindow): >>> def __init__(self, parent=None): >>> super(DrawTest, self).__init__(parent) >>> >>> self.ui = Ui_MainWindow() >>> self.ui.setupUi(self) >>> >>> def buttonClicked(self): >>> print("clicked") >>> self.ui.pushButton.setText("test") >>> self.ui.label.setText("Testing") >>> >>> def setLabel(self): >>> self.ui.label.setText("Bingo") >>> >>> DrawTest.setLabel(self) >>> DrawTest.ui.label.setText("Bingo") >>> >>> The two lines above don't work, >> >> You generally should specify in what way they don't work. In your case >> they don't work because 'self' is unbound in top-level code. You could >> use self if you were already inside a method of the same class and were >> calling a different one. >> >>> so my question is how do access the >>> setText function? And, what do I do about the self parameter in the >>> setLabel function? >>> >> >> Normally, you create an instance of the class. For example, you might >> do: >> mywindow = DrawTest(parent) >> >> Then, now you have the object, you can call the method: >> >> mywindow.setLabel() >> > > See above, "parent not defined". What should the defined parameter be? > That's really what I was asking. If QT works like other GUI's, it should be the instance of the parent window. If there's no parent window, it should be None, which is the default. So it may be correct to simply say mywindow = DrawTest() But since I don't use QT, I can't tell you if that's reasonable or not. > >> >> You need to play with classes using a simple Python tutorial, before you >> try to even understand a GUI. >> > > I done little else over the weekend but play with classes. It's been > eight or nine years since I've done any programming at all and then it > was strictly C++ and Qt. Extending that experience to PyQt or PySide is > not completely straight forward especially as the old memory fades. > > Although it doesn't seem relevant to the question, I'm programming with > Python 3 and, on this particular computer, the OS is Kububtu 13.04. > Lots of things are different between Python 2.x and 3.x, like the behavior of classes. In 2.x, you had new-style and old-style classes, and in 3.x you have only the new-style. Similarly, for tkinter, the imports are different between 2.x and 3.x. Telling us ahead of time can avoid people having to give more complex explanations, most of which aren't applicable. Perhaps the auxiliary functions dir() and help() might be of use when you can't figure out what attributes are available. They're intended for interactive use, but they work just fine inside real code. Just avoid putting them inside loops which might make the console display an inordinate amount of text. -- DaveA From alan.gauld at btinternet.com Sun Jun 30 10:00:34 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Jun 2013 09:00:34 +0100 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51CFA902.4090509@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> <51CDFF3E.8030308@nycap.rr.com> <51CE270F.2050302@davea.name> <51CED25A.9070807@nycap.rr.com> <51CEDDF7.60107@davea.name> <51CEF6A4.9060901@nycap.rr.com> <51CF8BFC.2090608@pearwood.info> <51CFA902.4090509@nycap.rr.com> Message-ID: On 30/06/13 04:41, Matt D wrote: > So i have a program that gets pickled data from a thread and displays > the data (9 strings) in TextCtrl fields in the UI. The fact that it is a UI is largely irrelevant apart from the fact that it forces an event driven architecture. > When the pickle is > received it is processed like this: > > def display_data(self,event): ... > attrs = pickle.loads(pickled_dict) > self.update(attrs) > > attrs is passed into the update function: > > def update(self, field_values): > # logger code---------- > self.logfile.write('\n') > self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", > localtime())))) > for k,v in self.fields.items(): > f = field_values.get(k, None) > if f: > self.logfile.write('%s,'%(str(f))) > #end logger code ---------------- Why keep the logfile open? Why not store the logfile name (as selected by the user) and open the file in the update function and close it after writing? > so i have the logfile.txt formatted in a was that is very useful for > later inspection with time series analysis. > ... up near the main class constructor the log file is opened like > this: > > self.logfile = open('logfile.txt', 'a') This is the bit I don't understand. Is there a reason you are using a hard coded filename? That is the source of much of your complexity. And why are you opening it so early? Why not wait till you need to write? > it is stored in the home folder That's a choice you make with the hard coded name. If you allow the user to select the name (and folder) it can be stored anywhere. The user choice can be via a GUI or via a config file or via a startup argument. > and gets appended every time the program > is run. Only problem is i need multiple log files Why do you need multiple log files? Is there one per user and you have multiple users? Or do you need multiple files per user? Or do you only "need" multiple files because you hardcoded the name and then allow the user to choose their own name? > and the user needs to > be able to choose the file from the UI. Are you saying the user needs to be able to rename the file in the middle of processing? If so thats an unusual requirement but there are ways of doing it that are easier than what you seem to be doing. > def openFile(self, evt): > with wx.FileDialog(self, "Choose a file", os.getcwd(), "", > "*.txt*", wx.OPEN) as dlg: > if dlg.ShowModal() == wx.ID_OK: > path = dlg.GetPath() > mypath = os.path.basename(path) > uf = open(mypath, "a") > uf.write(self.logfile) And as we've pointed out you can't write the logfile *object* you need to read the data and then write it out. And to read it you need to mess with the cursor using seek() But if you have already closed the file due to the way you opened it with 'with' you won;t be able to seek or write. Hence, I suspect, the error message. > I have been unable to get the logfile.txt written > into the user opened file. But I'd really like to understand why you believe this is needed. Why not just get the user to specify the file up front and then do all the logging into that. PS. In the update function you have this: > self.logfile.write('\n') > self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", > localtime())))) It might help if you separate out the string formatting from the file writing output = ('\n') output += ('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S",localtime())))) self.logfile.write(output) And hopefully this makes it obvious that the formatting is overly complex you don't need all the string conversion stuff. It can just be: ) output = '\n%s,' % strftime("%Y-%m-%d %H:%M:%S",localtime()) self.logfile.write(output) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From chigga101 at gmail.com Sun Jun 30 12:42:34 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 30 Jun 2013 11:42:34 +0100 Subject: [Tutor] Self and class functions In-Reply-To: <51CFAF9F.8090603@bigpond.com> References: <51CF616F.8060300@bigpond.com> <51CF8CD2.50509@davea.name> <51CFAF9F.8090603@bigpond.com> Message-ID: On Sun, Jun 30, 2013 at 5:10 AM, Phil wrote: > I have attempted to create an instance of the DrawTest class although I had > not tried DrawTest(parent) and in this case the error message is once again: > > Traceback (most recent call last): > File "/home/phil/Python/Qt_draw_sub/draw_test.py", line 52, in > draw = DrawTest(parent) > NameError: name 'parent' is not defined > parent is not a keyword so it needs to be defined in the correct scope otherwise it will be undefined > See above, "parent not defined". What should the defined parameter be? > That's really what I was asking. > honestly i agree with Dave that you should read on classes in Python. Your issue is more a Python one than Qt. Can you tell me who the parent is? A big issue is you are trying to define and pass in a parameter without knowing why. It should be us asking "What should the defined parameter be?." and not you. The default argument is None, so why not try the same code without the parent argument and see what happens. From md123 at nycap.rr.com Sun Jun 30 16:04:19 2013 From: md123 at nycap.rr.com (Matt D) Date: Sun, 30 Jun 2013 10:04:19 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> <51CDFF3E.8030308@nycap.rr.com> <51CE270F.2050302@davea.name> <51CED25A.9070807@nycap.rr.com> <51CEDDF7.60107@davea.name> <51CEF6A4.9060901@nycap.rr.com> <51CF8BFC.2090608@pearwood.info> <51CFA902.4090509@nycap.rr.com> Message-ID: <51D03AE3.1060600@nycap.rr.com> On 06/30/2013 04:00 AM, Alan Gauld wrote: > On 30/06/13 04:41, Matt D wrote: > >> So i have a program that gets pickled data from a thread and displays >> the data (9 strings) in TextCtrl fields in the UI. > > The fact that it is a UI is largely irrelevant apart from the > fact that it forces an event driven architecture. > >> When the pickle is >> received it is processed like this: >> >> def display_data(self,event): > ... >> attrs = pickle.loads(pickled_dict) >> self.update(attrs) >> >> attrs is passed into the update function: >> >> def update(self, field_values): >> # logger code---------- >> self.logfile.write('\n') >> self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", >> localtime())))) >> for k,v in self.fields.items(): >> f = field_values.get(k, None) >> if f: >> self.logfile.write('%s,'%(str(f))) >> #end logger code ---------------- > > Why keep the logfile open? Why not store the logfile name > (as selected by the user) and open the file in the update > function and close it after writing? > >> so i have the logfile.txt formatted in a was that is very useful for >> later inspection with time series analysis. > >> ... up near the main class constructor the log file is opened like >> this: >> >> self.logfile = open('logfile.txt', 'a') > > This is the bit I don't understand. Is there a reason you are > using a hard coded filename? That is the source of much of > your complexity. And why are you opening it so early? Why > not wait till you need to write? > >> it is stored in the home folder > > That's a choice you make with the hard coded name. If you > allow the user to select the name (and folder) it can > be stored anywhere. The user choice can be via a GUI > or via a config file or via a startup argument. > >> and gets appended every time the program >> is run. Only problem is i need multiple log files > > Why do you need multiple log files? > Is there one per user and you have multiple users? > Or do you need multiple files per user? > Or do you only "need" multiple files because you hardcoded > the name and then allow the user to choose their own name? > >> and the user needs to >> be able to choose the file from the UI. > > Are you saying the user needs to be able to rename > the file in the middle of processing? If so thats > an unusual requirement but there are ways of doing > it that are easier than what you seem to be doing. > >> def openFile(self, evt): >> with wx.FileDialog(self, "Choose a file", os.getcwd(), "", >> "*.txt*", wx.OPEN) as dlg: >> if dlg.ShowModal() == wx.ID_OK: >> path = dlg.GetPath() >> mypath = os.path.basename(path) >> uf = open(mypath, "a") >> uf.write(self.logfile) > > And as we've pointed out you can't write the logfile > *object* you need to read the data and then write it out. > And to read it you need to mess with the cursor using seek() > But if you have already closed the file due to the way > you opened it with 'with' you won;t be able to seek or write. > Hence, I suspect, the error message. > >> I have been unable to get the logfile.txt written >> into the user opened file. > > But I'd really like to understand why you believe this > is needed. Why not just get the user to specify the file > up front and then do all the logging into that. > > > PS. In the update function you have this: > >> self.logfile.write('\n') >> self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", >> localtime())))) > > It might help if you separate out the string formatting from the file > writing > > output = ('\n') > output += ('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S",localtime())))) > self.logfile.write(output) > > And hopefully this makes it obvious that the formatting is overly > complex you don't need all the string conversion stuff. It can > just be: > > ) > output = '\n%s,' % strftime("%Y-%m-%d %H:%M:%S",localtime()) > self.logfile.write(output) > > Why keep the logfile open? Why not store the logfile name > (as selected by the user) and open the file in the update > function and close it after writing? if the user selected file is opened by the click event in: # open file dialog def openFile(self, evt): then how i can i open it in : def update(self, field_values): !?!? > This is the bit I don't understand. Is there a reason you are > using a hard coded filename? That is the source of much of > your complexity. And why are you opening it so early? Why > not wait till you need to write? When i first started this project i wanted to be able to have a look at the file so i could get the format proper. So this was the easiest way to write the file. since then I have tried to open it in other places and it simply doesn't work. I suspect because it needs to be available to the main class to write in the home folder or be available across defs in order to copy it to the user selected file. > Why do you need multiple log files? There are multiple frequencies that I need to log data from. And multiple geographic locations. and multiple time periods. > Are you saying the user needs to be able to rename > the file in the middle of processing? If so thats > an unusual requirement but there are ways of doing > it that are easier than what you seem to be doing. no i am not saying the user needs to be able to rename in the middle of processing. what i am saying is that the user needs to be able to choose the file that the 'logfile.txt' is copied to. > But I'd really like to understand why you believe this > is needed. Why not just get the user to specify the file > up front and then do all the logging into that. that sounds ideal, but i have not found a way to pass the user selected file into the loop that writes the data without opening another file. > And hopefully this makes it obvious that the formatting is overly > complex you don't need all the string conversion stuff. i will try making the code more pretty after i get it functional. All that being said. . . i think shutil may the way to go here even though it creams existing files. so if open self.logfile like this: self.logfile = tempfile.mktemp('.txt) how would i use shutil to copy the tempory self.logfile into the user selected file in this open fileFile()?: # open file dialog def openFile(self, evt): with wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.txt*", wx.OPEN) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() mypath = os.path.basename(path) with open('mypath', 'a') as handle: So 'handle' is the user opened file, i set the dialog to only allow opening .txt files. how can i use the shutil.copyfile() to copy the temporary .txt file into the user opened .txt file? Thanks! From alan.gauld at btinternet.com Sun Jun 30 16:52:39 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Jun 2013 15:52:39 +0100 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51D03AE3.1060600@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> <51CDFF3E.8030308@nycap.rr.com> <51CE270F.2050302@davea.name> <51CED25A.9070807@nycap.rr.com> <51CEDDF7.60107@davea.name> <51CEF6A4.9060901@nycap.rr.com> <51CF8BFC.2090608@pearwood.info> <51CFA902.4090509@nycap.rr.com> <51D03AE3.1060600@nycap.rr.com> Message-ID: On 30/06/13 15:04, Matt D wrote: > > that sounds ideal, but i have not found a way to pass the user selected > file into the loop that writes the data without opening another file. Don;t pass the file pass the fgile *name* Then inside the update method open the file(in append mode) and write the latest update then close the file again. (Or use the 'with' paradigm which closes the file for you) Repeat as needed. Part of the propblem is that you are openming the file right at the beginning and trying to pass the open file object around. Pass the filename and open when needed. Its slightly more resource intensive but a lot simpler. > how would i use shutil to copy the tempory self.logfile into the user > selected file in this open fileFile()?: The way to go is to only have one file and avoid all the copying stuff completely. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From etanes.rm at gmail.com Sun Jun 30 16:46:02 2013 From: etanes.rm at gmail.com (Scurvy Scott) Date: Sun, 30 Jun 2013 14:46:02 +0000 Subject: [Tutor] Generate word list from specified letters Message-ID: Hello all. I'm trying to create a program right now that will pull a dictionary from urban dictionary, then use that dictionary as the basis for generating words with specified letters. Maybe I'm not articulating that well enough.. I'm not at all sure where to start and any guidance would be helpful. I'm running Debian and Python 2.7 Scott -------------- next part -------------- An HTML attachment was scrubbed... URL: From md123 at nycap.rr.com Sun Jun 30 17:42:18 2013 From: md123 at nycap.rr.com (Matt D) Date: Sun, 30 Jun 2013 11:42:18 -0400 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: References: <51BF4905.6010801@nycap.rr.com> <51BF52B5.1050902@davea.name> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> <51CDFF3E.8030308@nycap.rr.com> <51CE270F.2050302@davea.name> <51CED25A.9070807@nycap.rr.com> <51CEDDF7.60107@davea.name> <51CEF6A4.9060901@nycap.rr.com> <51CF8BFC.2090608@pearwood.info> <51CFA902.4090509@nycap.rr.com> <51D03AE3.1060600@nycap.rr.com> Message-ID: <51D051DA.8020307@nycap.rr.com> On 06/30/2013 10:52 AM, Alan Gauld wrote: > On 30/06/13 15:04, Matt D wrote: >> >> that sounds ideal, but i have not found a way to pass the user selected >> file into the loop that writes the data without opening another file. > > Don;t pass the file pass the fgile *name* > Then inside the update method open the file(in append mode) > and write the latest update then close the file again. (Or > use the 'with' paradigm which closes the file for you) > Repeat as needed. > > Part of the propblem is that you are openming the file right > at the beginning and trying to pass the open file object > around. Pass the filename and open when needed. Its slightly > more resource intensive but a lot simpler. > >> how would i use shutil to copy the tempory self.logfile into the user >> selected file in this open fileFile()?: > > The way to go is to only have one file and avoid all the > copying stuff completely. > im sorry i don't understand how to pass the file name from the open dialog into the update method? I'm sorry i just don't get it. so if the user opened file is 'handle' like this?: def openFile(self, evt): with wx.FileDialog(self, "Choose a file", os.getcwd(), "", "*.txt*", wx.OPEN) as dlg: if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() mypath = os.path.basename(path) with open('mypath', 'a') as handle: self.handle = handle Then i put 'handle' in the update() like this??: def update(self, field_values, handle): logfile = open('handle.txt', 'a') wait no 'handle' is already opened in the click event. so something like this: def update(self, field_values, handle): self.logfile = open('logfile.txt' 'a') #logger code--------------- self.logfile.write('\n') self.logfile.write('%s,'%(str(strftime("%Y-%m-%d %H:%M:%S", localtime())))) for k,v in self.fields.items(): f = field_values.get(k, None) if f: self.logfile.write('%s,'%(str(f))) #end logger code ---------------- self.logfile = handle I really have no idea how to go about implementing this idea of passing the file name around in code. Any suggestion will be much appreciated. Thanks. From alan.gauld at btinternet.com Sun Jun 30 19:43:04 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Jun 2013 18:43:04 +0100 Subject: [Tutor] Need help appending data to a logfile In-Reply-To: <51D051DA.8020307@nycap.rr.com> References: <51BF4905.6010801@nycap.rr.com> <51BF5382.2040608@gmail.com> <51C78BD7.9030502@davea.name> <51C8BC8A.9060008@nycap.rr.com> <51C8C0E4.9040508@davea.name> <51CC4DF4.3020205@nycap.rr.com> <51CC5276.2080807@nycap.rr.com> <51CC6082.4060102@davea.name> <51CC6964.4040704@nycap.rr.com> <51CC6E3A.8020609@davea.name> <51CCAA1F.2020808@nycap.rr.com> <51CCB266.5050206@davea.name> <51CD7328.8070407@nycap.rr.com> <51CD7592.7030902@davea.name> <51CD8D40.4000700@nycap.rr.com> <51CD92C9.6040303@pearwood.info> <51CDEA08.6060407@nycap.rr.com> <51CDFF3E.8030308@nycap.rr.com> <51CE270F.2050302@davea.name> <51CED25A.9070807@nycap.rr.com> <51CEDDF7.60107@davea.name> <51CEF6A4.9060901@nycap.rr.com> <51CF8BFC.2090608@pearwood.info> <51CFA902.4090509@nycap.rr.com> <51D03AE3.1060600@nycap.rr.com> <51D051DA.8020307@nycap.rr.com> Message-ID: On 30/06/13 16:42, Matt D wrote: > im sorry i don't understand how to pass the file name from the open > dialog into the update method? I'm sorry i just don't get it. so if > the user opened file is 'handle' like this?: OK, technically you probably donb;t want to pasws it into the metjod but to store it in an attribute of the object. > def openFile(self, evt): > with wx.FileDialog(self, "Choose a file", os.getcwd(), "", > "*.txt*", wx.OPEN) as dlg: > if dlg.ShowModal() == wx.ID_OK: > self.logpath = dlg.GetPath() Now self.logpath holds a record of the full path to the log file. (assuming dlg.getPath does return the full path, I haven't used wxPython for a while...) > def update(self, field_values): > with open(self.logpath, 'a') as logfile: > # format the line and write to file as before And that is all you need. logfile is now your open logfile object referencing the file named by the user in the dialog. Because we opened it in a 'with' construct it will automatically be closed at the end of the block ready to be reopened next time update gets called. And that is it. No more should be required. Provided you have permission to write to the file/folder then you are now logging to the file specified by the user. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Sun Jun 30 20:03:25 2013 From: __peter__ at web.de (Peter Otten) Date: Sun, 30 Jun 2013 20:03:25 +0200 Subject: [Tutor] Generate word list from specified letters References: Message-ID: Scurvy Scott wrote: > I'm trying to create a program right now that will pull a dictionary from > urban dictionary, then use that dictionary as the basis for generating > words with specified letters. > > Maybe I'm not articulating that well enough.. > > I'm not at all sure where to start and any guidance would be helpful. > > I'm running Debian and Python 2.7 I suggest that you start with one part. If you read the words from your local /usr/share/dict/words file you can concentrate on organising that data for an efficient lookup. Make it as simple as you can, e. g. implement an is_matching_word(word, letters) function and loop over the words file. You need to decide if you care about repetition -- is letter-count significant, i. e do 'appointing', 'pagination', and 'poignant' count as equal? Once you have a working baseline you can think about how to replace the slow loop with fast dict lookup. What should the dict keys look like? They must be hashable -- string, tuple or frozenset are promising contenders. What should the values be? You sure can come up with something for these. Once you have this running to your satisfaction you can work out how to get hold of the words from Urban Dictionary. Do they provide a downloadable list, an API, or do you have to scrape their webpages? If it's the first you have a drop-in replacement for you local words file, for the other options you need to write some more code. From jacklittlemc at yahoo.com Thu Jun 27 17:16:36 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Thu, 27 Jun 2013 17:16:36 +0200 Subject: [Tutor] Saving Progress Message-ID: <3FE557DB-0F34-4604-BE6A-82278EDFE031@yahoo.com> Is there a way to save a players progress in a game using python without any modules Jack Sent from my iPod From fabiosantosart at gmail.com Fri Jun 28 11:34:53 2013 From: fabiosantosart at gmail.com (=?ISO-8859-1?Q?F=E1bio_Santos?=) Date: Fri, 28 Jun 2013 10:34:53 +0100 Subject: [Tutor] unwanted 'zero' ending In-Reply-To: References: <51CC324E.5000903@pearwood.info> Message-ID: On 28 Jun 2013 08:33, "Peter Otten" <__peter__ at web.de> wrote: > > Whatever approach you pick, unittest, doctest, or a combination, your code > will improve -- not just because you are verifying its correctness to some > extent, but also because the inherent question "How can I test it?" will > lead to a better overall structure. This is the thing I've found to be most useful when I first started writing tests. When I go test-first and write your test for a new function, that's when the signature becomes obvious to me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From grubber at roadrunner.com Sat Jun 29 01:08:47 2013 From: grubber at roadrunner.com (grubber at roadrunner.com) Date: Fri, 28 Jun 2013 19:08:47 -0400 Subject: [Tutor] converting string to text Message-ID: <20130628230847.WFUBY.26433.root@cdptpa-web20-z02> I don't get why this doesn't work. Its a very small program to read in a group of numbers. I've attached the the python file and my test file. The test file just contains one line. The error I get is that it can't convert the string to a float, but its a valid number. -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: text/x-python Size: 520 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: test.dat Type: application/x-ns-proxy-autoconfig Size: 32 bytes Desc: not available URL: From infoservicecustomer at contractor.net Sat Jun 29 18:06:07 2013 From: infoservicecustomer at contractor.net (aaabbbfffmmmee aaabbbfffmmmee) Date: Sat, 29 Jun 2013 09:06:07 -0700 Subject: [Tutor] Notice Message-ID: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Claim.rtf Type: application/rtf Size: 855 bytes Desc: not available URL: From datar at wisc.edu Sat Jun 29 20:00:20 2013 From: datar at wisc.edu (Makarand Datar) Date: Sat, 29 Jun 2013 13:00:20 -0500 Subject: [Tutor] using python for parsing In-Reply-To: References: Message-ID: Hi, So I am able to read in a file, and write out a file from python. I have some question about the text manipulation that I need to do between reading in a file and spitting out another. Couple of things I would like to do, are: if the first character of a line is a comma, I would like to delete the newline character at the end of the previous line and make a longer line (one line followed by another without a newline in between); if the first character of the line is an exclamation mark, I would like to delete that line altogether. So for instance, if the input file text looks like the following, one, two, three , four, five, six ! This is a comment seven, eight, nine I would like to output a file the text in which looks like one, two, three, four, five, six seven, eight, nine This is to get me going on this and I will have to do a LOT of text manipulation beyond this. So any tips in general are highly appreciated. Thank you On Wed, Jun 26, 2013 at 12:05 PM, Makarand Datar wrote: > Hi, > > I know practically nothing about python. I know how to install it and all > that kind of stuff. I want to use python for parsing a text file. The task > is to read in a text file, and write out another text file that is written > in some particular way using the data from the file that was read in. The > question is how do I go about this? What part of python documentation, or a > book I should read etc. I dont want to start reading a python book from the > first page. I just want to do this parsing task and I will learn about > whatever I need to as I encounter it. > > Thank you for the help. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gbstack08 at gmail.com Sun Jun 30 08:18:23 2013 From: gbstack08 at gmail.com (Todong Ma) Date: Sun, 30 Jun 2013 14:18:23 +0800 Subject: [Tutor] how to determine windows version In-Reply-To: <51CFAF9F.8090603@bigpond.com> References: <51CF616F.8060300@bigpond.com> <51CF8CD2.50509@davea.name> <51CFAF9F.8090603@bigpond.com> Message-ID: <51CFCDAF.7090108@gmail.com> You can use either sys.getwindowsversion() or platform.platform() function. platform.platform() gives a more friendly string, e.g. "Windows-7-6.1.7600", that means Windows 7 with major version 6, minor version 1 and Build No. 7600. While sys.getwindowsversion() will return a named tuple, like (major=6, minor=1, build=7600) This blog post describes how to get windows version in detail: http://redino.net/blog/2013/06/detect-windows-version-in-python/