Re: TypeError not caught by except statement
On 2010-1-25 16:35, siddu wrote: Hi, except not able to caught the TypeError exception occured in the below code log.info(refer,ret) in the try block throws a TypeError which is not caught . Also sometimes process is getting hanged. import logging log = logging.getLogger() fileName = strftime(%d-%b-%Y-, gmtime()) + str(int(time.time())) + - Log.log log = logging.getLogger() log.setLevel(logging.NOTSET) fh = logging.FileHandler(logFile) logFileLevel = logging.DEBUG fh.setLevel(logFileLevel) format_string = '%(process)d %(thread)d %(asctime)-15s %(levelname)-5s at %(filename)-15s in %(funcName)-10s at line %(lineno)-3d %(message) s' fh.setFormatter(logging.Formatter(format_string)) log.addHandler(fh) try: log.info(start) log.info(refer,ret) ~~~ Seems this line causes the exception, and it is handled inside log.info(), which prints those traceback info. Usually log.info(msg, args) raises the same exception as print(msg%args). log.info(end) except TypeError: log.exception(Exception raised) -- OUTPUT message: Traceback (most recent call last): File C:\Python26\lib\logging\__init__.py, line 768, in emit msg = self.format(record) File C:\Python26\lib\logging\__init__.py, line 648, in format return fmt.format(record) File C:\Python26\lib\logging\__init__.py, line 436, in format record.message = record.getMessage() File C:\Python26\lib\logging\__init__.py, line 306, in getMessage msg = msg % self.args TypeError: not all arguments converted during string formatting -- http://mail.python.org/mailman/listinfo/python-list
Re: How to test if a file is a symbolic link?
On 2009-10-29 11:19, Peng Yu wrote: 'symbolic_link' is a symbolic link in the current directory. I run 'python main.py', but it does not return me anything. I want to check if a file is a symbolic link. I'm wondering what is the correct way to do so? $cat main.py import stat import os st = os.stat('symbolic_link') if stat.S_ISLNK(st.st_mode): print Hello Use os.lstat instead of os.stat to prevent following symbolic links. Or more directly, use os.path.islink() -- http://mail.python.org/mailman/listinfo/python-list
Re: unexplainable python
dads 写道: ... enter number: 34567 _5digit function used 34 before sent to _2digit 34 slice when at _2digit function 34 before sent to plus_ten function 7 slice when at _2digit function This is the point. _2digit() only gets 1 digit(7) and needs accessing the second byte in: var = self.plus_ten[n[0]+'0'] + ' ' + self._1digit(n[1]) 7 before sent to plus_ten function ... from __future__ import print_function import sys class number(object): def _5digit(self, n): print(n[:2],'before sent to _2digit') var = self._2digit(n[:2]) + ' thousand ' + self._4digit(n[2:]) You passed the last 3 digits to _4digit function. return var class control(object): def __init__(self): pass def data_input(self): while True: i = raw_input('enter number: ') if i == 's': break #try: n = number(i) #except: #print('not a number') if __name__ in '__main__': c = control() c.data_input() -- http://mail.python.org/mailman/listinfo/python-list
Re: Remove empty strings from list
Chris Rebert 写道: On Mon, Sep 14, 2009 at 6:49 PM, Helvin helvin...@gmail.com wrote: Hi, Sorry I did not want to bother the group, but I really do not understand this seeming trivial problem. I am reading from a textfile, where each line has 2 values, with spaces before and between the values. I would like to read in these values, but of course, I don't want the whitespaces between them. I have looked at documentation, and how strings and lists work, but I cannot understand the behaviour of the following: line = f.readline() line = line.lstrip() # take away whitespace at the beginning of the readline. list = line.split(' ') # split the str line into a list # the list has empty strings in it, so now, remove these empty strings for item in list: if item is ' ': print 'discard these: ',item index = list.index(item) del list[index] # remove this item from the list else: print 'keep this: ',item The problem is, when my list is : ['44', '', '', '', '', '', '0.0\n'] The output is: len of list: 7 keep this: 44 discard these: discard these: discard these: So finally the list is: ['44', '', '', '0.0\n'] The code above removes all the empty strings in the middle, all except two. My code seems to miss two of the empty strings. Would you know why this is occuring? Block quoting from http://effbot.org/zone/python-list.htm Note that the for-in statement maintains an internal index, which is incremented for each loop iteration. This means that if you modify the list you’re looping over, the indexes will get out of sync, and you may end up skipping over items, or process the same item multiple times. Thus why your code is skipping over some elements and not removing them. Moral: Don't modify a list while iterating over it. Use the loop to create a separate, new list from the old one instead. or use filter list=filter(lambda x: len(x)0, list) Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Remove empty strings from list
Helvin 写道: Hi, Sorry I did not want to bother the group, but I really do not understand this seeming trivial problem. I am reading from a textfile, where each line has 2 values, with spaces before and between the values. I would like to read in these values, but of course, I don't want the whitespaces between them. I have looked at documentation, and how strings and lists work, but I cannot understand the behaviour of the following: line = f.readline() line = line.lstrip() # take away whitespace at the beginning of the readline. list = line.split(' ') # split the str line into a list # the list has empty strings in it, so now, remove these empty strings for item in list: if item is ' ': print 'discard these: ',item index = list.index(item) del list[index] # remove this item from the list else: print 'keep this: ',item The problem is, when my list is : ['44', '', '', '', '', '', '0.0\n'] The output is: len of list: 7 keep this: 44 discard these: discard these: discard these: So finally the list is: ['44', '', '', '0.0\n'] The code above removes all the empty strings in the middle, all except two. My code seems to miss two of the empty strings. Would you know why this is occuring? Regards, Helvin You can use the default argument of split: list = line.split() From the python documentation, If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed). So it is suitable for most cases without introduce empty strings. -- http://mail.python.org/mailman/listinfo/python-list
Re: s.index(x[, i[, j]]) will change the s ?
s7v7nislands 写道: Thanks for your reply! Sorry for my poor english! On Sep 10, 12:33 pm, Chris Rebert c...@rebertia.com wrote: On Wed, Sep 9, 2009 at 9:00 PM, s7v7nislandss7v7nisla...@gmail.com wrote: hi all: what is the s.index() mean? does the index() change the s? It tells you the index of the first instance of the given element in the sequence. Or, to quote the docs: s.index(x[, i[, j]]) --- return smallest k such that s[k] == x and i = k j No, .index() does not modify the sequence itself. I known index() does not modify the sequence itself. my question is so why the doc put the index() method in the mutable sequence types list? It applies to both mutable and immutable sequence. In python2.6 doc (6.6.4. Mutable Sequence Types), Note 4: Raises ValueError when x is not found in s. When a negative index is passed as the second or third parameter to the index() method, the list length is added, as for slice indices. If it is still negative, it is truncated to zero, as for slice indices. Changed in version 2.3: Previously, index() didn’t have arguments for specifying start and stop positions. Nothing in the above says anything about modifying a sequence... When a negative index is passed as the second or third parameter to the index() method, the list length is added, as for slice indices. I don't understand the mean. the list length is added, why? if it changed, the original will change ? It is just the common rule for negative index. eg. s[-k] == s[-k + len(s)]. The original sequence is not changed. who can give a example? and why the s.remove() also point to note 4? Because it has the same behavior when the item is not present in the sequence. Examples using lists: assert [c, a, b, c, c].index(c, 1) == 3 try: [a, b].index(c) except ValueError: print 'c' was not in the list else: raise RuntimeError, Should never get here x = [a, b, c] x.remove(b) assert len(x) == 2 and x[0] == a and x[1] == c I want a example, maybe: use the a negative index is passed as the second or third parameter, and see the length changed. x = 'abcde' x.index('d', -3, -1) = x.index('d', 2, 4) = 3 x.index('a', -3, -1) = x.index('a', 2, 4) = -1, raise ValueError Is the document wrong? No. What made you think so? Sorry for my poor english. do you understand me now? thanks! Cheers, Chris --http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list