Re: [Tutor] Python assginment
On Wed, Feb 22, 2012 at 06:10:57AM +0530, Sukhpreet Sdhu wrote: > hi > i m working on Python assignment to convert roman numericals to arabic and > vice versa.I had tried many different codes but those are not working. > Can you please suggest me the code to do this by using while , if and else > statements. Everything you need to know to solve this problem can be found at this website: http://catb.org/esr/faqs/smart-questions.html Please read it, and then if you have any more questions, come back and ask and we'll see what we can do to help. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recognizing real numbers
On Tue, Feb 21, 2012 at 07:00:40PM -0800, Michael Lewis wrote: > It seems that the .isdigit() function that I use doesn't recognize the .5 > as a number and therefore doesn't multiply it. How can I get my code to > recognize numbers such as .5, 1.75 as numbers? As the saying goes, it is often Easier to Ask for Forgiveness than Permission ("EAFP"). In Python terms, that means when you want to do something, just do it, and then catch the exception if it fails. Wrap this in a function, and it allows you to use a nifty Look Before You Leap ("LBYL") style of programming: def isfloat(obj): """Return True if obj is a number or string-like floating point number. """ try: float(obj) except (TypeError, ValueError): return False else: # no errors return True And some examples of it in use: >>> isfloat("123.456") True >>> isfloat("123.45...6") False >>> isfloat(".1") True >>> isfloat("1.1e6") # 1.1 million True >>> isfloat("1.1g6") False >>> isfloat("+.1") True >>> isfloat(".") False -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pyhton editor
On Wed, Feb 22, 2012 at 01:01:50AM +, Alan Gauld wrote: > I seem to recall it was written in Borland's Delphi. > There is FreePascal which is very Delphi like, although not quite a > clone, it might be possible to port it to FreePascal if somebody was > keen enough! There is also GNU Pascal, which supports Borland Pascal 7 and some Delphi features. http://www.gnu-pascal.de/gpc/h-index.html -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Reading/dealing/matching with truly huge (ascii) files
So, Python question of the day: I have 2 files that I could normally just read in with asciitable, The first file is a 12 column 8000 row table that I have read in via asciitable and manipulated. The second file is enormous, has over 50,000 rows and about 20 columns. What I want to do is find the best match for (file 1 column 1 and 2) with (file 2 column 4 and 5), return all rows that match from the huge file, join them togeather and save the whole mess as a file with 8000 rows (assuming the smaller table finds one match per row) and 32=12+20 columns. So my read code so far is as follows: - import sys import asciitable import matplotlib import scipy import numpy as np from numpy import * import math import pylab import random from pylab import * import astropysics import astropysics.obstools import astropysics.coords x=small_file #cannot read blank values (string!) if blank insert -999.99 dat=asciitable.read(x,Reader=asciitable.CommentedHeader, fill_values=['','-999.99']) y=large_file fopen2=open('cfile2match.list','w') dat2=asciitable.read(y,Reader=asciitable.CommentedHeader, fill_values=['','-999.99']) #here are the 2 values for the small file Radeg=dat['ra-drad']*180./math.pi Decdeg=dat['dec-drad']*180./math.pi #here are the 2 values for the large file Radeg2=dat2['ra-drad']*180./math.pi Decdeg2=dat2['dec-drad']*180./math.pi for i in xrange(len(Radeg)): for j in xrange(len(Radeg2)): #select the value if it is very, very, very close if i != j and Radeg[i] <= (Radeg2[j]+0.01) and Radeg[i] >= (Radeg2[j]-0.01) and Decdeg[i] <= (Decdeg2[j]+0.01) and Decdeg[i] >= (Decdeg2[j]-0.01): fopen.write( " ".join([str(k) for k in list(dat[i])])+" "+" ".join([str(k) for k in list(dat[j])])+"\n") --- Now this is where I had to stop, this is way, way too long and messy. I did a similar approach with smaller (9000 lines each) files and it worked but took awhile, the problem here is I am going to have to play with the match range to return the best result and give only one (1!) match per row for my smaller file, i.e. row 1 of small file must match only 1 row of large file. then I just need to return them both. However, it isn't clear to me that this is the best way forward. I have been changing the xrange to low values to play with the matching, but I would appreciate any ideas. Thanks ~Elaina -- PhD Candidate Department of Physics and Astronomy Faculty of Science Macquarie University North Ryde, NSW 2109, Australia ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pyhton editor
Pyscripter.. I played with it when I had Windows but it seemed to e tied to a specific version of Python. Has that changed? *I have no clue which version you had ran it with, I am using it with Python 3.2.2 and it works great. > i love the simply way you can use tkinter from a server? > No muss no fuss. Can you elaborate on that? I have no idea what you mean? *As I had said, I had just played with it for a half an hour or so. I had seen remote listed in the menu, and had assumed it had to do with tkinter and Wx not being os based. What's that old chestnut about not assuming.. This is from the Pyscripter doc: · Remote Tk This remote Python engine is specifically created to run and debug Tkinter applications including pylabusing the Tkagg backend. It also supports running pylab in interactive mode. The engine activates a Tkinter mainloop and replaces the mainloop with a dummy function so that the Tkinter scripts you are running or debugging do not block the engine. You may even develop and test Tkinter widgets using the interactive console. Being a neophyte to Python, I was under the impression that you had to install tkinter independently.of python.This was a fresh install of WinXp, unless it either comes bundles with windows or Python, I was surprised it was there to load. -- Alan G Ken ___ 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
[Tutor] Recognizing real numbers
Hi everyone, I have some code where I import a file to use a module. That module that I import takes text and a multiplier, checks for any numbers in that text and will then multiply those numbers by the given multiplier. The imported module is below. I am getting the text from a file that I have which starts out as: .5 lb. butter 1.75 Cups Graham Cracker Crumbs 2.0 Cups Powder Sugar 1.0 Cups Peanut Butter 2.0 Cups Semi-sweet Chocolate Chips It seems that the .isdigit() function that I use doesn't recognize the .5 as a number and therefore doesn't multiply it. How can I get my code to recognize numbers such as .5, 1.75 as numbers? Imported module: def MultiplyText(text, multiplier): '''Recieve a S & int. For digits in S, multiply by multiplier and return updated S.''' return ' '.join(str(float(num) * multiplier) if num.isdigit() else num for num in text) Module doing the importing/opening/reading/creating a new file import Homework5_1 as multiply def DoubleDigits(file_name): '''Open file/read file/write new file that doubles all int's in the read file''' try: read_file = open(file_name) except IOError: return 'No such file.' new_file_name = file_name + '2' try: write_file = open(new_file_name, 'w') except IOError: read_file.close() return 'No such file to write to.' for line in read_file: new_line = line.split() new_line = ''.join(multiply.MultiplyText(new_line, 2)) write_file.write(new_line + '\n') read_file.close() write_file.close() def main(): DoubleDigits(raw_input('What file do you want to open? ')) if '__name__' == '__main__': print main() Output that is written to my file: Peanut Butter Bars Ingredients .5 lb. butter 1.75 Cups Graham Cracker Crumbs 4.0 Cups Powder Sugar 2.0 Cups Peanut Butter 4.0 Cups Semi-sweet Chocolate Chips Melt butter. Add graham cracker crumbs, peanut butter and sugar. Mix well and pat into sheet pan. Cover with melted chocolate. Refrigerate until semi-firm, then cut into squares. -- Michael J. Lewis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Editor
I agree, pyscripter if using windows used to be my favorite, and is in the top 3 favorite python editors. Based on your tastes and your editor selection I'd say that you might like another batteries-included(not much config, autocomplete, ability to test code/etc... ) editor for python native to both Windows & Linux would be that of Aptana Studio(primary focus is that of web), customized from eclipse however depending on the distro you use is may have to be compiled. But pydev(Aptana's python-based plugin) is included with Aptana Studio. If indeed the lack of a pre-configured system-ready package/compiling from source is not enticing, then one can use the pkg-management conducive to your distro and install eclipse(as most distros have that). Then go to the plug-in installation in Eclipse's help menu and install pydev, from I believe http://pydev.org. Its def. A great editor, and I have used it alot, and the fact both windows, and linux use it your able to seamlessly resume your work no matter what os your using. But Wine most certainly isnt bad and I have gotten if memory serves me correctly pyscripter to work on my archlinux install. Some other editors that are more so geared towards python development on linux are cream/pida, eric, & spyder(probably most similar to pyscripter). My one concern with pyscripter I believe is that its not being updated currently(I could be wrong, but I think thats what I last saw. ). Good luck! Will Sent from my Verizon Wireless Phone -Original message- From: tutor-requ...@python.org To: tutor@python.org Sent: Wed, Feb 22, 2012 00:28:23 GMT+00:00 Subject: Tutor Digest, Vol 96, Issue 89 Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-requ...@python.org You can reach the person managing the list at tutor-ow...@python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: Pyhton editor (ken brockman) 2. Re: Checking for file completion. (Steven D'Aprano) 3. how to rewrite area.py (William Stewart) 4. Re: how to rewrite area.py (Dave Angel) 5. Re: how to rewrite area.py (Steven D'Aprano) -- Message: 1 Date: Tue, 21 Feb 2012 15:29:01 -0800 (PST) From: ken brockman To: "Prasad, Ramit" ,"tutor@python.org" Subject: Re: [Tutor] Pyhton editor Message-ID: <1329866941.17077.yahoomail...@web39302.mail.mud.yahoo.com> Content-Type: text/plain; charset="iso-8859-1" From: "Prasad, Ramit" To: "tutor@python.org" Sent: Tuesday, February 21, 2012 10:08 AM Subject: Re: [Tutor] Pyhton editor However I stumbled upon PyScripter and I find it really amazing. Pity it is only for Windows. WINE? Ramit I?concur. Pyscripter , though?I've?only installed it a few days ago, seems to be one of the better ones. I am?running?it in a virtualbox winXP on top of?Linux?Ubuntu, but i love the simply way you can use tkinter from a server? No muss no fuss. Just install and go. I understand that the way it had been built, it can't be readily ported to Linux. Mores the pity. Ken Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email.? ___ Tutor maillist? -? Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- next part -- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20120221/1bad24e9/attachm ent-0001.html> -- Message: 2 Date: Wed, 22 Feb 2012 10:35:00 +1100 From: Steven D'Aprano To: Python Tutor Subject: Re: [Tutor] Checking for file completion. Message-ID: <4f442a24.3030...@pearwood.info> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Tony Pelletier wrote: Missing a return statement in the case of an exception. Can you explain this? Why would I want the return on the exception? Because if you don't, it will return None. -- Steven -- Message: 3 Date: Tue, 21 Feb 2012 15:51:39 -0800 (PST) From: Will
Re: [Tutor] Pyhton editor
On 21/02/12 23:29, ken brockman wrote: I concur. Pyscripter , though I've only installed it a few days ago, seems to be one of the better ones. I played with it when I had Windows but it seemed to e tied to a specific version of Python. Has that changed? > i love the simply way you can use tkinter from a server? > No muss no fuss. Can you elaborate on that? I have no idea what you mean? You can run a tkinter program on a server and display it on your local PC using X, but that has nothing to do with Pyscripter? And not much to do with tkinter for that matter! I assume you mean something else? understand that the way it had been built, it can't be readily ported to Linux. Mores the pity. I seem to recall it was written in Borland's Delphi. There is FreePascal which is very Delphi like, although not quite a clone, it might be possible to port it to FreePascal if somebody was keen enough! -- Alan G 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 assginment
On 02/21/2012 07:40 PM, Sukhpreet Sdhu wrote: hi i m working on Python assignment to convert roman numericals to arabic and vice versa.I had tried many different codes but those are not working. Can you please suggest me the code to do this by using while , if and else statements. thanks Sukhpreet Sidhu You need to indent the code following the if statement on line 244. Or if you haven't tried, you might want to attempt a few lines before asking for help here. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to rewrite area.py
On 21/02/12 23:51, William Stewart wrote: I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). You will find something similar in my tutorial in the topic Branching. Look under the heading "Python multi-selection" and there is some code you should be able to include as template. Have a go and come back with questions. I am horrible at math and I cannot even figure out what I need to do for this Steven has done the math bit for you, so just plug it into the python code you need. -- Alan G 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
[Tutor] Python assginment
hi i m working on Python assignment to convert roman numericals to arabic and vice versa.I had tried many different codes but those are not working. Can you please suggest me the code to do this by using while , if and else statements. thanks Sukhpreet Sidhu___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to rewrite area.py
On 2/21/2012 6:51 PM, William Stewart wrote: hello I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). "Need to"" - why? Is this a homework assignment? I am horrible at math and I cannot even figure out what I need to do for this Any help would be appreciated All I have is the menu which looks like this Did you run this program? What results did you get? How did they differ from what you expected? What does being "horrible at mat" have to do with this? What do you know about defining functions? Did you write this program yourself? If you are taking a Python class and don't know what to do either the class is poorly designed or you are in the wrong class. Please say more about this. We are glad to help, but won't write your homework for you. import math print "your options are:" print " " print "1) Area(SQUARE)" print "2) Area(RECTANGLE)" print "3) Area(CIRCLE)" print "4) Perimeter(SQUARE)" print "5) Perimeter(RECTANGLE)" print "6) Perimeter(CIRCLE)" print "7) Exit" while True: selection = raw_input("Please select an option from the menu.: ") python area.py print "Calculate information about a rectangle" length = input("Length:") width = input("Width:") print "Area",length*width print "Perimeter",2*length+2*width print 'To find the area of a rectangle,' print 'Enter the width and height below.' print w = input('Width: ') while w <= 0: print 'Must be a positive number' w = input('Width: ') h = input('Height: ') while h <= 0: print 'Must be a positive number' h = input('Height: ') print 'Width =',w,' Height =',h,' so Area =',area(w,h) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to rewrite area.py
William Stewart wrote: hello I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). I am horrible at math and I cannot even figure out what I need to do for this Any help would be appreciated Have you learned about functions? Here's an example. Put this in a file and try it. def get_drink(): answer = raw_input("Would you like a cup of tea? (y/n) ").lower() while answer not in ('y', 'yes', 'n', 'no'): print "I'm sorry, I don't understand that response." print "Please enter Yes or No." answer = raw_input("Would you like a cup of tea? (y/n) ").lower() if answer in ('y', 'yes'): return "a nice steaming cup of tea, with a couple of biscuits" else: return "a stale cup of bitter coffee" drink = get_drink() print "I have", drink Notice a few things: First, you define a function with the "def" keyword, and give it a name, in this case, "get_drink". Names should usually be verbs ("doing words"), because functions do things. Second, the function normally should use the "return" statement to send a result back to the caller. Third, you call the function by name, using round brackets (parentheses) to indicate to Python that you are calling it, and save the result in a variable ("drink" in the above example). And finally, you can then use the variable for further processing. In your case, you want six functions, to get the area of a square, the perimeter of a rectangle, etc. So for each function, you need to decide on a descriptive name, such as this: def get_area_of_square(): # Ask the user for the width of the square. ... # Calculate the area. area = width**2 return area The dots ... need to be filled in by you. Your program already has code that asks the user for a width, just grab it and put it inside the function. The formulae you need are: SQUARES: area = width*width = width**2 perimeter = width+width+width+width = 4*width RECTANGLES: area = width*height perimeter = width+height+width+height = 2*(width+height) CIRCLES: area = pi*radius**2 circumference = 2*pi*radius To get the value of pi, put this at the top of your program: from math import pi Hope this helps. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to rewrite area.py
On 02/21/2012 06:51 PM, William Stewart wrote: hello I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). I am horrible at math and I cannot even figure out what I need to do for this Any help would be appreciated All I have is the menu which looks like this import math print "your options are:" print " " print "1) Area(SQUARE)" print "2) Area(RECTANGLE)" print "3) Area(CIRCLE)" print "4) Perimeter(SQUARE)" print "5) Perimeter(RECTANGLE)" print "6) Perimeter(CIRCLE)" print "7) Exit" while True: selection = raw_input("Please select an option from the menu.: ") python area.py print "Calculate information about a rectangle" length = input("Length:") width = input("Width:") print "Area",length*width print "Perimeter",2*length+2*width print 'To find the area of a rectangle,' print 'Enter the width and height below.' print w = input('Width: ') while w<= 0: print 'Must be a positive number' w = input('Width: ') h = input('Height: ') while h<= 0: print 'Must be a positive number' h = input('Height: ') print 'Width =',w,' Height =',h,' so Area =',area(w,h) Just what don't you understand? If it's really just the math, then go ahead and write dummy versions of the needed functions and control structures, and then ask for help modifying the code. There are bugs in the present code that have nothing to do with math, and I'm not just referring to the line "python area.py". -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to rewrite area.py
hello I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). I am horrible at math and I cannot even figure out what I need to do for this Any help would be appreciated All I have is the menu which looks like this import math print "your options are:" print " " print "1) Area(SQUARE)" print "2) Area(RECTANGLE)" print "3) Area(CIRCLE)" print "4) Perimeter(SQUARE)" print "5) Perimeter(RECTANGLE)" print "6) Perimeter(CIRCLE)" print "7) Exit" while True: selection = raw_input("Please select an option from the menu.: ") python area.py print "Calculate information about a rectangle" length = input("Length:") width = input("Width:") print "Area",length*width print "Perimeter",2*length+2*width print 'To find the area of a rectangle,' print 'Enter the width and height below.' print w = input('Width: ') while w <= 0: print 'Must be a positive number' w = input('Width: ') h = input('Height: ') while h <= 0: print 'Must be a positive number' h = input('Height: ') print 'Width =',w,' Height =',h,' so Area =',area(w,h)___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking for file completion.
Tony Pelletier wrote: Missing a return statement in the case of an exception. Can you explain this? Why would I want the return on the exception? Because if you don't, it will return None. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pyhton editor
From: "Prasad, Ramit" To: "tutor@python.org" Sent: Tuesday, February 21, 2012 10:08 AM Subject: Re: [Tutor] Pyhton editor >>However I stumbled upon PyScripter and I find it really amazing. >Pity it is only for Windows. WINE? Ramit I concur. Pyscripter , though I've only installed it a few days ago, seems to be one of the better ones. I am running it in a virtualbox winXP on top of Linux Ubuntu, but i love the simply way you can use tkinter from a server? No muss no fuss. Just install and go. I understand that the way it had been built, it can't be readily ported to Linux. Mores the pity. Ken Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ 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] Checking for file completion.
On 02/21/2012 05:20 PM, Tony Pelletier wrote: def getReport(service, reportId): reportIds = service.client.factory.create('ArrayOfstring') reportIds.string.append(reportId) try: result = service.client.service.ReportQueryById(reportIds, 'True') if result.Report[0].ReportStatus == 'Processing': print 'Report in Processing state...' time.sleep(3) getReport(service,reportId) Dd you intend to call yourself recursively here? I don't understand all your logic here, but if you really did, I'd at least expect you to save the return value from the recursive call. This is also the first place you're missing a return statement. Is it possible you're trying to use recursion to substitute for a while loop? Generally a bad idea. I did intend it. I'm trying to grab the report right after I send the request in, which probably isn't a great idea, but I'll worry about that after I figure this out. The idea is that I know I'll get result.Report[0].ReportStatus to be 'Processing', so I'm sleeping and doing it over. On the second go around, I get the return. But recursion is not "go around". It creates a new stack frame, all new local variables, It calls that factory thingie again, I have no idea what this library of yours does, so I can't directly advise you, but this code is just wrong. else: filename = result.Report[0].ReportFileArgs.ReportFileArg[0].UserFileName print filename encodedfile = result.Report[0].ReportFileArgs.ReportFileArg[0].EncodedValue encodedstring = encodedfile.encode('utf-8') str_list = [] for line in encodedstring: line = line.rstrip() str_list.append(line) string = ''.join(str_list) data = base64.b64decode(string) outfile = open(filename, 'w') outfile.write(data) outfile.close() shutil.copyfile(filename, os.path.join('files', filename)) print filename + ' report succesfully written out...' logging.info(filename + ' report succesfully written out...') return filename except suds.WebFault as e: print e.fault.detail Missing a return statement in the case of an exception. Can you explain this? Why would I want the return on the exception? I'll answer your question with a question. Just what do YOU think will happen after it prints the e.fault.detail stuff? It'll return to the caller, with a return value of None. You need an explicit return statement to give it a different, explicit value. then from main, I'm using filename to then make the call to getEventAttachments and passing in filename. The None you see is a result of my "print filename" statement. Clearly this is Python 2.x code. print is a statement and has no return value (result). You don't state that this is the whole code, but if so, then you're missing return statements from several exit points in the function. It's probably that missing return statement that gives you the None. Not sure I agree here. Again, if put a 3 sec pause in as mentioned below, I get these successful results. You have a return statement on the else clause, so if it happens to execute that path, you'll get a return value for filename. C:\Python27\python.exe C:/cygwin/home/Tony/code/soaptraining/getEventAttachments.py Deleting "files" directory... "files" directory successfully created... WeeklyDeliveriesReport_2012-02-21.csv WeeklyDeliveriesReport_2012-02-21.csv report succesfully written out... WeeklyDeliveriesReport_2012-02-21.csv - This is the print statement that returns None Rows of data here I print out.. TestWordDoc.docx successfully written out! FREE LEARN TO PLAY HOCKEY PROGRAM.docx successfully written out! bookofruby.pdf successfully written out! EmAlex1.jpg successfully written out! Creating archive... bookofruby.pdf EmAlex1.jpg FREE LEARN TO PLAY HOCKEY PROGRAM.docx TestWordDoc.docx WeeklyDeliveriesReport_2012-02-21.csv Done zipping attachments . Starting file transfer... File attachments.zip successfully transferred. Look, you don't even include the import statements, nor mention what library you're using for this SOAP stuff. So you aren't likely to get help from whoever happens to know that library. Your output reflects running a lot more code than you show here, so we're all just guessing. I can only give you general help on the python code, and that function has 3 return points, but only one of them has a return statement. It recurses without using the results of
Re: [Tutor] Checking for file completion.
>> >> def getReport(service, reportId): >> reportIds = service.client.factory.create('ArrayOfstring') >> reportIds.string.append(reportId) >> >> try: >> result = service.client.service.ReportQueryById(reportIds, >> 'True') >> if result.Report[0].ReportStatus == 'Processing': >> print 'Report in Processing state...' >> time.sleep(3) >> getReport(service,reportId) > > > Dd you intend to call yourself recursively here? I don't understand all > your logic here, but if you really did, I'd at least expect you to save the > return value from the recursive call. This is also the first place you're > missing a return statement. > > Is it possible you're trying to use recursion to substitute for a while > loop? Generally a bad idea. I did intend it. I'm trying to grab the report right after I send the request in, which probably isn't a great idea, but I'll worry about that after I figure this out. The idea is that I know I'll get result.Report[0].ReportStatus to be 'Processing', so I'm sleeping and doing it over. On the second go around, I get the return. > > >> >> else: >> >> filename = >> result.Report[0].ReportFileArgs.ReportFileArg[0].UserFileName >> print filename >> encodedfile = >> result.Report[0].ReportFileArgs.ReportFileArg[0].EncodedValue >> >> encodedstring = encodedfile.encode('utf-8') >> str_list = [] >> for line in encodedstring: >> line = line.rstrip() >> str_list.append(line) >> string = ''.join(str_list) >> data = base64.b64decode(string) >> outfile = open(filename, 'w') >> outfile.write(data) >> outfile.close() >> shutil.copyfile(filename, os.path.join('files', >> filename)) >> print filename + ' report succesfully written >> out...' >> logging.info(filename + ' report succesfully >> written out...') >> return filename >> except suds.WebFault as e: >> print e.fault.detail > > > Missing a return statement in the case of an exception. Can you explain this? Why would I want the return on the exception? > > >> >> then from main, I'm using filename to then make the call to >> getEventAttachments and passing in filename. The None you see is a >> result of my "print filename" statement. >> > > Clearly this is Python 2.x code. print is a statement and has no return > value (result). You don't state that this is the whole code, but if so, > then you're missing return statements from several exit points in the > function. It's probably that missing return statement that gives you the > None. Not sure I agree here. Again, if put a 3 sec pause in as mentioned below, I get these successful results. C:\Python27\python.exe C:/cygwin/home/Tony/code/soaptraining/getEventAttachments.py Deleting "files" directory... "files" directory successfully created... WeeklyDeliveriesReport_2012-02-21.csv WeeklyDeliveriesReport_2012-02-21.csv report succesfully written out... WeeklyDeliveriesReport_2012-02-21.csv - This is the print statement that returns None Rows of data here I print out.. TestWordDoc.docx successfully written out! FREE LEARN TO PLAY HOCKEY PROGRAM.docx successfully written out! bookofruby.pdf successfully written out! EmAlex1.jpg successfully written out! Creating archive... bookofruby.pdf EmAlex1.jpg FREE LEARN TO PLAY HOCKEY PROGRAM.docx TestWordDoc.docx WeeklyDeliveriesReport_2012-02-21.csv Done zipping attachments . Starting file transfer... File attachments.zip successfully transferred. > > > >> Now, if I uncomment that time.sleep(3), it runs flawlessly which I >> think tells me that the file is still being written to. I *think*... >> >> Two questions. >> 1. Is that not it and if so, am I missing something obvious? >> 2. If it is it, is there a way to check to see if the file I'm trying >> to read from is done being written to? >> >> Thanks >> > > > -- > > DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] chat openssl
hello guys hello master of python "Fu" hello I just finished a chat with openssl rewrite this for secure connections. my script is it well written? https://github.com/fakessh/openprojectssl/blob/master/pyCHATopenssl.py can you tell me what is wrong built sincerely -- http://pgp.mit.edu:11371/pks/lookup?op=get&search=0xC2626742 gpg --keyserver pgp.mit.edu --recv-key C2626742 http://urlshort.eu fakessh @ http://gplus.to/sshfake http://gplus.to/sshswilting http://gplus.to/john.swilting signature.asc Description: Ceci est une partie de message numériquement signée ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking for file completion.
On 02/21/2012 01:42 PM, Tony Pelletier wrote: Please post your message again, as a text message rather than an html one. Reading non-trivial python code that's lost all its indentation is impossible. You've done it before, but that case was simple enough to not matter much. -- DaveA Sorry about that. I actually thought i was... my bad... Hi, I'm struggling with what I think seems to be a problem. I've created a program that does numerous SOAP calls. In short, I create a report on a report server, pull that file down then parse that file that's been written locally for data to make more SOAP calls. My problem is I'm grabbing the filename then losing it somewhere along the way. The only thing I can think of is that it's still open/being written and causing me a problem. Main starts like such. def main(): service = Service() cleanup() reportId = createReport(service) #time.sleep(3) filename = getReport(service,reportId) getEventAttachments(service, filename) Here are the results from a test run. Deleting "files" directory... "files" directory successfully created... Report in Processing state... WeeklyDeliveriesReport_2012-02-21.csv WeeklyDeliveriesReport_2012-02-21.csv report succesfully written out... None File still being written out... getReport() returns a filename and you actually see it twice up in the results. def getReport(service, reportId): reportIds = service.client.factory.create('ArrayOfstring') reportIds.string.append(reportId) try: result = service.client.service.ReportQueryById(reportIds, 'True') if result.Report[0].ReportStatus == 'Processing': print 'Report in Processing state...' time.sleep(3) getReport(service,reportId) Dd you intend to call yourself recursively here? I don't understand all your logic here, but if you really did, I'd at least expect you to save the return value from the recursive call. This is also the first place you're missing a return statement. Is it possible you're trying to use recursion to substitute for a while loop? Generally a bad idea. else: filename = result.Report[0].ReportFileArgs.ReportFileArg[0].UserFileName print filename encodedfile = result.Report[0].ReportFileArgs.ReportFileArg[0].EncodedValue encodedstring = encodedfile.encode('utf-8') str_list = [] for line in encodedstring: line = line.rstrip() str_list.append(line) string = ''.join(str_list) data = base64.b64decode(string) outfile = open(filename, 'w') outfile.write(data) outfile.close() shutil.copyfile(filename, os.path.join('files', filename)) print filename + ' report succesfully written out...' logging.info(filename + ' report succesfully written out...') return filename except suds.WebFault as e: print e.fault.detail Missing a return statement in the case of an exception. then from main, I'm using filename to then make the call to getEventAttachments and passing in filename. The None you see is a result of my "print filename" statement. Clearly this is Python 2.x code. print is a statement and has no return value (result). You don't state that this is the whole code, but if so, then you're missing return statements from several exit points in the function. It's probably that missing return statement that gives you the None. Now, if I uncomment that time.sleep(3), it runs flawlessly which I think tells me that the file is still being written to. I *think*... Two questions. 1. Is that not it and if so, am I missing something obvious? 2. If it is it, is there a way to check to see if the file I'm trying to read from is done being written to? Thanks -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking for file completion.
> Please post your message again, as a text message rather than an html one. > Reading non-trivial python code that's lost all its indentation is > impossible. You've done it before, but that case was simple enough to not > matter much. > > > > -- > > DaveA > Sorry about that. I actually thought i was... my bad... Hi, I'm struggling with what I think seems to be a problem. I've created a program that does numerous SOAP calls. In short, I create a report on a report server, pull that file down then parse that file that's been written locally for data to make more SOAP calls. My problem is I'm grabbing the filename then losing it somewhere along the way. The only thing I can think of is that it's still open/being written and causing me a problem. Main starts like such. def main(): service = Service() cleanup() reportId = createReport(service) #time.sleep(3) filename = getReport(service,reportId) getEventAttachments(service, filename) Here are the results from a test run. Deleting "files" directory... "files" directory successfully created... Report in Processing state... WeeklyDeliveriesReport_2012-02-21.csv WeeklyDeliveriesReport_2012-02-21.csv report succesfully written out... None File still being written out... getReport() returns a filename and you actually see it twice up in the results. def getReport(service, reportId): reportIds = service.client.factory.create('ArrayOfstring') reportIds.string.append(reportId) try: result = service.client.service.ReportQueryById(reportIds, 'True') if result.Report[0].ReportStatus == 'Processing': print 'Report in Processing state...' time.sleep(3) getReport(service,reportId) else: filename = result.Report[0].ReportFileArgs.ReportFileArg[0].UserFileName print filename encodedfile = result.Report[0].ReportFileArgs.ReportFileArg[0].EncodedValue encodedstring = encodedfile.encode('utf-8') str_list = [] for line in encodedstring: line = line.rstrip() str_list.append(line) string = ''.join(str_list) data = base64.b64decode(string) outfile = open(filename, 'w') outfile.write(data) outfile.close() shutil.copyfile(filename, os.path.join('files', filename)) print filename + ' report succesfully written out...' logging.info(filename + ' report succesfully written out...') return filename except suds.WebFault as e: print e.fault.detail then from main, I'm using filename to then make the call to getEventAttachments and passing in filename. The None you see is a result of my "print filename" statement. Now, if I uncomment that time.sleep(3), it runs flawlessly which I think tells me that the file is still being written to. I *think*... Two questions. 1. Is that not it and if so, am I missing something obvious? 2. If it is it, is there a way to check to see if the file I'm trying to read from is done being written to? Thanks ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking for file completion.
On 02/21/2012 01:10 PM, Tony Pelletier wrote: Hi, I'm struggling with what I think seems to be a problem. I've created a program that does numerous SOAP calls. In short, I create a report on a report server, pull that file down then parse that file that's been written locally for data to make more SOAP calls. My problem is I'm grabbing the filename then losing it somewhere along the way. The only thing I can think of is that it's still open/being written and causing me a problem. Main starts like such. def main(): service = Service() cleanup() reportId = createReport(service) #time.sleep(3) filename = getReport(service,reportId) getEventAttachments(service, filename) Here are the results from a test run. Deleting "files" directory... "files" directory successfully created... Report in Processing state... WeeklyDeliveriesReport_2012-02-21.csv WeeklyDeliveriesReport_2012-02-21.csv report succesfully written out... None File still being written out... getReport() returns a filename and you actually see it twice up in the results. def getReport(service, reportId): reportIds = service.client.factory.create('ArrayOfstring') reportIds.string.append(reportId) try: result = service.client.service.ReportQueryById(reportIds, 'True') if result.Report[0].ReportStatus == 'Processing': print 'Report in Processing state...' time.sleep(3) getReport(service,reportId) else: filename = result.Report[0].ReportFileArgs.ReportFileArg[0].UserFileName print filename encodedfile = result.Report[0].ReportFileArgs.ReportFileArg[0].EncodedValue encodedstring = encodedfile.encode('utf-8') str_list = [] for line in encodedstring: line = line.rstrip() str_list.append(line) string = ''.join(str_list) data = base64.b64decode(string) outfile = open(filename, 'w') outfile.write(data) outfile.close() shutil.copyfile(filename, os.path.join('files', filename)) print filename + ' report succesfully written out...' logging.info(filename + ' report succesfully written out...') return filename except suds.WebFault as e: print e.fault.detail then from main, I'm using filename to then make the call to getEventAttachments and passing in filename. The None you see is a result of my "print filename" statement. Now, if I uncomment that time.sleep(3), it runs flawlessly which I think tells me that the file is still being written to. I *think*... Two questions. 1. Is that not it and if so, am I missing something obvious? 2. If it is it, is there a way to check to see if the file I'm trying to read from is done being written to? Thanks Tony Please post your message again, as a text message rather than an html one. Reading non-trivial python code that's lost all its indentation is impossible. You've done it before, but that case was simple enough to not matter much. -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pyhton editor
>>However I stumbled upon PyScripter and I find it really amazing. >Pity it is only for Windows. WINE? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] '__name__' == '__main__'
On 21/02/12 04:55, Michael Lewis wrote: I am back to being confused. I just tried running the module without first importing it, and it worked just fine. How do I do this properly to where the module only runs if I import it? Whoooah! That paragraph is so full of ambiguities as to be meaningless. What exactly did you do to "run it without first importing it"? And what happened that was "just fine"? And what do you expect when you say "properly"? What is it that you are expecting to happen? And what does happen? The module always runs when you import it regardless of whether you have an if statement, the only thing that changes is the value of __name__. There is no other magic, the if statement is is just like any other piece of Python code. But, the file will also run if you execute it, again the only difference is the value of __name__. When you import the file it is run with __name__ set to the filename. When you execute the file __name__ is set to "__main__" -- Alan G 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] __name__=='__main__'
On 21/02/12 03:07, Michael Lewis wrote: Now that I am better understanding '__name__'=='__main__', > if '__name__' == '__main__': > GetUserInput() Note that __name__ is a variable so it should NOT have quotes around it. What you are doing is comparing two literal strings which are obviously different so the if block never gets executed. It has to be: if __name__ == '__main__': GetUserInput() HTH -- Alan G 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