[Tutor] Apparent incosistency with Python interperter in IDLE
I am an experienced C/C++/C# programmer who is just starting out with Python. My first attempt at IDLE worked great with the tutorial, but seems to have a problem with my first real app! I am trying to get the Python subprocess/Popen module working with the example from the Python 3 documentation page: import subprocess subprocess.call('ls') ArchiveFirefox_wallpaper.png result.txt ... which is what I expect. However this same input to the IDLE Python Shell yields: Python 3.0.1+ (r301:69556, Apr 15 2009, 15:59:22) [GCC 4.3.3] on linux2 Type copyright, credits or license() for more information. No Subprocess import subprocess subprocess.call('ls') 0 Which appears to be merely the return code, not the stdout! It looks like I need to set some variable in IDLE, but I can't figure out exactly what is needed here. Can anyone point me to an answer? Karen ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Apparent incosistency with Python interperter in IDLE
Karen Palen wrote: Which appears to be merely the return code, not the stdout! It looks like I need to set some variable in IDLE, but I can't figure out exactly what is needed here. Can anyone point me to an answer? Well, Karen, according to my IDLE (admittedly it's 2.6 not 3.0 so it may not agree), call only returns the return code. You can check on your system by doing the following: IDLE 2.6.2 import subprocess help(subprocess.call) which will print out the docstring for the method: Help on function call in module subprocess: call(*popenargs, **kwargs) Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call([ls, -l]) I believe what's happening is that you are confused about the presence of STDOUT in IDLE. In a normal console window, when you call a program (such as ls), stdout is directed at the screen (the console window.) So what's happening in the first example (the non-idle one) is: open subprocess and execute an ls call - the subprocess prints out the result of the ls call -subprocess finishes process finishes Now the key here is that in this case, both of these have the same stdout (the screen), which is the default stdout. However, when you run from an IDLE prompt, your stdout is not going to be the default. check it out if you want: import sys print sys.stdout idlelib.rpc.RPCProxy object at 0x01198F90 Notice that this is not a standard stdout. In a normal Python window, import sys print sys.stdout open file 'stdout', mode 'w' at 0x00A43070 it's not the same stdout as IDLE has. So what's happening when you run the command from IDLE: open subprocess and execute an ls call -subprocess starts, executes ls, prints result to _its_ stdout (which is not IDLE's stdout, remember!) -subprocess executes, output goes bye bye your process ends as well So the problem is that the stdout of the ls command is appearing in some location that you cannot see. As for ways to remedy this - I don't know. The idea here, though, is that even though the regular Python version has the side-effect that it outputs it in the console, that's not necessarily what you want it to do. The reason is that you have no way to access that data. Also you mentioned that IDLE prints out a 0. This is only something that IDLE's interpreter does. For example x = hello x 'hello' IDLE echoes the value of x. However, if you had the code x = hello x and you ran it (not in IDLE's interpreter) you would not get any output. What you should learn from this is 1- IDLE is weird in many ways 2 - that subprocess.call() is not meant to get data back from a call (look at subprocess.Popen and its communicate() method for that) 3 - sometimes things that appear to be outputs are side-effects/artifacts of the environment you're running them in and can't be depended upon. HTH, -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fast way to access items in a dictionary
Elisha Rosensweig bensha...@gmail.com wrote if 'someKey' in dict.keys(): someData = dict['someKey'] is there a faster way to do this? Faster in terms of execution speed? Sure just miss out the test... accessing a key that does not exist will through an exception, which is just as tiresome... Tiresome means more code? but its a lot faster in execution time since it only affects the result when you have an error. (Assuming you hit more often than you miss!) But you can also use get() which will not throw an exception and you can provide a default return value for the times you miss d = {1:7,2:9,3:12} d.get(2,-1) 9 d.get(12,-1) -1 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] please help me
to every one help me please .. i need the code to do chatting by python in mobiles over bluetooth technology .. i need it please if any one know it send it to me as soon as possible.. thanks for all. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] variable within function retains value
On Thu, Jun 18, 2009 at 6:21 AM, karmadorjeta...@googlemail.com wrote: Hi All, I'm trying to write a function that flattens a list. However after I call the function more than once, it appends the result (a list) from the second call with the first. I can get around it by either setting the list to an empty one before calling the function, but I would like to keep it in the function, another alternative I found was to pass an empty list as an argument. Can someone explain how python keeps track of variables within functions (I was expecting the variable to be destroyed after a value was returned). Also what is a better way to handle this? Default arguments are only evaluated once, when the function is compiled, so the start list is shared between invocations of flatten. This is a FAQ: http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm Another solution - it's easy to rewrite flatten() so it doesnt' need a default argument: In [1]: def flatten(myList): ...: start = [] ...: for i in myList: ...: if type(i) != list: ...: start.append(i) ...: else: ...: start.extend(flatten(i)) ...: return start Kent PS Please don't quote unrelated questions when posting. Thanks def flatten(myList,start=[]): Flatten nested lists flatten([1,[2,[3,4],5]],[]) [1, 2, 3, 4, 5] for i in myList: if type(i) != list: start.append(i) else: flatten(i,start) return start flatten([1,[2,[3,4],5]]) [1, 2, 3, 4, 5] flatten([1,[2,[3,4],5]]) [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] flatten([1,[2,[3,4],5]],[]) [1, 2, 3, 4, 5] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] variable within function retains value
Excellent, thanks for that answer Kent. Also thanks for the link 2009/6/18 Kent Johnson ken...@tds.net: On Thu, Jun 18, 2009 at 6:21 AM, karmadorjeta...@googlemail.com wrote: Hi All, I'm trying to write a function that flattens a list. However after I call the function more than once, it appends the result (a list) from the second call with the first. I can get around it by either setting the list to an empty one before calling the function, but I would like to keep it in the function, another alternative I found was to pass an empty list as an argument. Can someone explain how python keeps track of variables within functions (I was expecting the variable to be destroyed after a value was returned). Also what is a better way to handle this? Default arguments are only evaluated once, when the function is compiled, so the start list is shared between invocations of flatten. This is a FAQ: http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm Another solution - it's easy to rewrite flatten() so it doesnt' need a default argument: In [1]: def flatten(myList): ...: start = [] ...: for i in myList: ...: if type(i) != list: ...: start.append(i) ...: else: ...: start.extend(flatten(i)) ...: return start Kent PS Please don't quote unrelated questions when posting. Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] converting encoded symbols from rss feed?
Some further searching reveals this: (yay archives ;)) http://mail.python.org/pipermail/python-list/2008-April/658644.html Aha! I noticed that 150 was missing from the ISO encoding table and the source xml is indeed using windows-1252 encoding. That explains why this appears to be the only character in the xml source that doesn't seem to get translated by Universal Feed Parser. But I'm now wondering if the feed parser is using windows-1252 rather than some other encoding. The below page provides details on how UFP handles character encodings. http://www.feedparser.org/docs/character-encoding.html I'm wondering if there's a way to figure out which encoding UFP uses when it parses the file. I didn't have the Universal Encoding Detector (http://chardet.feedparser.org/) installed when I parsed the xml file. It's not clear to me whether UFP requires that library to detect the encoding or if it's an optional part of it's broader routine for determining encoding. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Eliminating consecutive duplicates in a list
I was playing around with eliminating duplicates in a list not using groupby. From the two solutions below, which is more pythonic. Alternative solutions would be welcome. Thanks x=[1,1,1,3,2,2,2,2,4,4] [v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0] [x[i] for i in range(len(x)-1) if i==0 or x[i]!=x[i-1]] output: [1, 3, 2, 4] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Eliminating consecutive duplicates in a list
This might help: http://code.activestate.com/recipes/52560/ Robert On Thu, 2009-06-18 at 15:15 +0200, karma wrote: I was playing around with eliminating duplicates in a list not using groupby. From the two solutions below, which is more pythonic. Alternative solutions would be welcome. Thanks x=[1,1,1,3,2,2,2,2,4,4] [v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0] [x[i] for i in range(len(x)-1) if i==0 or x[i]!=x[i-1]] output: [1, 3, 2, 4] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Eliminating consecutive duplicates in a list
Hi Robert, Thanks for the link. However, I am looking for eliminating consecutive duplicates rather than all duplicates - my example wasn't clear, apologies for that. x=[1,1,1,3,2,2,2,4,4,2,2] [1 ,3 ,2 ,4 ,2 ] 2009/6/18 Robert Berman berma...@cfl.rr.com: This might help: http://code.activestate.com/recipes/52560/ Robert On Thu, 2009-06-18 at 15:15 +0200, karma wrote: I was playing around with eliminating duplicates in a list not using groupby. From the two solutions below, which is more pythonic. Alternative solutions would be welcome. Thanks x=[1,1,1,3,2,2,2,2,4,4] [v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0] [x[i] for i in range(len(x)-1) if i==0 or x[i]!=x[i-1]] output: [1, 3, 2, 4] ___ Tutor maillist - tu...@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Program Slicing / Trace
Hi Tutor The problem i have is to see which statements modify my data at execution time without referring to the code. Referring to the code is difficult esp because of branching. You can never tell before hand which branch execution will follow. e.g in the example below, statements 1, 2, 5,7 and 10 modify my data and are the ones i would like to trace during run time. However the other statements do not change my data so am not interested in them. How can this be achieved during execution? Not sure if the traceback module can be helpful here! Cheers Jojo. === def myfunction(): 1.num1= 20 #statement 1 2.num2 = 30 #statement 2 3.somelist= [ ] #statement 3 4.if (num1 num2): 5. num2 = num2 * 20 #statement 3 6.else: 7 num2 = num1 + num2 #statement 3 8.mylist = [num1, num2] #statement 4 9.for items in mylist: 10. somelist.append( math.sqrt(item) + math.log(item)) #statement 5 11. return somelist ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] please help me
On 6/18/2009 1:30 AM suzee Eslam said... to every one help me please .. i need the code to do chatting by python in mobiles over bluetooth technology .. i need it please if any one know it send it to me as soon as possible.. thanks for all. Maybe this will get you started... http://www.mobilenin.com/mobilepythonbook/examples/057-btchat.html Emile ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Program Slicing / Trace
It is not clear to me in what way line 3 is different than line 2 - both are assignments... Please clarify Elisha On Thu, Jun 18, 2009 at 10:37 AM, Jojo Mwebaze jojo.mweb...@gmail.comwrote: Hi Tutor The problem i have is to see which statements modify my data at execution time without referring to the code. Referring to the code is difficult esp because of branching. You can never tell before hand which branch execution will follow. e.g in the example below, statements 1, 2, 5,7 and 10 modify my data and are the ones i would like to trace during run time. However the other statements do not change my data so am not interested in them. How can this be achieved during execution? Not sure if the traceback module can be helpful here! Cheers Jojo. === def myfunction(): 1.num1= 20 #statement 1 2.num2 = 30 #statement 2 3.somelist= [ ] #statement 3 4.if (num1 num2): 5. num2 = num2 * 20 #statement 3 6.else: 7 num2 = num1 + num2 #statement 3 8.mylist = [num1, num2] #statement 4 9.for items in mylist: 10. somelist.append( math.sqrt(item) + math.log(item)) #statement 5 11. return somelist ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Program Slicing / Trace
On 6/18/2009 7:37 AM Jojo Mwebaze said... Hi Tutor The problem i have is to see which statements modify my data at execution time without referring to the code. Referring to the code is difficult esp because of branching. You can never tell before hand which branch execution will follow. e.g in the example below, statements 1, 2, 5,7 and 10 modify my data and are the ones i would like to trace during run time. However the other statements do not change my data so am not interested in them. How can this be achieved during execution? I think most of us will litter print statements through the code to track where something changes, then remove them once we're done. Sometimes I'll set a DEBUG variable or dict. I also use pdb as needed, eg import pdb; pdb.set_trace() Emile Not sure if the traceback module can be helpful here! Cheers Jojo. === def myfunction(): 1.num1= 20 #statement 1 2.num2 = 30 #statement 2 3.somelist= [ ] #statement 3 4.if (num1 num2): 5. num2 = num2 * 20 #statement 3 6.else: 7 num2 = num1 + num2 #statement 3 8.mylist = [num1, num2] #statement 4 9.for items in mylist: 10. somelist.append( math.sqrt(item) + math.log(item)) #statement 5 11. return somelist ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Eliminating consecutive duplicates in a list
On 6/18/2009 7:23 AM karma said... Hi Robert, Thanks for the link. However, I am looking for eliminating consecutive duplicates rather than all duplicates - my example wasn't clear, apologies for that. x=[1,1,1,3,2,2,2,4,4,2,2] [1 ,3 ,2 ,4 ,2 ] Something like [ ii for ii,jj in zip(x,x[1:]+[-1]) if jj != ii] Emile ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Eliminating consecutive duplicates in a list
Whoops. That's called assuming what I read is really what I see. A good lesson in reading questions twice. I remember this from a post some time back and I remember having been intrigued by it. I used Google, and since I tend to keep extensive notes, the solution I found is not uniquely mine, but it does work. http://wasstock.com/?p=12 Robert On Thu, 2009-06-18 at 16:23 +0200, karma wrote: Hi Robert, Thanks for the link. However, I am looking for eliminating consecutive duplicates rather than all duplicates - my example wasn't clear, apologies for that. x=[1,1,1,3,2,2,2,4,4,2,2] [1 ,3 ,2 ,4 ,2 ] 2009/6/18 Robert Berman berma...@cfl.rr.com: This might help: http://code.activestate.com/recipes/52560/ Robert On Thu, 2009-06-18 at 15:15 +0200, karma wrote: I was playing around with eliminating duplicates in a list not using groupby. From the two solutions below, which is more pythonic. Alternative solutions would be welcome. Thanks x=[1,1,1,3,2,2,2,2,4,4] [v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0] [x[i] for i in range(len(x)-1) if i==0 or x[i]!=x[i-1]] output: [1, 3, 2, 4] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Subclassing list
I get an error TypeError: 'rounding' is an invalid keyword argument for this function on my list subclass. How might I subclass list without this error? This is the code: class SeriesList(list): def __new__(cls, *args, **kwargs): series_list = list.__new__(cls, *args) series_list.rounding = kwargs.get('rounding', None) return series_list def moving_average(self, function, period=10): index = 0 window = [] ma = [] for i in self.__iter__(): i = float(i) if is_not_nan(i): window.insert(0, i) if len(window) == period: ma.append(function(window)) window.pop() else: ma.append(float('nan')) return round(ma, self.rounding) --- Regards, Luis ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Program Slicing / Trace
True both are assignments, L3, does change a value of any variable. Johnson On Thu, Jun 18, 2009 at 4:53 PM, Elisha Rosensweig bensha...@gmail.comwrote: It is not clear to me in what way line 3 is different than line 2 - both are assignments... Please clarify Elisha On Thu, Jun 18, 2009 at 10:37 AM, Jojo Mwebaze jojo.mweb...@gmail.comwrote: Hi Tutor The problem i have is to see which statements modify my data at execution time without referring to the code. Referring to the code is difficult esp because of branching. You can never tell before hand which branch execution will follow. e.g in the example below, statements 1, 2, 5,7 and 10 modify my data and are the ones i would like to trace during run time. However the other statements do not change my data so am not interested in them. How can this be achieved during execution? Not sure if the traceback module can be helpful here! Cheers Jojo. === def myfunction(): 1.num1= 20 #statement 1 2.num2 = 30 #statement 2 3.somelist= [ ] #statement 3 4.if (num1 num2): 5. num2 = num2 * 20 #statement 3 6.else: 7 num2 = num1 + num2 #statement 3 8.mylist = [num1, num2] #statement 4 9.for items in mylist: 10. somelist.append( math.sqrt(item) + math.log(item)) #statement 5 11. return somelist ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Subclassing list
Luis N wrote: I get an error TypeError: 'rounding' is an invalid keyword argument for this function on my list subclass. How might I subclass list without this error? This is the code: class SeriesList(list): def __new__(cls, *args, **kwargs): series_list = list.__new__(cls, *args) series_list.rounding = kwargs.get('rounding', None) return series_list def moving_average(self, function, period=10): index = 0 window = [] ma = [] for i in self.__iter__(): i = float(i) if is_not_nan(i): window.insert(0, i) if len(window) == period: ma.append(function(window)) window.pop() else: ma.append(float('nan')) return round(ma, self.rounding) --- I copied and ran the above. It gives me no errors. Of course all it is is a class definition. Is there more to the code? And please post the traceback so we have more information! -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] reference to directory a module is located at
Hi, How can I determine the directory in which a module is located, from within that module? Elisha ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reference to directory a module is located at
Elisha Rosensweig wrote: Hi, How can I determine the directory in which a module is located, from within that module? sys.modules[__name__].__file__ -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Eliminating consecutive duplicates in a list
karma wrote: I was playing around with eliminating duplicates in a list not using groupby. From the two solutions below, which is more pythonic. Alternative solutions would be welcome. Thanks x=[1,1,1,3,2,2,2,2,4,4] [v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0] [x[i] for i in range(len(x)-1) if i==0 or x[i]!=x[i-1]] output: [1, 3, 2, 4] I'd vote for the first form, though I might make a generator out of it. gen = (v for i,v in enumerate(x) if x[i]!=x[i-1] or i==0) print list(gen) Of course, that depends on the lifetime of the various objects. Interestingly, if you modify x after defining gen, but before using it, gen will use the new contents of x. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reference to directory a module is located at
bob gailer wrote: Elisha Rosensweig wrote: Hi, How can I determine the directory in which a module is located, from within that module? sys.modules[__name__].__file__ -- Bob Gailer Or more simply, __file__ But the OP wanted the directory, which can be extracted with method dirname: import os print __file__ print os.path.dirname(__file__) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reference to directory a module is located at
Try the following: import os.path os.path.abspath(__file__) This won't work in an interactive shell since it is not being executed from within a module. -- ~ Matthew Strax-Haber National Aeronautics and Space Administration Langley Research Center (LaRC) Co-op, Safety-Critical Avionics Systems Branch Student, Northeastern University W: 757-864-7378; C: 561-704-0029 matthew.strax-ha...@nasa.gov From: Elisha Rosensweig bensha...@gmail.com Reply-To: bensha...@gmail.com Date: Thu, 18 Jun 2009 11:17:56 -0500 To: Python Tutor tutor@python.org Subject: [Tutor] reference to directory a module is located at Hi, How can I determine the directory in which a module is located, from within that module? Elisha ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Apparent incosistency with Python interperter in IDLE
Luke Paireepinart wrote: So the problem is that the stdout of the ls command is appearing in some location that you cannot see. As for ways to remedy this - I don't know. The idea here, though, is that even though the regular Python version has the side-effect that it outputs it in the console, that's not necessarily what you want it to do. The reason is that you have no way to access that data. You have to explicitly redirect the stdout from subprocess subprocess.Popen(['ls'], stdout=...) What you're seeing is a side effect of the nature of the interactive console and IDLE. The defined behavior of python is when it is being run from a script. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List Splicing
Luke Paireepinart wrote: Robert Berman wrote: Emille, Thank you for the example of list splicing. Do you know if this is faster than a more conventional loop statement as in my code for primearray which is in my original post (reprinted here) As has been mentioned, you will want to profile your code to know what is truly faster. however, the main idea in speeding up your code is to move as much of the actual operations to C functions as possible. For example, x = [] for i in range(1): x.append(0) is going to be quite a bit slower than x = [0] * 1 t = Timer(x = [0] * 1000) t.timeit() 6.623384202829115 t = Timer(x = [] for i in range(1000): x.append(0)) t.timeit() 141.14222554321785 As you can see, the for loop version is about 20 times slower than the other version. But they both accomplish the same thing. The key here is that the first one, using the [] * var syntax, does not iterate over items individually. This is a gross oversimplification, but think of the python interpreter like this: you take your code to a copy shop (a la Kinkos). however, they do not have any copy machines... instead they will rewrite it by hand, line by line. and say they're going to charge you 20 cents per line. Therefore you'd want to minimize the lines of code to save money, right? Also, it's a matter of memory allocation. With an .append loop, there is no way python would know how much memory to allocate in advance; therefore it has to repeatedly reallocate memory as the list grows. Reallocating is an expensive stuff as the interpreter has to copy the whole list everytime. With [0] * 100, the interpreter knows to allocate a memory for 100 objects, in advance. It can allocate once and does not need to copy the list. But remember that all these are low level stuffs we should not need to worry about unless we have problems with performance. As for the original question (l1[n+n:len(l1):n] = 0), I usually use this: l1[start:stop:step] = [value] * len(ll[start:stop:step]) Since the len(ll[start:stop:step]) part will only generate a slice object, it would be fast. However, note that [value] * int does generate a list. Maybe an even faster version could be made using itertools.repeat(0, len(a[2::2])), we'll need to ask timeit's opinion about it. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reference to directory a module is located at
Whoops. I should read more carefully. I thought he said the path to the module itself. Yes, os.path.dirname(__file__) works. If you want an absolute path (rather than a relative path), use: os.path.abspath(os.path.dirname(__file__)) I would find this more useful if the path will be passed around. -- ~ Matthew Strax-Haber National Aeronautics and Space Administration Langley Research Center (LaRC) Co-op, Safety-Critical Avionics Systems Branch Student, Northeastern University W: 757-864-7378; C: 561-704-0029 matthew.strax-ha...@nasa.gov From: Dave Angel da...@ieee.org Date: Thu, 18 Jun 2009 11:48:40 -0500 To: Python Tutor tutor@python.org Subject: Re: [Tutor] reference to directory a module is located at bob gailer wrote: Elisha Rosensweig wrote: Hi, How can I determine the directory in which a module is located, from within that module? sys.modules[__name__].__file__ -- Bob Gailer Or more simply, __file__ But the OP wanted the directory, which can be extracted with method dirname: import os print __file__ print os.path.dirname(__file__) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Eliminating consecutive duplicates in a list
On Thu, Jun 18, 2009 at 9:15 AM, karmadorjeta...@googlemail.com wrote: I was playing around with eliminating duplicates in a list not using groupby. From the two solutions below, which is more pythonic. Alternative solutions would be welcome. But why not use groupby()? That seems much clearer to me: In [1]: from itertools import groupby In [3]: x=[1,1,1,3,2,2,2,2,4,4] In [4]: [ k for k, v in groupby(x) ] Out[4]: [1, 3, 2, 4] In [5]: x=[1,1,1,3,2,2,2,4,4,2,2] In [6]: [ k for k, v in groupby(x) ] Out[6]: [1, 3, 2, 4, 2] Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Checking Syntax
I am teaching myslef Python from a GIS tutorial 'Writing_Geoprocessing_Scripts.pdf'. I have typed everything exactly like it is in the tutorial and when I go to run a check on the sytax (before I try running the program) it places a cursor like so: outFeatureClas|s = outWorkspace + / + GP.ValidateTableName(fc,outWorkspace) I have checked the tutorial and I can't see what is wrong. I can't get past this until it is corrected. I have attached the script. Any advice would be greatly appreciated. Thanks, Kevin #Import standard library modules #imports system, operating system Windows 32 modules #sys refers to Python system, os refers to acess to operating system import win32com.client, sys, os #Create the Geoprocessor object GP = win32com.client.Dispatch(esriGeoprocessing.GpDispatch.1) #Set the input workspace #argv = argument value #argv[1] is the name of the script GP.workspace = sys.argv[1] #Set the clip featureclass clipFeatures = sys.argv[2] #Set the output workspace outWorkspace = sys.argv[3] #Set the cluster tolerance clusterTolerance = sys.argv[4] #try statement defines the beginning of a block of code that will be #handled by its associated exception handler, or except statement #try/except statements are used to handle unexpected errors #this defines that the program should do when an exception happens try: #Get a list of the featureclasses in the input folder fcs = GP.ListFeatureClasses() #Loop through the list of feature classes #always reset a list so the first item is extracted #so you can be sure you get the first item in the list fcs.Reset() fc = fcs.Next() while fc: #Validate the new feature class name for the output workspace. #ValidateTableName ensures output name is valid for output #workspace, it returns unique name so no existing data is overwritten. outFeatureClass = outWorkspace + / + GP.ValidateTableName(fc, outWorkspace) #Clip each feature class in list with the clip feature class. #Do not clip the clipFeatures, it may be in the same workspace. if str(fc) != str(os.path.split(clipFeatures)[1]): GP.Clip(fc, clipFeatures, outFeatureClass, clusterTolerance) fc = fcs.Next() except: #except statement is required by the earlier try statement #if an error occurs during execution the code in the except #block will run GP.AddMessage(GP.GetMessages(2)) print GP.GetMessages(2) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reference to directory a module is located at
Thanks - just what I needed (and thanks to all the others too) Elisha On Thu, Jun 18, 2009 at 12:48 PM, Dave Angel da...@ieee.org wrote: bob gailer wrote: Elisha Rosensweig wrote: Hi, How can I determine the directory in which a module is located, from within that module? sys.modules[__name__].__file__ -- Bob Gailer Or more simply, __file__ But the OP wanted the directory, which can be extracted with method dirname: import os print __file__ print os.path.dirname(__file__) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] converting encoded symbols from rss feed?
Hey everyone, I'm trying to get down to basics with this handy intro on Python encodings: http://eric.themoritzfamily.com/2008/11/21/python-encodings-and-unicode/ But I'm running into some VERY strange results. On the above link, the section on Encoding Unicode Byte Streams has the following example: u = uabc\u2013 print u Traceback (most recent call last): File stdin, line 1, in module UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3: ordinal not in range(128) print u.encode(utf-8) abc– But when I try the same example on my Windows XP machine (with Python 2.5.4), I can't get the same results. Instead, it spits out the below (hopefully it renders properly and we don't have encoding issues!!!): $ python Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. x = uabc\u2013 print x Traceback (most recent call last): File stdin, line 1, in module File C:\Program Files\Python25\lib\encodings\cp437.py, line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u2013' in position 3: character maps to undefined x.encode(utf-8) 'abc\xe2\x80\x93' print x.encode(utf-8) abcΓÇô I get the above results in python interpreters invoked from both the Windows command line and in a cygwin shell. HOWEVER -- the test code works properly (i.e. I get the expected abc- when I run the code in WingIDE 10.1 (version 3.1.8-1). In a related test, I was unable change the default character encoding for the python interpreter from ascii to utf-8. In all cases (cygwin, Wing IDE, windows command line), the interpreter reported that I my sys module does not contain the setdefaultencoding method (even though this should be part of the module from versions 2.x and above). Can anyone help me untangle this mess? I'd be indebted! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking Syntax
On 6/18/2009 12:55 PM Kevin Pearson said... I am teaching myslef Python from a GIS tutorial 'Writing_Geoprocessing_Scripts.pdf'. I have typed everything exactly like it is in the tutorial and when I go to run a check on the sytax (before I try running the program) it places a cursor like so: outFeatureClas|s = outWorkspace + / + GP.ValidateTableName(fc,outWorkspace) I have checked the tutorial and I can't see what is wrong. I can't get past this until it is corrected. I have attached the script. Any advice would be greatly appreciated. Thanks, Kevin #Import standard library modules #imports system, operating system Windows 32 modules #sys refers to Python system, os refers to acess to operating system import win32com.client, sys, os #Create the Geoprocessor object GP = win32com.client.Dispatch(esriGeoprocessing.GpDispatch.1) #Set the input workspace #argv = argument value #argv[1] is the name of the script GP.workspace = sys.argv[1] #Set the clip featureclass clipFeatures = sys.argv[2] #Set the output workspace outWorkspace = sys.argv[3] #Set the cluster tolerance clusterTolerance = sys.argv[4] #try statement defines the beginning of a block of code that will be #handled by its associated exception handler, or except statement #try/except statements are used to handle unexpected errors #this defines that the program should do when an exception happens try: #Get a list of the featureclasses in the input folder fcs = GP.ListFeatureClasses() #Loop through the list of feature classes #always reset a list so the first item is extracted #so you can be sure you get the first item in the list fcs.Reset() fc = fcs.Next() while fc: I don/t know if this is the only case, but certainly you'll need to increase indentation level after any lines ending in a colon that indicate the start of a block. This type of error can cause cryptic messages to the thrown up that don't always point to the actual problem. HTH, Emile #Validate the new feature class name for the output workspace. #ValidateTableName ensures output name is valid for output #workspace, it returns unique name so no existing data is overwritten. outFeatureClass = outWorkspace + / + GP.ValidateTableName(fc, outWorkspace) #Clip each feature class in list with the clip feature class. #Do not clip the clipFeatures, it may be in the same workspace. if str(fc) != str(os.path.split(clipFeatures)[1]): GP.Clip(fc, clipFeatures, outFeatureClass, clusterTolerance) fc = fcs.Next() except: #except statement is required by the earlier try statement #if an error occurs during execution the code in the except #block will run GP.AddMessage(GP.GetMessages(2)) print GP.GetMessages(2) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Apparent incosistency with Python interperter in IDLE
Karen Palen wrote: WOW! Thanks for the detailed explanation! Sure thing, putting off doing homework so... This was about what I had expected so it is no surprise. My conclusion (so far) is that there is not much to gain from an IDE in this situation and a lot of complexity to deal with. You'd be surprised how many people write Python without an IDE at all. I end up doing most of my work just in an editor with syntax highlighting (such as Notepad ++) and setting my f5 to run my Python program in a new window. That circumvents all the issues IDEs have with their stdout, as well as some other issues IDLE has (namely, if IDLE can't create a subprocess (which it is the default behavior on windows not to) and you run a program, all variables and imports will hang around for the next program run. therefore you can have the line import os then run your program, remove the line, and run it again, and even if you use methods from the os module, your code will still work fine... that is, until you restart IDLE.) Clearly I will have to deal with stdin and stdout as part of any real app however. Python makes it really easy to deal with stdin and stdout - they are just generic File objects. Since Python does Duck Typing (anything that walks like a duck and quacks like a duck may as well be a duck), you can place any class into stdin and stdout that has the common File methods (write, writeline, read, readline, etc.) You don't even have to inherit the class from File. You can make an entirely new class, so long as it implements the common methods. That's one of the beauties of Python. so you can do something like class GUIStdOut(object): def write(self, data): #draw data in your GUI self.stdout = GUIStdOut() and then you can print Hello, World! and it will show up in your GUI. The intended app is to run a mono based subprocess (yes I know, but it is too big to change) and then control it through a pipe with stdin and stdout. It looks as I I will just have to write something in C#/mono to echo my commands for testing then go from there. At the moment it looks like the straight Python interpreter plus Gedit/PDB will be the tools of choice. Yes, those are perfectly suitable tools. You may find an IDE that you like later, but just using editors are fine. One thing I do miss about IDEs is the printing of the method docstrings while you're typing, but you can get plugins to do that for most editors, I believe. I am using Python 301 because this is a brand new project and I don't want to have to convert 6 months or so down the road. Can you suggest a better strategy? No, Python 3 is probably a better bet in the long run. Just be wary of it in regard to other libraries - most 3rd party libraries do not work on Python 3 yet (Python 3 broke backward compatibility). So if you have to use any of those libraries, you're going to end up having to use 2.6. I'm personally not moving to Python 3 until all the libraries I use support it, even if I'm not using one of said libraries for a specific program. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] converting encoded symbols from rss feed?
On Thu, Jun 18, 2009 at 4:37 PM, Serdar Tumgorenzstumgo...@gmail.com wrote: On the above link, the section on Encoding Unicode Byte Streams has the following example: u = uabc\u2013 print u Traceback (most recent call last): File stdin, line 1, in module UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3: ordinal not in range(128) print u.encode(utf-8) abc– But when I try the same example on my Windows XP machine (with Python 2.5.4), I can't get the same results. Instead, it spits out the below (hopefully it renders properly and we don't have encoding issues!!!): $ python Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. x = uabc\u2013 print x Traceback (most recent call last): File stdin, line 1, in module File C:\Program Files\Python25\lib\encodings\cp437.py, line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u2013' in position 3: character maps to undefined x.encode(utf-8) 'abc\xe2\x80\x93' print x.encode(utf-8) abcΓÇô The example is written assuming the console encoding is utf-8. Yours seems to be cp437. Try this: C:\Project\Mango py Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. In [1]: import sys In [2]: sys.stdout.encoding Out[2]: 'cp437' But there is another problem - \u2013 is an em dash which does not appear in cp437, so even giving the correct encoding doesn't work. Try this: In [6]: x = uabc\u2591 In [7]: print x.encode('cp437') -- print(x.encode('cp437')) abc░ In a related test, I was unable change the default character encoding for the python interpreter from ascii to utf-8. In all cases (cygwin, Wing IDE, windows command line), the interpreter reported that I my sys module does not contain the setdefaultencoding method (even though this should be part of the module from versions 2.x and above). sys.defaultencoding is deleted by site.py on python startup.You have to set the default encoding from within a sitecustomize.py module. But it's usually better to get a correct understanding of what is going on and to leave the default encoding alone. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] converting encoded symbols from rss feed?
The example is written assuming the console encoding is utf-8. Yours seems to be cp437. Try this: In [1]: import sys In [2]: sys.stdout.encoding Out[2]: 'cp437' That is indeed the result that I get as well. But there is another problem - \u2013 is an em dash which does not appear in cp437, so even giving the correct encoding doesn't work. Try this: In [6]: x = uabc\u2591 In [7]: print x.encode('cp437') -- print(x.encode('cp437')) abc░ So does this mean that my python install is incapable of encoding the en/em dash? For the time being, I've gone with treating the symptom rather than the root problem and created a translate function. def translate_code(text): text = text.replace(#145;,') text = text.replace(#146;,') text = text.replace(#147;,'') text = text.replace(#148;,'') text = text.replace(#150;,-) text = text.replace(#151;,--) return text Which of course has led to a new problem. I'm first using Fredrik Lundh's code to extract random html gobbledygook, then running my translate function over the file to replace the windows-1252 encoded characters. But for some reason, I can't seem to get my translate_code function to work inside the same loop as Mr. Lundh's html cleanup code. Below is the problem code: infile = open('test.txt','rb') outfile = open('test_cleaned.txt','wb') for line in infile: try: newline = strip_html(line) cleanline = translate_code(newline) outfile.write(cleanline) except: newline = NOT CLEANED: %s % line outfile.write(newline) infile.close() outfile.close() The strip_html function, documented here (http://effbot.org/zone/re-sub.htm#unescape-html ), returns a text string as far as I can tell. I'm confused why I wouldn't be able to further manipulate the string with the translate_code function and store the result in the cleanline variable. When I try this approach, none of the translations succeed and I'm left with the same HTML gook in the outfile. Is there some way to combine these functions so I can perform all the processing in one pass? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking Syntax
Kevin Pearson kevinfpear...@gmail.com wrote run a check on the sytax (before I try running the program) it places a cursor like so: outFeatureClas|s = outWorkspace + / + GP.ValidateTableName(fc,outWorkspace) You should try running it, the error message may be more helpful than the syntax checker... However, it will also help make your code more readable is you insert some blank lines to break it into logical groups See below... Also most of the comments are really bad stylistically since they simply describe what the code is doing which is in most cases self evident even to a beginner. Comments should describe *why* the code is as it is, not what it is. I've removed the worst cases. #Import standard library modules import win32com.client, sys, os #Create the Geoprocessor object GP = win32com.client.Dispatch(esriGeoprocessing.GpDispatch.1) #argv[1] is the name of the script GP.workspace = sys.argv[1] clipFeatures = sys.argv[2] outWorkspace = sys.argv[3] clusterTolerance = sys.argv[4] try: fcs = GP.ListFeatureClasses() #always reset a list so the first item is extracted #so you can be sure you get the first item in the list fcs.Reset() fc = fcs.Next() while fc: # returns unique name so no existing data is overwritten. outFeatureClass = outWorkspace + / + GP.ValidateTableName(fc, outWorkspace) Notice that this line is supposerd to be inside the body of a while loop. That means it should be indented. Because it isn't the syntax checker thinks there is a missing body to the loop. Your line is the first line after Python detects the error so thats where the cursor stops. #Do not clip the clipFeatures, it may be in the same workspace. if str(fc) != str(os.path.split(clipFeatures)[1]): GP.Clip(fc, clipFeatures, outFeatureClass, clusterTolerance) fc = fcs.Next() I suspect all of these lines should be indented too... except: GP.AddMessage(GP.GetMessages(2)) print GP.GetMessages(2) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] list of instance objects, access attribute
given a class like class B(): def __init__(self, b1, b2): self.fooa = fooa self.foob = foob Ok now I have several instances in a list b1 = B(1, 2) b2 = B(3, 4) b3 = B(9, 10) alist = [b1, b2, b3] Lets say for each instance of the class I want to print the value of fooa if it is greater than 5. How do I do this, what I am unclear about is how I iterate over the values of fooa. As I write this I am thinking of trying For x in alist: if x.fooa 5 : print(x.fooa) Is that the right way or is there a better? will this work for methods? Thanks Vincent Davis ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list of instance objects, access attribute
On Thu, Jun 18, 2009 at 7:32 PM, Vincent Davisvinc...@vincentdavis.net wrote: given a class like class B(): def __init__(self, b1, b2): self.fooa = fooa self.foob = foob Ok now I have several instances in a list b1 = B(1, 2) b2 = B(3, 4) b3 = B(9, 10) alist = [b1, b2, b3] Lets say for each instance of the class I want to print the value of fooa if it is greater than 5. How do I do this, what I am unclear about is how I iterate over the values of fooa. As I write this I am thinking of trying For x in alist: if x.fooa 5 : print(x.fooa) Is that the right way or is there a better? What you have is fine. will this work for methods? Sure. Try it! Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] converting encoded symbols from rss feed?
2009/6/18 Serdar Tumgoren zstumgo...@gmail.com: In [7]: print x.encode('cp437') -- print(x.encode('cp437')) abc░ So does this mean that my python install is incapable of encoding the en/em dash? No, the problem is with the print, not the encoding. Your console, as configured, is incapable of displaying the em dash. But for some reason, I can't seem to get my translate_code function to work inside the same loop as Mr. Lundh's html cleanup code. Below is the problem code: infile = open('test.txt','rb') outfile = open('test_cleaned.txt','wb') for line in infile: try: newline = strip_html(line) cleanline = translate_code(newline) outfile.write(cleanline) except: newline = NOT CLEANED: %s % line outfile.write(newline) infile.close() outfile.close() The strip_html function, documented here (http://effbot.org/zone/re-sub.htm#unescape-html ), returns a text string as far as I can tell. I'm confused why I wouldn't be able to further manipulate the string with the translate_code function and store the result in the cleanline variable. When I try this approach, none of the translations succeed and I'm left with the same HTML gook in the outfile. Your try/except is hiding the problem. What happens if you take it out? what error do you get? My guess is that strip_html() is returning unicode and translate_code() is expecting strings but I'm not sure without seeing the error. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] converting encoded symbols from rss feed?
Ok, I should say that I managed to solve the problem by first reading and translating the data, and then applying Mr. Lundh's strip_html function to the resulting lines. For future reference (and of course any additional feedback), the working code is here: http://pastebin.com/f309bf607 But of course that's a Band-Aid approach and I'm still interested in understanding the root of the problem. To that end, I've attached the Exception below from the problematic code. Your try/except is hiding the problem. What happens if you take it out? what error do you get? My guess is that strip_html() is returning unicode and translate_code() is expecting strings but I'm not sure without seeing the error. When I run this code: snip for line in infile: cleanline = translate_code(line) newline = strip_html(cleanline) outfile.write(newline) snip ...I receive the below traceback: Traceback (most recent call last): File htmlcleanup.py, line 112, in module outfile.write(newline) UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 21: ordinal not in range(128) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list of instance objects, access attribute
Vincent Davis wrote: given a class like class B(): def __init__(self, b1, b2): ??? self.fooa = fooa ??? self.foob = foob Ok now I have several instances in a list b1 = B(1, 2) b2 = B(3, 4) b3 = B(9, 10) alist = [b1, b2, b3] Lets say for each instance of the class I want to print the value of fooa if it is greater than 5. How do I do this, what I am unclear about is how I iterate over the values of fooa. As I write this I am thinking of trying For x in alist: if x.fooa 5 : print(x.fooa) Is that the right way or is there a better? will this work for methods? Thanks Vincent Davis Did you actually try to run this code? There are at least three syntax problems. 1) you need to indent the body of the class 2) you need to match the formal parameters of __init__() with their usage. 3) you need to change 'For' to 'for' class B(): def __init__(self, b1, b2): self.fooa = b1 self.foob = b2 #Ok now I have several instances in a list b1 = B(1, 2) b2 = B(3, 4) b3 = B(9, 10) alist = [b1, b2, b3] for x in alist: if x.fooa 5 : print(x.fooa) And then the answer is yes, that's a reasonable way to iterate over the objects, displaying the ones with an attribute of specified value. However, as a style issue, I'd split the print on its own line. Another change I'd make is to explicitly specify object as the base class for class B. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Subclassing list
On Fri, Jun 19, 2009 at 12:56 AM, bob gailer bgai...@gmail.com wrote: Luis N wrote: I get an error TypeError: 'rounding' is an invalid keyword argument for this function on my list subclass. How might I subclass list without this error? This is the code: class SeriesList(list): def __new__(cls, *args, **kwargs): series_list = list.__new__(cls, *args) series_list.rounding = kwargs.get('rounding', None) return series_list def moving_average(self, function, period=10): index = 0 window = [] ma = [] for i in self.__iter__(): i = float(i) if is_not_nan(i): window.insert(0, i) if len(window) == period: ma.append(function(window)) window.pop() else: ma.append(float('nan')) return round(ma, self.rounding) --- I copied and ran the above. It gives me no errors. Of course all it is is a class definition. Is there more to the code? And please post the traceback so we have more information! -- Bob Gailer Chapel Hill NC 919-636-4239 This is the traceback. I want to let SeriesList know how to round moving average series derived from itself. In [121]: s = SeriesList(rounding=1) --- TypeError Traceback (most recent call last) /Users/Luis/Documents/Programming/speculation/ipython console in module() TypeError: 'rounding' is an invalid keyword argument for this function Thank you for your help, Luis ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] home directory usage script
I was wondering if I can get some incite on how to create a python that will accomplish the following tasks: issue: /home partition is partitioned to 80 or so G of space 24 G's is used A. What is taking up this amount of space B. Not alot of packages are installed and shouldnt take up much space Script to perform: A. Create a script that monitors the /home partition B. have it write to a log file in /var/log C. have crontab run it daily ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] converting encoded symbols from rss feed?
On Thu, Jun 18, 2009 at 9:03 PM, Serdar Tumgorenzstumgo...@gmail.com wrote: When I run this code: snip for line in infile: cleanline = translate_code(line) newline = strip_html(cleanline) outfile.write(newline) snip ...I receive the below traceback: Traceback (most recent call last): File htmlcleanup.py, line 112, in module outfile.write(newline) UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 21: ordinal not in range(128) OK, so newline is unicode, outfile.write() wants a plain string. What encoding do you want outfile to be in? Try something like outfile.write(newline.encode('utf-8')) or use the codecs module to create an output that knows how to encode. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Subclassing list
On Thu, Jun 18, 2009 at 9:48 PM, Luis Ngloboph...@gmail.com wrote: I get an error TypeError: 'rounding' is an invalid keyword argument for this function on my list subclass. How might I subclass list without this error? This is the code: class SeriesList(list): def __new__(cls, *args, **kwargs): series_list = list.__new__(cls, *args) series_list.rounding = kwargs.get('rounding', None) return series_list This is the traceback. I want to let SeriesList know how to round moving average series derived from itself. In [121]: s = SeriesList(rounding=1) --- TypeError Traceback (most recent call last) /Users/Luis/Documents/Programming/speculation/ipython console in module() TypeError: 'rounding' is an invalid keyword argument for this function I think you need to define SeriesList.__init__(self, rounding=None). This function should assign self.round, then __new__() can be just def __new__(cls, *args, **kwargs): series_list = list.__new__(cls, *args) return series_list Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] home directory usage script
On Thu, Jun 18, 2009 at 9:48 PM, dave chachidjbags...@yahoo.com wrote: A. Create a script that monitors the /home partition B. have it write to a log file in /var/log C. have crontab run it daily What do you want it to write? Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Apparent incosistency with Python interperter in IDLE
Yes I see. Based on other feedback I am leaning towards not using any IDE for the moment. Python seems well adapted to that kind of workflow, as well as an impressive portability - every bit as good a Java from my tests so far. Karen --- On Thu, 6/18/09, Lie Ryan lie.1...@gmail.com wrote: From: Lie Ryan lie.1...@gmail.com Subject: Re: [Tutor] Apparent incosistency with Python interperter in IDLE To: tutor@python.org Date: Thursday, June 18, 2009, 10:20 AM Luke Paireepinart wrote: So the problem is that the stdout of the ls command is appearing in some location that you cannot see. As for ways to remedy this - I don't know. The idea here, though, is that even though the regular Python version has the side-effect that it outputs it in the console, that's not necessarily what you want it to do. The reason is that you have no way to access that data. You have to explicitly redirect the stdout from subprocess subprocess.Popen(['ls'], stdout=...) What you're seeing is a side effect of the nature of the interactive console and IDLE. The defined behavior of python is when it is being run from a script. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor