tutor@python.org
"Steven D'Aprano" wrote They are not gone however there are still 32 bits in an integer so the top bits *should* be set to zero. No, Python ints are not 32 bit native ints. They're not even 64 bit ints. Python has unified the old "int" type with "long", so that ints automatically grow as needed. This is in Python 3.1: Valid point but irrelevant to the one I was making which is that the number after shifting is longer than 8 bits. But glitches can occur from time to time... If Python had a glitch of the magnitude of right-shifting non-zero bits into a number, that would be not just a bug but a HUGE bug. Bit shifting is machine specific. Some CPUs (the DEC PDP range from memory is an example) will add the carry bit for example, most will not. But you can never be sure unless you know exactly which artchiotecture the program will run on. And of course data can always be corrupted at any time so its always wise to take as many precautions as possibe to keep it clean (although corruption within the CPU itself is, I agree, extremely unlikely) be as serious as having 1+1 return 374 instead of 2. Guarding against (say) 8 >> 1 returning anything other than 4 Not if you have a 4 bit processor and the previous opertation set the carry flag. In that case returning 12 would be emminently sensibleand used to be a common assembler trick for recovering from overflow errors. guarding against 8//2 returning something other than 4: if you can't trust Python to get simple integer arithmetic right, But ths is not simple integer arithmetic it is bit m,anippulation. You can use bit manipulation to fake arithmetic but they are fundamentally different operations and may not always produce the same results depending on how the designer built it! trust it to do *anything*, and your guard (ANDing it with 255) can't be trusted either. Nothing can be trusted 100% on a computer because, as you say the guard might itself be corrupted. Itas all about risk management. But when it comes to bit operations I'd always have at least one extra level of check, whether it be a mask or a checksum. It is certainly good practice if you are dealing with numbers which might be more than 24 bits to start with: Its more than good practice there, its essential. But *if* you know the int is no more than 32 bits, then adding in a guard to protect against bugs in the >> operator is just wasting CPU It may not be a bug it may be a design feature. Now all modern CPUs behave as you would expect but if you are running on older equipment (or specialised hardware - but that's more unlikely to have Python onboard!) you can never be quite sure how bitwise operations will react at boundary cases. If you know for certainty what the runtime environment will be then you can afford to take a chance. In the case in point the & 255 keeps the coding style consistent and provides an extra measure of protection against unexpected oddities so I would keep it in there. cycles and needlessly complicating the code. The right way to guard against "this will never happen" scenarios is with assert: assert n.bit_length() <= 32 # or "assert 0 <= n < 2**32" I would accept the second condition but the mask is much faster. bit_length doesn't seem to work on any of my Pythons (2.5,2.6 and 3.1) This has two additional advantages: (1) It clearly signals to the reader what your intention is ("I'm absolutely 100% sure than n will not be more than 32 bits, but since I'm a fallible human, I'd rather find out about an error in my logic as soon as possible"). The assert approach is perfectly valid, but since the mask is more consistent I'd still prefer to use it in this case. Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
tutor@python.org
On Sun, Feb 14, 2010 at 09:16:18AM -, Alan Gauld wrote: > But ths is not simple integer arithmetic it is bit m,anippulation. > You can use bit manipulation to fake arithmetic but they are > fundamentally different operations and may not always > produce the same results depending on how the designer > built it! And this brings us back to one of Python's philosophical points. State clearly and explicitly what you mean to be doing. If you are doing bit manipulation, use bit manipulation operators. All the valid points above in this thread aside, it will make maintain- ing your code easier in the future if it's very clear what you intended the code to accomplish, and how. -- Steve Willoughby| Using billion-dollar satellites st...@alchemy.com | to hunt for Tupperware. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Editing html using python
Hi I need to edit html programmatically . Sadly the html might be broken at places . I was using BeautifulSoup but there were lots of problems and it is also not maintained can some one guide me to any tutorials on editing html using lxml . -- A-M-I-T S|S ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ?
2010/2/13 Luke Paireepinart > > > On Sat, Feb 13, 2010 at 9:56 AM, patrice laporte wrote: > >> >> Hi, >> >> Being in an exeption of my own, I want to print the name of the caller, >> and I'm looking for a way to have it. >> >> Could you tell us exactly why you want to do this? It seems sort of > strange. Also couldn't you pass the caller as an argument to your function? > > Hi, I don't know if it's strange, maybe, so tell me why. Or maybe it's me Maybe the fact I'm à pure C coder for a longtime prevent me from thinking in Python, maybe my brain is only capable of thinking and viewing in C. and maybe there's an obvious way to solve my problem that I can't see yet... or maybe it's because I'm French, genetically programed to live in the past ? ... so this mailing list is my starting point to improve my Python understanding. And now, something different : what I want to do, and why. I got a class that takes a file name in its __init__ method (it could be elsewhere, but why not here ?). Then, somewhere in that class, a method will do something with that file name, such as "try to open that file". If the file do esn't exist, bing ! I got an exception "I/O Error n°2 : file doesn't exist". That's nice, I of course catch this exception, but it's not enough for the user : What file are we talking about ? And how to tell the user what is that file, and make him understand he tell the app to use a file that doesn't exist ? And this is not enough for developer : where that error happened ? what class ? what method ? There is many solution, and mine is : - don't check for the existence of the file in __init__ - don't use a default value for the file name parameter in __init__ : coder MUST provide it. - try/catch open(this_file_name) and if I got an IOErro exception, I re-raise my own exception with : - the name of the class where that IOError occured - the name of the method in that class that make that error occured - the name of the file the method tried to opened - some other info to help diagnostic Then my exception object can : - log in a file dedicated to the team (so, just me for the moment) - and/or log in a file dedicated to the user And then the app can popup a message box or something like that. Currently, I'm thinking about "how to get that class/method name", easily, and make something usefull with that. I don't want to write the name of the method and the class each time I need to use my exception class, and I don't want to modify that name each time I'm doing a refactoring operation : I just want to do something like : except IOError, (errno, errmes): raise myexceptioniwanttobenice ("IO Error %d -> %s ('%s')" % (errno, errmes, self.__csv) ) And then I print somewhere a message like : Error in csv2db.getColumnFromCsv : IO Error 2 -> No such file or directory ('toto') What I don't want is to write something like : except IOError, (errno, errmes): raise myexceptioniwanttobenice ("cvs2db.getColumnFromCsv IO Error %d -> %s ('%s')" % (errno, errmes, self.__csv) ) I don't want because it's to much to write, and if I change the class name, I don't want to rewrite all my call to change that name. So, I was looking for a way to retrieve : The name of the class the object that throw the exception belongs to The name of the method in that class And I finally found those recipe with the sys._getframe call. My first solution, currently, is (I didn't yet rewrite it with the solution with the traceback module) : class argError(Exception): def __init__(self, callerClass, errorMessage): self.__class = callerClass.__class__.__name__ self.__method = sys._getframe(1).f_code.co_name self.__message = errorMessage def __str__(self): return "Error in %s.%s : %s" % (self.__class, self.__method, self.__message) And how I use it : try: f = open(self.__csv) except IOError, (errno, errmes): raise argError (self, "IO Error %d -> %s ('%s')" % (errno, errmes, self.__csv) ) I now will : - rewrite it with the solution with traceback module - read about that module and find how to get rid of the need to pass "self" as an argument in the call "raise argError (*self*, "IO Error %d -> %s ('%s')" % (errno, errmes, self.__csv) )". That call enable me to get the name of the class. All of that is a way to me to experiment Python, I try a lot of thing to understand, and then I will make a choice. But now, it's time to lunch. Did I gave you enough information about what I want ? Patrice ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ?
I see why you would want the error messages but why is the default error message not enough, that is why I am curious, and typically introspection on objects is not necessary (for example, people often want to convert a string into a variable name to store a value (say they have the string "foobar1" and they want to store the value "f" in the variable "foobar1", how do they change foobar1 to reference a string? well you can just use exec but the core issue is that there's really no reason to do it in the first place, they can just use a dictionary and store dict['foobar1'] = 'f' and it is functionally equivalent (without the danger in the code)). I get the feeling that your issue is the same sort of thing, where an easier solution exists but for whatever reason you don't see it. I don't know if this is true or not. Here's my take on this: >>> class x(object): def __init__(self, fname): self.temp = open(fname).read() >>> a = x('foobar') Traceback (most recent call last): File "", line 1, in# this is the module it's in a = x('foobar')# this is the line where I tried to initialize it File "", line 3, in __init__ # which called this function, which is the one that has the error self.temp = open(fname).read() #and the error occurred while trying to perform this operation IOError: [Errno 2] No such file or directory: 'foobar' #and the error was that the file 'foobar' could not be found. This is implicitly stated that 'x' is the class with the method that had the issue, and it was specifically the __init__ method, and the file that could not be read was called 'foobar'. How does this not satisfy your requirements? Is it the form of the output that you do not agree with (you want it all on one line?) I've never had issues with Python's exception statements, I've always had no trouble finding where exceptions occurred, and I'm not sure what information is missing from the traceback that you'd like to convey to the user. On Sun, Feb 14, 2010 at 5:33 AM, patrice laporte wrote: > > 2010/2/13 Luke Paireepinart > > >> >> On Sat, Feb 13, 2010 at 9:56 AM, patrice laporte wrote: >> >>> >>> Hi, >>> >>> Being in an exeption of my own, I want to print the name of the caller, >>> and I'm looking for a way to have it. >>> >>> Could you tell us exactly why you want to do this? It seems sort of >> strange. Also couldn't you pass the caller as an argument to your function? >> >> > Hi, > > I don't know if it's strange, maybe, so tell me why. Or maybe it's me > Maybe the fact I'm à pure C coder for a longtime prevent me from thinking in > Python, maybe my brain is only capable of thinking and viewing in C. and > maybe there's an obvious way to solve my problem that I can't see yet... or > maybe it's because I'm French, genetically programed to live in the past ? > ... so this mailing list is my starting point to improve my Python > understanding. > > And now, something different : what I want to do, and why. > > I got a class that takes a file name in its __init__ method (it could be > elsewhere, but why not here ?). Then, somewhere in that class, a method will > do something with that file name, such as "try to open that file". > > If the file do esn't exist, bing ! I got an exception "I/O Error n°2 : file > doesn't exist". > > That's nice, I of course catch this exception, but it's not enough for the > user : What file are we talking about ? And how to tell the user what is > that file, and make him understand he tell the app to use a file that > doesn't exist ? > And this is not enough for developer : where that error happened ? what > class ? what method ? > > There is many solution, and mine is : > > - don't check for the existence of the file in __init__ > - don't use a default value for the file name parameter in __init__ : coder > MUST provide it. > - try/catch open(this_file_name) and if I got an IOErro exception, I > re-raise my own exception with : >- the name of the class where that IOError occured >- the name of the method in that class that make that error occured >- the name of the file the method tried to opened >- some other info to help diagnostic > > Then my exception object can : >- log in a file dedicated to the team (so, just me for the moment) >- and/or log in a file dedicated to the user > > And then the app can popup a message box or something like that. > > Currently, I'm thinking about "how to get that class/method name", easily, > and make something usefull with that. > > I don't want to write the name of the method and the class each time I need > to use my exception class, and I don't want to modify that name each time > I'm doing a refactoring operation : I just want to do something like : > >except IOError, (errno, errmes): > raise myexceptioniwanttobenice ("IO Error %d -> %s ('%s')" % > (errno, e
Re: [Tutor] Editing html using python
On Sun, Feb 14, 2010 at 5:10 AM, Amit Sethi wrote: > Hi I need to edit html programmatically . Sadly the html might be broken at > places . I was using BeautifulSoup but there were lots of problems and it is > also not maintained can some one guide me to any tutorials on editing html > using lxml . > This is a rather specific question and if you really just want tutorials why don't you just google for them? Or are you also asking in a roundabout way if anyone on the list has a better idea for parsing broken html? It would help if you would take the time to explain how the html is broken and what exactly "lost of problems" with BeautifulSoup were. Also I think beautifulsoup is part of the Python standardlib now, isn't it? Why do you think it is not maintained? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ?
On Sun, Feb 14, 2010 at 6:33 AM, patrice laporte wrote: > - try/catch open(this_file_name) and if I got an IOErro exception, I > re-raise my own exception with : >- the name of the class where that IOError occured >- the name of the method in that class that make that error occured >- the name of the file the method tried to opened >- some other info to help diagnostic > > Then my exception object can : >- log in a file dedicated to the team (so, just me for the moment) >- and/or log in a file dedicated to the user > > And then the app can popup a message box or something like that. For simple applications that run from the command line and just do one thing, it is often adequate to let the exceptions propagate to the top level of the program and abort it, printing the stack trace. If the programming is doing some kind of repeated processing and you don't want an error in one iteration to abort the rest of the processing, then catch the exception inthe loop and log the error, then continue. The logging module makes it pretty easy to log exceptions. You can even have it log a detailed error to a file and a shortened version to the console. For GUI programs I usually install an exception handler in the event loop so if there is a problem running any event the error is caught and logged and the program continues. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Editing html using python
On Sun, Feb 14, 2010 at 6:10 AM, Amit Sethi wrote: > Hi I need to edit html programmatically . Sadly the html might be broken at > places . I was using BeautifulSoup but there were lots of problems and it is > also not maintained can some one guide me to any tutorials on editing html > using lxml . What version of BS are you using? 3.0.8 seems to be the best choice for Python 2.6. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] file exception & behaviour (was: Getting caller name...)
On Sun, 14 Feb 2010 12:33:09 +0100 patrice laporte wrote: > 2010/2/13 Luke Paireepinart > > > > > > > On Sat, Feb 13, 2010 at 9:56 AM, patrice laporte > > wrote: > > > >> > >> Hi, > >> > >> Being in an exeption of my own, I want to print the name of the caller, > >> and I'm looking for a way to have it. > >> > >> Could you tell us exactly why you want to do this? It seems sort of > > strange. Also couldn't you pass the caller as an argument to your function? > > > > > Hi, > > I don't know if it's strange, maybe, so tell me why. Or maybe it's me > Maybe the fact I'm à pure C coder for a longtime prevent me from thinking in > Python, maybe my brain is only capable of thinking and viewing in C. and > maybe there's an obvious way to solve my problem that I can't see yet... or > maybe it's because I'm French, genetically programed to live in the past ? > ... so this mailing list is my starting point to improve my Python > understanding. > > And now, something different : what I want to do, and why. > > I got a class that takes a file name in its __init__ method (it could be > elsewhere, but why not here ?). Then, somewhere in that class, a method will > do something with that file name, such as "try to open that file". > > If the file do esn't exist, bing ! I got an exception "I/O Error n°2 : file > doesn't exist". > > That's nice, I of course catch this exception, but it's not enough for the > user : What file are we talking about ? And how to tell the user what is > that file, and make him understand he tell the app to use a file that > doesn't exist ? > And this is not enough for developer : where that error happened ? what > class ? what method ? > > There is many solution, and mine is : > > - don't check for the existence of the file in __init__ > - don't use a default value for the file name parameter in __init__ : coder > MUST provide it. > - try/catch open(this_file_name) and if I got an IOErro exception, I > re-raise my own exception with : >- the name of the class where that IOError occured >- the name of the method in that class that make that error occured >- the name of the file the method tried to opened >- some other info to help diagnostic > > Then my exception object can : >- log in a file dedicated to the team (so, just me for the moment) >- and/or log in a file dedicated to the user > > And then the app can popup a message box or something like that. > > Currently, I'm thinking about "how to get that class/method name", easily, > and make something usefull with that. > > I don't want to write the name of the method and the class each time I need > to use my exception class, and I don't want to modify that name each time > I'm doing a refactoring operation : I just want to do something like : > >except IOError, (errno, errmes): > raise myexceptioniwanttobenice ("IO Error %d -> %s ('%s')" % > (errno, errmes, self.__csv) ) > > And then I print somewhere a message like : > > Error in csv2db.getColumnFromCsv : IO Error 2 -> No such file or > directory ('toto') > > What I don't want is to write something like : > > except IOError, (errno, errmes): > raise myexceptioniwanttobenice ("cvs2db.getColumnFromCsv IO > Error %d -> %s ('%s')" % (errno, errmes, self.__csv) ) > > I don't want because it's to much to write, and if I change the class name, > I don't want to rewrite all my call to change that name. > > So, I was looking for a way to retrieve : > The name of the class the object that throw the exception belongs to > The name of the method in that class > > And I finally found those recipe with the sys._getframe call. > > My first solution, currently, is (I didn't yet rewrite it with the solution > with the traceback module) : > > class argError(Exception): > def __init__(self, callerClass, errorMessage): > self.__class = callerClass.__class__.__name__ > self.__method = sys._getframe(1).f_code.co_name > self.__message = errorMessage > > def __str__(self): > return "Error in %s.%s : %s" % (self.__class, self.__method, > self.__message) > > And how I use it : > >try: > f = open(self.__csv) > except IOError, (errno, errmes): > raise argError (self, "IO Error %d -> %s ('%s')" % (errno, > errmes, self.__csv) ) > > I now will : > - rewrite it with the solution with traceback module > - read about that module and find how to get rid of the need to pass "self" > as an argument in the call "raise argError (*self*, "IO Error %d -> %s > ('%s')" % (errno, errmes, self.__csv) )". That call enable me to get the > name of the class. > > All of that is a way to me to experiment Python, I try a lot of thing to > understand, and then I will make a choice. > > But now, it's time to lunch. Did I gave you enough information about what I > want ? > > Patrice First, here is a kind of implementation of your specification. I just wr
tutor@python.org
Just reviewed this post and wonder whether the explanation is clear for anyone else as myself ;-) Denis On Sat, 13 Feb 2010 23:17:27 +0100 spir wrote: > On Sat, 13 Feb 2010 13:58:34 -0500 > David Abbott wrote: > > > I am attempting to understand this little program that converts a > > network byte order 32-bit integer to a dotted quad ip address. > > > > #!/usr/bin/python > > # Filename : int2ip.py > > > > MAX_IP = 0xL > > ip = 2130706433 > > > > def int2ip(l): > > if MAX_IP < l < 0: > > raise TypeError, "expected int between 0 and %d inclusive" % > > MAX_IP > > return '%d.%d.%d.%d' % (l>>24 & 255, l>>16 & 255, l>>8 & 255, l & > > 255) > > > > result = int2ip(ip) > > print result > > > > I don't understand the l>>24 & 255. > > > > from the docs; > > Right Shift a >> b rshift(a, b) > > Bitwise And a & b and_(a, b) > > > > thanks > > > > In addition to Steve's excellent explanation: > Shifting to the left n bits is equivalent to multiplying by 2^n. Shifting to > the right n bits is equivalent to dividing by 2^n. Shifting to the right 8 > bits is thus equivalent to dividing by 2^8=256; which means making each octet > (in a long integer) one level less significant. > AND-ing is equivalent to masking (this is actually called a mask operating) > all bits wich are not 1 in the mask. So AND-ing with =255 masks all > bits except the ones of the least significant octet. > If you represent a 32-bit integer as 4 octets, or 8 hex digits, the picture > is easier to catch: > n = 0x12345678# 0x12345678 = abcd (b=0x34=52) > # to get b: > temp = n >> 16# 0x1234 = 00ab > b = temp & 255# 0x0034 = 000b > > You can perform the same operation without bit-level operators, using modulo > and integer division. To understand this, again consider the "abcd" > representation: this means a 32-bit integer can be seen as 4-digit number > written in base 256 (yes!). Division by 256^n gets rid of n lowest digits, > moving down all other ones. Modulo 256^n gets rid of digits in higher > position than n. (This may help and fully catch the sense of "base n"). > n = 0x12345678# 0x12345678 = abcd (b=0x34) > # to get b: > temp = n // (256**2) # 0x1234 = 00ab > b = temp % 256# 0x0034 = 000b > > (examples untested) > Bit operations are by far faster, indeed. > > > Denis la vita e estrany http://spir.wikidot.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
tutor@python.org
On Sun, 14 Feb 2010 09:16:18 - "Alan Gauld" wrote: > In the case in point the & 255 keeps the coding style consistent > and provides an extra measure of protection against unexpected > oddities so I would keep it in there. You're right on that, Kent. My comment was rather wrong. Especially for consistent code I would now keep it, too. Denis la vita e estrany http://spir.wikidot.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting caller name without the help of "sys._getframe(1).f_code.co_name" ?
On Sun, 14 Feb 2010 10:33:09 pm patrice laporte wrote: > I got a class that takes a file name in its __init__ method (it > could be elsewhere, but why not here ?). Then, somewhere in that > class, a method will do something with that file name, such as "try > to open that file". > > If the file do esn't exist, bing ! I got an exception "I/O Error n°2 > : file doesn't exist". Are you sure? What version of Python are you using? I get a completely different error message: >>> open("no such file.txt", "r") Traceback (most recent call last): File "", line 1, in IOError: [Errno 2] No such file or directory: 'no such file.txt' Note carefully that the exception shows you the file name. > That's nice, I of course catch this exception, but it's not enough > for the user : What file are we talking about ? And how to tell the > user what is that file, and make him understand he tell the app to > use a file that doesn't exist ? >>> try: ... open("no such file.txt", "r") ... except IOError, e: ... pass ... >>> e.filename 'no such file.txt' > And this is not enough for developer : where that error happened ? > what class ? what method ? All these things are displayed by the default traceback mechanism. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] command error help
SyntaxError: EOL while scanning single-quoted string. 2010/2/14 Shurui Liu (Aaron Liu) > Here is a program I need to run in putty.exe, but there is an error in it. > I cannot find out. When I ran this program, it mentions that the error is in > red line.It shows that "SyntaxError: EOL while scanning single-quoted > string." Would you please help me? Thank you! > > > # Useless Trivia > > # > # Gets personal information from the user and then > # prints true, but useless information about him or her > > name = raw_input("Hi. What's your name? ") > > age = raw_input("And how old are you? ") > > > age = int(age) > > weight = raw_input("Okay, last question. How many pounds do you weigh? ") > weight = int(weight) > > print "\nIf poet ee cummings were to email you, he'd address you as", > name.lower() > > > ee_mad = name.upper() > print "But if ee were mad, he'd call you", ee_mad > > dog_years = age / 7 > print "\nDid you know that you're just", dog_years, "in dog years?" > > > > seconds = age * 365 * 24 * 60 * 60 > print "But you're also over", seconds, "seconds old." > > called = name * 5 > print "\nIf a small child were trying to get your attention, " \ > > > "your name would become:" > print called > > moon_weight = weight / 6.0 > print "\nDid you know that on the moon you would weigh only", moon_weight, > "pounds?" > > sun_weight = weight * 27.1 > > print "But on the sun, you'd weigh", sun_weight, "(but, ah... not for long)." > > raw_input("\n\nPress the enter key to exit.") > > > > -- > Shurui Liu (Aaron Liu) > Computer Science & Engineering Technology > University of Toledo > > > > -- > Shurui Liu (Aaron Liu) > Computer Science & Engineering Technology > University of Toledo > -- Shurui Liu (Aaron Liu) Computer Science & Engineering Technology University of Toledo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] command error help
Here is a program I need to run in putty.exe, but there is an error in it. I cannot find out. When I ran this program, it mentions that the error is in red line. Would you please help me? Thank you! # Useless Trivia # # Gets personal information from the user and then # prints true, but useless information about him or her name = raw_input("Hi. What's your name? ") age = raw_input("And how old are you? ") age = int(age) weight = raw_input("Okay, last question. How many pounds do you weigh? ") weight = int(weight) print "\nIf poet ee cummings were to email you, he'd address you as", name.lower() ee_mad = name.upper() print "But if ee were mad, he'd call you", ee_mad dog_years = age / 7 print "\nDid you know that you're just", dog_years, "in dog years?" seconds = age * 365 * 24 * 60 * 60 print "But you're also over", seconds, "seconds old." called = name * 5 print "\nIf a small child were trying to get your attention, " \ "your name would become:" print called moon_weight = weight / 6.0 print "\nDid you know that on the moon you would weigh only", moon_weight, "pounds?" sun_weight = weight * 27.1 print "But on the sun, you'd weigh", sun_weight, "(but, ah... not for long)." raw_input("\n\nPress the enter key to exit.") -- Shurui Liu (Aaron Liu) Computer Science & Engineering Technology University of Toledo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] command error help
"Shurui Liu (Aaron Liu)" wrote SyntaxError: EOL while scanning single-quoted string. Yes, that sounds about right. But it doesn't add much. Can you print the entifre error message not just that single line? Or Here is a program I need to run in putty.exe, but there is an error in it. I cannot find out. When I ran this program, it mentions that the error is in red line. How are you running the code in putty. I don't get any red lines in my terminal... It suggests you might be using some other tool or IDE perhaps? Since I can't see any single quoted strings in your code we can't begin to guess what line the error pertains to. It might for example be one of the apostraphes thats causing the error? name = raw_input("Hi. What's your name? ") age = raw_input("And how old are you? ") age = int(age) weight = raw_input("Okay, last question. How many pounds do you weigh? ") weight = int(weight) print "\nIf poet ee cummings were to email you, he'd address you as", name.lower() ee_mad = name.upper() print "But if ee were mad, he'd call you", ee_mad dog_years = age / 7 print "\nDid you know that you're just", dog_years, "in dog years?" seconds = age * 365 * 24 * 60 * 60 print "But you're also over", seconds, "seconds old." called = name * 5 print "\nIf a small child were trying to get your attention, " \ "your name would become:" print called moon_weight = weight / 6.0 print "\nDid you know that on the moon you would weigh only", moon_weight, "pounds?" sun_weight = weight * 27.1 print "But on the sun, you'd weigh", sun_weight, "(but, ah... not for long)." raw_input("\n\nPress the enter key to exit.") -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting caller name without the help of"sys._getframe(1).f_code.co_name" ?
"patrice laporte" wrote Maybe the fact I'm à pure C coder for a longtime prevent me from thinking in Python, ... And now, something different : what I want to do, and why. Based on that last line I think your brain is well on the way to thinking like a Python programmer! :-) Others have addressed your main issues. Alan G ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] try MySQLdb Error
Hi. I want to catch MySQL error. This is my code. #!/usr/bin/env python #-*- coding:utf-8 -*- # Copyright 2009 Grigor Kolev # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. from time import sleep from time import localtime import MySQLdb, sys #-- class Config (): '''Това е основен клас всички други са негови подкласове. Този клас зарежда данните от конфигурационния файл. Премахва коментарите. Изгражда променливите с данните от конфигурацията. Тези данни се използват във всички останали класове.''' def __init__(self, config_file = 'mail_list.conf'): self.config = open(config_file, 'r') # Отваря cinfif файла за четене. self.config = self.config.readlines() # Прочита файла. try: b = 0 # Брояч while 1: if self.config[b][0] == '#': # Индексира списъка получен при четенето del self.config[b] # на conf файла. Ако ред започва с # self.config[b] = self.config[b][:-1] else: # го изтрива от списъка. b+=1 except IndexError: # Прихваща грешката получена при край pass # на файла и продължава с изпълнението. try: self.db_root_pass = self.config[0][5:] # Взема паролата на root за базата except MySQLdb.DatabaseError: raise Error, 'OperationalError: Достъп отказан. Невалидна root парола за базата' sys.exit() self.db_host = self.config[1][5:] self.work_user_name = self.config[2][5:] self.work_user_pass = self.config[3][5:] #-- class Error (Exception): '''Класа обхваща някой от възможните грешки и ги записва във лог файл.''' def __init__(self, values): self.values = values # Приема грешката дадена при повдигане на изключение. self.write_in_log() # Изпълнява функцията за записване в лог файла. def error_time(self): # Получава времето на генериране на грешката. '''Получава времето на генериране на изключението и оформя данните за запис.''' self.date = str(localtime()[2]), str(localtime()[1]), str(localtime()[0]) # Оформя self.time = str(localtime()[3]), str(localtime()[4:]) # за запис. def write_in_log(self): '''Записва времето на генериране на грешката и самата грешка във лог файл''' self.error_time() # Изпълнява функцията за получаване на времето. self.values ='[%s-%s-%s]-->[%s:%s] %s\n' % (self.date[0], self.date[1], self.date[2], self.time[0], self.time[1], self.values) # Оформя получените данни. try: log_file = open('error.log', 'a') # Отваря лог файла. except IOError: # При липса на лог log_file = file('error.log', 'w') # го създава. log_file.write(self.values) # Запис. log_file.close() # Затваря лога. #-- class SQL (Config): '''Създаване на базата данни. Създава таблицата. Създава работен потребител с ограничени права. Осъществява връзка с базата''' def create_db(self ): #Създаване на базата данни. '''Създава базата данни и таблицата където ще се записва''' connect = MySQLdb.connect(host=self.db_host, user='root', passwd=self.db_root_pass) # Връзка с базата create = connect.cursor() # Отваря базата create.execute('''CREATE DATABASE IF NOT EXISTS site_db;''') # Изпълнява командата подадена към базата create.execute('''CREATE TABLE IF NOT EXISTS `site_db`.`user_list` ( `ID` INT NOT NULL AUTO_INCREMENT, `E-mail` VARCHAR(100) , `Name` VARCHAR(100) , `Skill` VARCHAR(200) , `Pic` VARCHAR(100) , PRIMARY KEY (`ID`) ) ENGINE = MyISAM CHARACTER SET utf8 COLLATE utf8_general_ci;''') def create_db_work_user(self): # Създава работен потребител с ограничени права. '''Създава работен потребител с ограничени права.''' connect = MySQLdb.connect(host=self.db_host, user='root', passwd=self.db_root_pass, db='site_db') # Взима паролата и хоста от cong файла user_create = connect.cursor() try: user = '''CREATE USER '%s'@'localhost' IDENTIFIED BY
[Tutor] A Stuborn Tab Problem in IDLE
When I use F5 to execute a py program in IDLE, Win7, I get a tab error on an indented else. I've selected all and untabifed with 4 spaces several times, and get the same problem. I've tried re-typing the line with zero results. What next? I had been modifying the program repeatedly over several hours, and executing it without any trouble like this. -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A Stuborn Tab Problem in IDLE
On Mon, 15 Feb 2010 09:19:35 am Wayne Watson wrote: > When I use F5 to execute a py program in IDLE, Win7, I get a tab > error on an indented else. I've selected all and untabifed with 4 > spaces several times, and get the same problem. I've tried re-typing > the line with zero results. What next? I had been modifying the > program repeatedly over several hours, and executing it without any > trouble like this. Can you copy and paste the exact error message displayed? -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
tutor@python.org
On Sun, 14 Feb 2010 08:16:18 pm Alan Gauld wrote: > >> But glitches can occur from time to time... > > > > If Python had a glitch of the magnitude of right-shifting non-zero > > bits into a number, that would be not just a bug but a HUGE bug. > > Bit shifting is machine specific. Pardon me, but that's incorrect. Python is not assembly, or C, and the behaviour of bit shifting in Python is NOT machine specific. Python doesn't merely expose the native bit shift operations on native ints, it is a high-level object-oriented method with carefully defined semantics. http://docs.python.org/library/stdtypes.html#bit-string-operations-on-integer-types In Python, a left shift of n MUST return the equivalent of multiplication by 2**n, and a right shift MUST return the equivalent of integer division by 2**n. Any other result is a SERIOUS bug in Python of the same magnitude (and the same likelihood) as 10/2 returning 18. So while I bow to your knowledge of bit operations in assembler on obscure four bit processors, Python does not do that. (I'm not even sure if Python runs on any four bit CPUs!) Python is a high-level language, not an assembler, and the behaviour of the bit operators >> and << is guaranteed to be the same no matter what CPU you are using. (The only low-level ops that Python exposes are floating point ops: Python mostly does whatever the C library on your platform does.) > > It is certainly good practice if you are dealing with numbers which > > might be more than 24 bits to start with: > > Its more than good practice there, its essential. Hardly. There are other ways of truncating a number to 8 bits, e.g. by using n % 256. If you're dealing with signed numbers, using & 255 will throw away the sign bit, which may be undesirable. And of course, it isn't desirable (let alone essential) to truncate the number if you don't need an 8 bit number in the first place! [and discussing the case where you know your input is already 8 bits] > In the case in point the & 255 keeps the coding style consistent > and provides an extra measure of protection against unexpected > oddities so I would keep it in there. So you add unnecessary operations to be consistent? That's terrible practice. So if you have an operation like this: n = 12*i**3 + 7 and later on, you then want n = i+1, do you write: n = 1*i**1 + 1 instead to be "consistent"? I would hope not! > > cycles and needlessly complicating the code. The right way to guard > > against "this will never happen" scenarios is with assert: > > > > assert n.bit_length() <= 32 # or "assert 0 <= n < 2**32" > > I would accept the second condition but the mask is much faster. Premature (micro) optimizations is the root of all evil. An assert that can be turned off and not executed is infinitely faster than a bit shift which is always executed whether you want it or not. And either way, the 20 seconds I lose trying to interpret the bit ops when I read the code is far more important than the 0.01 seconds I lose executing the assert :) > bit_length doesn't seem to work on any of my Pythons (2.5,2.6 and > 3.1) It won't work in 2.5 or 2.6. You're probably trying this: 123.bit_length() and getting a syntax error. That's because the Python parser sees the . and interprets it as a float, and 123.bit_length is not a valid decimal float. You need to either group the int, or refer to it by name: (123).bit_length() n = 123 n.bit_length() -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A Stuborn Tab Problem in IDLE
I'm not sure it's postable or attachable for this mail list. I'll give it a try. Attachments do work with other lists. On 2/14/2010 2:51 PM, Steven D'Aprano wrote: On Mon, 15 Feb 2010 09:19:35 am Wayne Watson wrote: When I use F5 to execute a py program in IDLE, Win7, I get a tab error on an indented else. I've selected all and untabifed with 4 spaces several times, and get the same problem. I've tried re-typing the line with zero results. What next? I had been modifying the program repeatedly over several hours, and executing it without any trouble like this. Can you copy and paste the exact error message displayed? -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
tutor@python.org
"Steven D'Aprano" wrote Pardon me, but that's incorrect. Python is not assembly, or C, and the behaviour of bit shifting in Python is NOT machine specific. http://docs.python.org/library/stdtypes.html#bit-string-operations-on-integer-types In Python, a left shift of n MUST return the equivalent of multiplication by 2**n, and a right shift MUST return the equivalent of integer division by 2**n. Any other result is a SERIOUS bug in Python So it seems, I apologise, I had assumed that for bit shifting Python did indeed just pass it down to the C compiler which in turn passes it to the CPU. As someone who works a lot at the CPU level that's slightly dissappointing since it makes bit shifting predictable but unreliable from my perspective - I can't guarantee the effect on the CPU... But since it's never actually caused me a problem I won't lose sleep over it. So while I bow to your knowledge of bit operations in assembler on obscure four bit processors, I haven't used 4 bit CPUs since working on the millenium bug ~10 years ago but the same applies in higher order processors too. I only used a 4 bit CPU since you gave a 4 bit example. But given the above it's irrelevant, the language defines the behaviour and I was wrong about that. Python does not do that. (I'm not even sure if Python runs on any four bit CPUs!) Probably not but it does run on some 8 bit ones. > It is certainly good practice if you are dealing with numbers which > might be more than 24 bits to start with: Its more than good practice there, its essential. Hardly. There are other ways of truncating a number to 8 bits I meant the truncating was needed not the & mechanism. [and discussing the case where you know your input is already 8 bits] In the case in point the & 255 keeps the coding style consistent and provides an extra measure of protection against unexpected oddities so I would keep it in there. So you add unnecessary operations to be consistent? That's terrible practice. No but I don't mix two styles of guard. If I need a guard and I'm already using masks then I'll use a mask, I certainly wouldn't mix asserts and masks for similar functions. If I'm sure I don't need the guard then I definitely wouldn't add one just for consistency of style. So if you have an operation like this: n = 12*i**3 + 7 and later on, you then want n = i+1, do you write: n = 1*i**1 + 1 No I'd write n = i+1 rather than n = lambda x: x+1(i) or even (if Python had such an incr function) n = incr(i) since the arithmetic version is more consistent that the function call or the lambda. > cycles and needlessly complicating the code. The right way to guard > against "this will never happen" scenarios is with assert: > > assert n.bit_length() <= 32 # or "assert 0 <= n < 2**32" I would accept the second condition but the mask is much faster. Premature (micro) optimizations is the root of all evil. An assert that can be turned off and not executed is infinitely faster than a bit shift which is always executed whether you want it or not. But I did want it :-) And either way, the 20 seconds I lose trying to interpret the bit ops when I read the code is far more important than the 0.01 seconds I lose executing the assert :) Ah, but to me bit ops are normal code so I don't lose time reading them. In fact I'd take longer to figure out the assert. Readability is all about idioms and if you do a lot of bit tweaking masking is the normal idiom. (The only difference is that I would have used hex rather than decimal numbers for the masks - because I read bit patterns in hex faster than in decimal) bit_length doesn't seem to work on any of my Pythons (2.5,2.6 and 3.1) It won't work in 2.5 or 2.6. You're probably trying this: 123.bit_length() Indeed, I tried using a variable and it worked. Thanks for that I hadn't come across bit_length() before. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A Stuborn Tab Problem in IDLE
"Wayne Watson" wrote When I use F5 to execute a py program in IDLE, Win7, I get a tab error on an indented else. What happens if you execute from a command line? Do you get the same error? If so look at the lines before. If not try closing and restarting IDLE HTH, Alan G ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A Stuborn Tab Problem in IDLE
I rebooted, and no change. I saved it under a new name, and no change. I tried to activate it as a file, and it put up a screen and down that I had no chance to read it. Since I have been on W7 for a month, have no clue as how to run it from a command line. I'll check with help, and report back. Maybe stuffing it in a txt file with NotePad might reveal something. On 2/14/2010 5:05 PM, Alan Gauld wrote: "Wayne Watson" wrote When I use F5 to execute a py program in IDLE, Win7, I get a tab error on an indented else. What happens if you execute from a command line? Do you get the same error? If so look at the lines before. If not try closing and restarting IDLE HTH, Alan G ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A Stuborn Tab Problem in IDLE
Well, command line was easy to get to. It's on the menu for python, but it gives me >>>. How do I get to the folder with the py file? Can I switch to a c:\ type operation? Back to exploring. On 2/14/2010 5:05 PM, Alan Gauld wrote: "Wayne Watson" wrote When I use F5 to execute a py program in IDLE, Win7, I get a tab error on an indented else. What happens if you execute from a command line? Do you get the same error? If so look at the lines before. If not try closing and restarting IDLE HTH, Alan G ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A Stuborn Tab Problem in IDLE
I got to the dos command line facility and got to the file. I executed the program, and it failed with a syntax error. I can't copy it out of the window to paste here, but here's the code surrounding the problem: (arrow ==> points at the problem. The console code shows [ missing. I SEE the syntax error. It's two lines above the line with the arrow. The code now works. Thanks very much. Console wins again! (I suspect you are not into matplotlib, but the plot requires a list for x and y in plot(x,y). xy[0,0] turns out to be a float64, which the syntax rejects. I put [] around it, and it works. Is there a better way? ax1.plot([xy[0,0]],[xy[0,1]],'gs') if npts == 90: # exactly 90 frames ax1.plot([xy[npts-1,0]], xy[npts-1,1]],'rs') # mark it is a last frame else: ax1.plot([xy[npts-1,0]], ==>[xy[npts-1,1]],'ys') # mark 90th frame in path last_pt = len(xy[:,0]) ax1.plot([xy[npts-1,0]],[xy[npts-1,1]],'rs') On 2/14/2010 6:18 PM, Wayne Watson wrote: Well, command line was easy to get to. It's on the menu for python, but it gives me >>>. How do I get to the folder with the py file? Can I switch to a c:\ type operation? Back to exploring. On 2/14/2010 5:05 PM, Alan Gauld wrote: "Wayne Watson" wrote When I use F5 to execute a py program in IDLE, Win7, I get a tab error on an indented else. What happens if you execute from a command line? Do you get the same error? If so look at the lines before. If not try closing and restarting IDLE HTH, Alan G ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A Stuborn Tab Problem in IDLE
Wayne Watson wrote: I got to the dos command line facility and got to the file. I executed the program, and it failed with a syntax error. I can't copy it out of the window to paste here, but here's the code surrounding the problem: (arrow ==> points at the problem. The console code shows [ missing. I SEE the syntax error. It's two lines above the line with the arrow. The code now works. Thanks very much. Console wins again! (I suspect you are not into matplotlib, but the plot requires a list for x and y in plot(x,y). xy[0,0] turns out to be a float64, which the syntax rejects. I put [] around it, and it works. Is there a better way? ax1.plot([xy[0,0]],[xy[0,1]],'gs') if npts == 90: # exactly 90 frames ax1.plot([xy[npts-1,0]], xy[npts-1,1]],'rs') # mark it is a last frame else: ax1.plot([xy[npts-1,0]], ==>[xy[npts-1,1]],'ys') # mark 90th frame in path last_pt = len(xy[:,0]) ax1.plot([xy[npts-1,0]],[xy[npts-1,1]],'rs') On 2/14/2010 6:18 PM, Wayne Watson wrote: Well, command line was easy to get to. It's on the menu for python, but it gives me >>>. How do I get to the folder with the py file? Can I switch to a c:\ type operation? Back to exploring. On 2/14/2010 5:05 PM, Alan Gauld wrote: "Wayne Watson" wrote When I use F5 to execute a py program in IDLE, Win7, I get a tab error on an indented else. What happens if you execute from a command line? Do you get the same error? If so look at the lines before. If not try closing and restarting IDLE HTH, Alan G Once you've discovered the DOS box, you should also discover QuickEdit mode. In the DOS box, right click on the title bar, and choose "Properties". First tab is Options. Enable Quick-Edit mode, and press OK. Now, you can drag a rectangle on the DOS box, and use right click to paste it to the clipboard. Practice a bit and you'll find it easy. An essential tool. DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A Stuborn Tab Problem in IDLE
Thanks for the reminder on that. I haven't need the DOS box for 8 months. Just off on other non-programming efforts for the most part. Things have picked up of late. I was beginning to think for awhile that Win7 might have dropped it. I don't see any changes to it. On 2/14/2010 7:01 PM, Dave Angel wrote: Wayne Watson wrote: I got to the dos command line facility and got to the file. I executed the program, and it failed with a syntax error. I can't copy it out of the window to paste here, "Wayne Watson" wrote When I use F5 to execute a py program in IDLE, Win7, I get a tab error on an indented else. What happens if you execute from a command line? Do you get the same error? If so look at the lines before. If not try closing and restarting IDLE HTH, Alan G Once you've discovered the DOS box, you should also discover QuickEdit mode. In the DOS box, right click on the title bar, and choose "Properties". First tab is Options. Enable Quick-Edit mode, and press OK. Now, you can drag a rectangle on the DOS box, and use right click to paste it to the clipboard. Practice a bit and you'll find it easy. An essential tool. DaveA -- "Crime is way down. War is declining. And that's far from the good news." -- Steven Pinker (and other sources) Why is this true, but yet the media says otherwise? The media knows very well how to manipulate us (see limbic, emotion, $$). -- WTW ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor