Re: [Tutor] Can't loop thru file and don't see the problem
Roy Hinkelman wrote: Thank you very much! I had forgotten that unix URLs are case sensitive. Also, I changed my 'For' statements to your suggestion, tweaked the exception code a little, and it's working. So, there are obviously several ways to open files. Do you have a standard practice, or does it depend on the file format? I will eventually be working with Excel and possibly mssql tables. Thanks again for your help. Roy On Thu, Dec 3, 2009 at 3:46 AM, Christian Witts cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za wrote: Roy Hinkelman wrote: Your list is great. I've been lurking for the past two weeks while I learned the basics. Thanks. I am trying to loop thru 2 files and scrape some data, and the loops are not working. The script is not getting past the first URL from state_list, as the test print shows. If someone could point me in the right direction, I'd appreciate it. I would also like to know the difference between open() and csv.reader(). I had similar issues with csv.reader() when opening these files. Any help greatly appreciated. Roy Code: Select all # DOWNLOAD USGS MISSING FILES import mechanize import BeautifulSoup as B_S import re # import urllib import csv # OPEN FILES # LOOKING FOR THESE SKUs _missing = open('C:\\Documents and Settings\\rhinkelman\\Desktop\\working DB files\\missing_topo_list.csv', 'r') # IN THESE STATES _states = open('C:\\Documents and Settings\\rhinkelman\\Desktop\\working DB files\\state_list.csv', 'r') # IF NOT FOUND, LIST THEM HERE _missing_files = [] # APPEND THIS FILE WITH META _topo_meta = open('C:\\Documents and Settings\\rhinkelman\\Desktop\\working DB files\\topo_meta.csv', 'a') # OPEN PAGE for each_state in _states: each_state = each_state.replace(\n, ) print each_state html = mechanize.urlopen(each_state) _soup = B_S.BeautifulSoup(html) # SEARCH THRU PAGE AND FIND ROW CONTAINING META MATCHING SKU _table = _soup.find(table, tabledata) print _table #test This is returning 'None' If you take a look at the webpage you open up, you will notice there are no tables. Are you certain you are using the correct URLs for this ? for each_sku in _missing: The for loop `for each_sku in _missing:` will only iterate once, you can either pre-read it into a list / dictionary / set (whichever you prefer) or change it to _missing_filename = 'C:\\Documents and Settings\\rhinkelman\\Desktop\\working DB files\\missing_topo_list.csv' for each_sku in open(_missing_filename): # carry on here each_sku = each_sku.replace(\n,) print each_sku #test try: _row = _table.find('tr', text=re.compile(each_sku)) except (IOError, AttributeError): _missing_files.append(each_sku) continue else: _row = _row.previous _row = _row.parent _fields = _row.findAll('td') _name = _fields[1].string _state = _fields[2].string _lat = _fields[4].string _long = _fields[5].string _sku = _fields[7].string _topo_meta.write(_name + | + _state + | + _lat + | + _long + | + _sku + ||) print x +': ' + _name print Missing Files: print _missing_files _topo_meta.close() _missing.close() _states.close() The message I am getting is: Code: http://libremap.org/data/state/Colorado/drg/ None 33087c2 Traceback (most recent call last): File //Dc1/Data/SharedDocs/Roy/_Coding Vault/Python code samples/usgs_missing_file_META.py, line 34, in module _row = _table.find('tr', text=re.compile(each_sku)) AttributeError: 'NoneType' object has no attribute 'find' And the files look like: Code: state_list http://libremap.org/data/state/Colorado/drg/ http://libremap.org/data/state/Connecticut/drg/ http://libremap.org/data/state/Pennsylvania/drg/ http://libremap.org/data/state/South_Dakota/drg/ missing_topo_list 33087c2 34087b2 33086b7 34086c2
Re: [Tutor] When max() doesn't work as expected
On Fr, 2009-12-04 at 08:21 +0100, spir wrote: By the way, is there any reason why the compare func parameter is called 'key'? I'd guess because what you provide creates keys for the values in the collection to sort them by. What else to call it? Comparators compare two values, hashes don't need to provide information relevant to ordering, and indexes are not directly related to the value at all. Cheers, Alan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] saving output data in a file
On Fri, Dec 04, 2009 at 01:13:42PM +0530, Prasad Mehendale wrote: I am a beginner. I want to save the output data of the following programme in a file through the programme. Please suggest me the way. I am using Python 2.3.3 on mandrake linux 10 and using Idle to save the output to a file presently. To save the output to a file, you have a open a file object and write to it. When you are done, just close it. If your program, open a fileobj somewhere on the top. fileobj = open('dc-generator-output.txt','w') And where you put the print statement, replace it with fileobj.write( ) # Within in the the output which you want to put. One strategy would be create a string in place of your print and write the string. For eg. Instead of print '(Pole*RPM) product for various values of conductors/slot is: \n', polerpm You will do msg = '(Pole*RPM) product for various values of conductors/slot is: \n', polerpm fileobj.write(msg) And in the end, close the fileobj. fileobj.close() -- Senthil Flee at once, all is discovered. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] saving output data in a file
Prasad Mehendale prachit...@gmail.com wrote I am a beginner. I want to save the output data of the following programme in a file through the programme. The easiest way is to use file redirection at run-time $ python foo.py results.txt This will work on Linux/MacOS/Windows The alternatives are 1) open a file in your program and replace all of the print statements with write() functions 2) Use the file output trick with print resultFile = open('results.txt',w) print resultFile 'my output string' You can find out more about file handling in the Handling Files topic of my tutorial ... -- 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] saving output data in a file
Senthil Kumaran orsent...@gmail.com wrote Instead of print '(Pole*RPM) product for various values of conductors/slot is: \n', polerpm You will do msg = '(Pole*RPM) product for various values of conductors/slot is: \n', polerpm You would need to do a bit more since polerpm will not automatically be appended to the string as it would in a print. So you probably want to use a format string or at least convert polerpm to a string using str() -- 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] saving output data in a file
Prasad Mehendale prachit...@gmail.com dixit: I am a beginner. I want to save the output data of the following programme in a file through the programme. Please suggest me the way. I am using Python 2.3.3 on mandrake linux 10 and using Idle to save the output to a file presently. Thanks in advance. You just need to create/open a file before the loop and add a writing instruction -- see below lines inserted in your code. #programme to calculate various parameters for a dc-generator. import math #import os #flux is assumed to be .005Wb, and A=parallel paths = 2 for wave winding polerpm=[] for ConductorsPerSlot in range(1,11): we consider that output voltage is 20 V DC PoleRpmProduct=2/ConductorsPerSlot polerpm.append(PoleRpmProduct) print '(Pole*RPM) product for various values of conductors/slot is: \n', polerpm savefile = file(save_file_path, 'w')### for poles in range(2,18,2): print print '\n For number of poles='+str(poles) +' RPM values are: ' for i in range(len(polerpm)): rpm=polerpm[i]/poles print rpm, savefile.write(rpm)### savefile.close() ### Search for file in online or local documentation. Notes: * Always close a file if ever... * open() and file() are aliases. * The 'w' argument stands for 'writing'. Another approach is to redirect sys.stdout to a file. Search for this in the doc. The disadvantages imo are (1) this is less obvious (redirection can easily be overlooked) and (2) you lose output to console for checking. Denis 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] When max() doesn't work as expected
On Fri, Dec 4, 2009 at 2:21 AM, spir denis.s...@free.fr wrote: Albert Sweigart asweig...@gmail.com dixit: You need to specify an ordering function, in your case, len(): By the way, is there any reason why the compare func parameter is called 'key'? It is conventional terminology - the sort key is the value the sort is done on. Google 'sort key' for lots of usage examples. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] How do I plot a horizontal line and a vertical line in python
How can I do this using matplotlib? The snippet of my code looks like: k = 1.195*ones((1,data[0].size)) plot(data[0], k,'--') but I get this error: Traceback (most recent call last): File ./plot_detector.py, line 26, in module plot(data[0], k,'--') File /usr/lib/pymodules/python2.6/matplotlib/pyplot.py, line 2142, in plot ret = ax.plot(*args, **kwargs) File /usr/lib/pymodules/python2.6/matplotlib/axes.py, line 3418, in plot for line in self._get_lines(*args, **kwargs): File /usr/lib/pymodules/python2.6/matplotlib/axes.py, line 297, in _grab_next_args for seg in self._plot_args(remaining, kwargs): File /usr/lib/pymodules/python2.6/matplotlib/axes.py, line 274, in _plot_args x, y = self._xy_from_xy(x, y) File /usr/lib/pymodules/python2.6/matplotlib/axes.py, line 214, in _xy_from_xy raise ValueError(x and y must have same first dimension) ValueError: x and y must have same first dimension Am I doing this all the wrong way? Regards Mkha ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python at my work
- Original Message - From: Alan Gauld alan.ga...@btinternet.com To: tutor@python.org Sent: Thursday, December 3, 2009 3:07:06 PM GMT -07:00 US/Canada Mountain Subject: Re: [Tutor] Python at my work Playing Devil's Advocate here... skrab...@comcast.net wrote - Clean easy to read syntax - Easy to learn But if the rest already know Perl that's not such a compelling argument. - Object Oriented as needed - Large community Yep, Perl does that too. - Multi-platform Yep, Perl too. - Fits in your head Hmmm I know what you mean but I'm not sure a Perl fan would understand what that means. - Batteries included - Large library(Cheese Shop) Perl fans would say the same - CPAN is bigger and easier to use than the CheeseShop, we can't really argue that point. Anything else? The main advantage over Perl is its suitability for large scale programming - packages as well as simple modules - and maybe ease of integration with Java via Jython if that matters (I think there is a Java Perl but I'm not sure how mature it is) And of course Perl fans will trawl out the usual disadvantages of poorer performance and a smaller installed base. You need to consider the counter arguments when constructing a case. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ --- Our dept has already decided to keep Perl in its arsenal of languages. I just need to give enough justification to keep Python in that arsenal. Thanks for all of your responses. Alan did a good job of Devil's Advocate. Is Python easier to learn that Perl? When we get new developers into our group, the new developer will need to get up to speed on the tools in our arsenal. The best explanation of fits in your head is many times I have guessed on how to do something in Python and it usually works. I don't have to look it up in the docs or a book. I can't say I've had that experience in Perl. The biggest advantage I see is Python's clean easy to read syntax. Perl cannot claim that. I'll need to reread Eric Raymond's article and see if I can pick anything that will help. Thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python equivalent to Matlab keyboard function
This is probably an easy one. When I was writing Matlab m-files, I really enjoyed the ability to stop the code to check how values were being stored or to 'step' into a function with the keyboard function. I have numerous 'environments'? as part of Python (x,y) including IDLE, Eclipse, and Spyder. I know that Spyder is very Matlab esque, but I prefer to use Eclipse as my programs up to this point have not been mathematics based. To do what I want In Spyder I paste a portion of my program and click the run icon. The interactive console then allows me to proceed through the next lines manually so that I can get real-time feedback. This is really helpful in understanding what I'm doing with OOP as I'm learning from a book and would like to follow along just like it is written which is usually a few lines at a time. Is there a way in Eclipse to do the same thing so I am not switching between environments? When I try the same thing it just terminates at the end of the code. (I am following the learning python for absolute beginners book. I love Python btw, it is very easy to use IMO, and has the muscle to do some really cool things.) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python equivalent to Matlab keyboard function
On Fri, Dec 4, 2009 at 11:10 AM, Tim Goddard timgoddardsem...@gmail.com wrote: This is probably an easy one. When I was writing Matlab m-files, I really enjoyed the ability to stop the code to check how values were being stored or to 'step' into a function with the keyboard function. I have numerous 'environments'? as part of Python (x,y) including IDLE, Eclipse, and Spyder. I know that Spyder is very Matlab esque, but I prefer to use Eclipse as my programs up to this point have not been mathematics based. To do what I want In Spyder I paste a portion of my program and click the run icon. The interactive console then allows me to proceed through the next lines manually so that I can get real-time feedback. This is really helpful in understanding what I'm doing with OOP as I'm learning from a book and would like to follow along just like it is written which is usually a few lines at a time. Is there a way in Eclipse to do the same thing so I am not switching between environments? When I try the same thing it just terminates at the end of the code. I'm not really sure what you are doing in Spyder but you should be able to do what you want in PyDev using the debugger or the interactive console. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Dictionary Comprehensions
Hi everyone! I'm using python 3.1 and I want to to know why is it when I enter the following in a dictionary comprehension: dc={y:x for y in list(khalid) for x in range(6)} I get the following: {'a': 5, 'd': 5, 'i': 5, 'h': 5, 'k': 5, 'l': 5} instead of the expected: {'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5} and is there a way to get the target (expected) dictionary using a dictionary comprehension. note that I tried sorted(range(6)) also but to no avail. thanks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Comprehensions
On 12/5/2009 7:32 AM, Khalid Al-Ghamdi wrote: Hi everyone! I'm using python 3.1 and I want to to know why is it when I enter the following in a dictionary comprehension: dc={y:x for y in list(khalid) for x in range(6)} are you sure you want this? {'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5} instead of: {'a': 2, 'd': 5, 'i': 4, 'h': 1, 'k': 0, 'l': 3} for the former case, you can't, you can't guarantee any sort of ordering in dictionary. You should use ordered dictionary instead. For the latter case, it's easy with zip() dc={y:x for x, y in zip(khalid, range(6))} as for why python did that, it's because dictionary comprehension is supposed to have similar semantic with: dc = {x: y for x, y in lst} dc = dict( (x, y) for x, y in lst ) so this: dc={y:x for y in list(khalid) for x in range(6)} becomes: dc=dict( (y, x) for y in list(khalid) for x in range(6) ) note that: [(y, x) for y in list(khalid) for x in range(6)] [('k', 0), ('k', 1), ('k', 2), ('k', 3), ('k', 4), ('k', 5), ('h', 0), ('h', 1), ('h', 2), ('h', 3), ('h', 4), ('h', 5), ('a', 0), ('a', 1), ('a', 2), ('a', 3), ('a', 4), ('a', 5), ('l', 0), ('l', 1), ('l', 2), ('l', 3), ('l', 4), ('l', 5), ('i', 0), ('i', 1), ('i', 2), ('i', 3), ('i', 4), ('i', 5), ('d', 0), ('d', 1), ('d', 2), ('d', 3), ('d', 4), ('d', 5)] and when that big list is turned into a dict it gives: dict(_) {'a': 5, 'd': 5, 'i': 5, 'h': 5, 'k': 5, 'l': 5} ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Comprehensions
On Fri, Dec 4, 2009 at 9:32 PM, Khalid Al-Ghamdi emailkg...@gmail.com wrote: Hi everyone! I'm using python 3.1 and I want to to know why is it when I enter the following in a dictionary comprehension: dc={y:x for y in list(khalid) for x in range(6)} I get the following: {'a': 5, 'd': 5, 'i': 5, 'h': 5, 'k': 5, 'l': 5} instead of the expected: {'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5} and is there a way to get the target (expected) dictionary using a dictionary comprehension. note that I tried sorted(range(6)) also but to no avail. thanks That dictionary comprehension is equivalent to the following code: dc = {} for x in range(6): for y in list(khalid): dc[y] = x This makes it clear what is wrong. The two for loops come out as nested, rather than zipped. The general fix for something like this is the zip function: bc = {x: y for x, y in zip(khalid, xrange(6))} However, in this case, the idiomatic way to write this would be the enumerate function: bc = {y: x for x, y in enumerate(khalid)} Note that your output is like so: {'a': 2, 'd': 5, 'i': 4, 'h': 1, 'k': 0, 'l': 3} The first character in your original string gets a zero, the second a one, so on and so forth. I'm hoping that's what you meant. If you really want this: {'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5} I'm not sure how to do that programmatically. The dict object prints its objects in no particular order, so figuring out that order is hard (and very likely implementation/platform dependent). My best guess was sorted(khalid, key=hash): {'a': 0, 'd': 1, 'i': 3, 'h': 2, 'k': 4, 'l': 5} close, but no cigar. Anyone who can think of a clever hack for this? Not that it's very useful, but fun. Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Comprehensions
On 12/4/2009 12:32 PM Khalid Al-Ghamdi said... Hi everyone! I'm using python 3.1 and I want to to know why is it when I enter the following in a dictionary comprehension: dc={y:x for y in list(khalid) for x in range(6)} Try breaking this into pieces... First see what [(x,y) for y in in list(khalid) for x in range(6)] gets you, then see how that fits into dict(). To get where you want, take a look at zip'ing the two lists. (II don't remember -- s zip still in 3.1?) Emile I get the following: {'a': 5, 'd': 5, 'i': 5, 'h': 5, 'k': 5, 'l': 5} instead of the expected: {'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5} and is there a way to get the target (expected) dictionary using a dictionary comprehension. note that I tried sorted(range(6)) also but to no avail. thanks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary Comprehensions
Khalid Al-Ghamdi wrote: Hi everyone! I'm using python 3.1 and I want to to know why is it when I enter the following in a dictionary comprehension: dc={y:x for y in list(khalid) for x in range(6)} I get the following: {'a': 5, 'd': 5, 'i': 5, 'h': 5, 'k': 5, 'l': 5} instead of the expected: {'a': 0, 'd': 1, 'i': 2, 'h': 3, 'k': 4, 'l': 5} and is there a way to get the target (expected) dictionary using a dictionary comprehension. note that I tried sorted(range(6)) also but to no avail. thanks You're confused about what two for loops do here. It's basically a doubly-nested loop, with the outer loop iterating from k through d, and the inner loop iterating from 0 to 5. So there are 36 entries in the dictionary, but of course the dictionary overwrites all the ones with the same key. For each letter in the outer loop, it iterates through all six integers, and settles on 5. To do what you presumably want, instead of a doubly nested loop you need a single loop with a two-tuple for each item, consisting of one letter and one digit. dc = { y:x for y,x in zip(khalid, range(6)) } The output for this is: {'a': 2, 'd': 5, 'i': 4, 'h': 1, 'k': 0, 'l': 3} Now, this isn't the same values for each letter as you expected, but I'm not sure how you came up with that particular order.I expect, and get, 0 for the first letter 'k' and 1 for the 'h'. etc. Perhaps printing out the zip would make it clearer: list( zip(khalid, range(6)) ) yields [('k', 0), ('h', 1), ('a', 2), ('l', 3), ('i', 4), ('d', 5)] DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python equivalent to Matlab keyboard function
Message: 6 Date: Fri, 4 Dec 2009 11:57:45 -0500 From: Kent Johnson ken...@tds.net To: Tim Goddard timgoddardsem...@gmail.com Cc: tutor@python.org Subject: Re: [Tutor] Python equivalent to Matlab keyboard function Message-ID: 1c2a2c590912040857nacae64jcd9feab87af58...@mail.gmail.com Content-Type: text/plain; charset=ISO-8859-1 On Fri, Dec 4, 2009 at 11:10 AM, Tim Goddard timgoddardsem...@gmail.com wrote: This is probably an easy one. When I was writing Matlab m-files, I really enjoyed the ability to stop the code to check how values were being stored or to 'step' into a function with the keyboard function. I have numerous 'environments'? as part of Python (x,y) including IDLE, Eclipse, and Spyder. I know that Spyder is very Matlab esque, but I prefer to use Eclipse as my programs up to this point have not been mathematics based. To do what I want In Spyder I paste a portion of my program and click the run icon. ?The interactive console then allows me to proceed through the next lines manually so that I can get real-time feedback. This is really helpful in understanding what I'm doing with OOP as I'm learning from a book and would like to follow along just like it is written which is usually a few lines at a time. Is there a way in Eclipse to do the same thing so I am not switching between environments? ?When I try the same thing it just terminates at the end of the code. I'm not really sure what you are doing in Spyder but you should be able to do what you want in PyDev using the debugger or the interactive console. Kent Right, My problem is I can't run the code in the interactive console. I'm sure this is a configuration issue in eclipse. Copy and pasting the code into an interactive console window results in a bunch of errors that aren't really there. Running the code normally results in termination once it reaches the end. IDLE and Spyder are meant for python so there is no setup, and I can interact with the program as it remains 'running'. I guess I'll have to spend some time reading more about eclipse and getting the interactive feature working. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python time
Only just spotted this. spir denis.s...@free.fr wrote It's not C's function, it's a Unix system call. It's been part of Unix since BSD 4.2 I am confused here. That's what I first thought (there _must_ be a way to get time more precise that seconds!). But on my system (ubuntu 9.10) I cannot find the proper manner to use these system calls. Even from the command-line directly. You cannot call system calls from the command line. You can only execute Unixc commands from the shell. A command is a standaline program(executable), it is quite different to a system call. A system call in Unix is the C API provided by the kernel. It can only be called by C or some other language that can link with the kernel libraries - eg Fortran, Assembler etc. So when you use Python it calls the Unix system call via C. [Aside: There is an excellent O'Reilly book on using the Unix system calls from C: Unix Systems Programming for SVR4 Much of it is directly applicable to Python - sockets, file handling, time, fork, spawn, etc It can be bought used for just a few dollars on Amazon...] This let me think gettimeofday() and ftime() are C routines, They are C functions provided by the Unix kernel. This makes them Unix OS system calls rather than C standard library functions. time() is the lowest common denominator supported by any ANSI C system. Whereas time is provided by the C standard libvrary and is not part of the Unix kernel. So, I still have the issue of not beeing smart enough to access one of these systems-provided features. You access them by using Python. HTH, -- 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] Python equivalent to Matlab keyboard function
Tim Goddard timgoddardsem...@gmail.com wrote My problem is I can't run the code in the interactive console. If its any consolation I couldn't get Eclipse's interactive session working well either. However... I guess I'll have to spend some time reading more about eclipse and getting the interactive feature working. I think for what you want you should investigate the debugger rather that interactive mode. Check out breakpoints, watches and step-over and step-into. The Eclipse debugger is good, much better than IDLE. HTH, -- 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] saving output data in a file
On Fri, Dec 04, 2009 at 01:13:42PM +0530, Prasad Mehendale wrote: I am a beginner. I want to save the output data of the following programme in a file through the programme. Please suggest me the way. I am using Python 2.3.3 on mandrake linux 10 and using Idle to save the output to a file presently. Thanks in advance. #programme to calculate various parameters for a dc-generator. import math #import os #flux is assumed to be .005Wb, and A=parallel paths = 2 for wave winding polerpm=[] for ConductorsPerSlot in range(1,11): we consider that output voltage is 20 V DC PoleRpmProduct=2/ConductorsPerSlot polerpm.append(PoleRpmProduct) print '(Pole*RPM) product for various values of conductors/slot is: \n', polerpm for poles in range(2,18,2): print print '\n For number of poles='+str(poles) +' RPM values are: ' for i in range(len(polerpm)): rpm=polerpm[i]/poles print rpm, Another suggestion is to define a class that contains a method named write which takes one argument which is the text to be printed. This approach is useful when there are print statements in code that is not under your control, for example imported modules. There is a note about this here: http://docs.python.org/library/sys.html#sys.stdout Here is an example: # import sys class Redirect(object): def __init__(self, filename): self.outfile = open(filename, 'w') self.count = 0 def write(self, msg): self.count += 1 self.outfile.write('%d %s\n' % (self.count, msg, )) def close(self): self.outfile.close() def test(): print 'starting' save_stdout = sys.stdout redir = Redirect('/tmp/tmp1.txt') sys.stdout = redir print 'something' print 'something else' redir.close() sys.stdout = save_stdout print 'finished' test() # A few notes: - Be sure to close or flush the file. - The chunks passed to your write method may not be whole lines. - Dave -- --prasad mehendale ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Dave Kuhlman http://www.rexx.com/~dkuhlman ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor