[Tutor] socket question
When I receive a 4-bytes integer using socket.recv, it is stored in a string. How to convert this string to a integer? Thanks in advance. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Introduction
Hello. I am new to the mailing list and to Python. My knowledge of Python comes almost strictly from Nick Parlante's classes on YouTube that I've watched over the last week or so. I'm not certain why I'm diving into Python. My only coding experience has been using Bash scripts on my Ubuntu system for the past half dozen years, and so far I'm not particularly convinced that Python has any advantage FOR ME over what I have been using. In my Bash scripts I make generous use of sed and grep, with the occasional use of awk -- batch renaming of files, pulling exif date information from (manually) downloaded jpegs and adding that date to the front of file names, removing url '%' coding on photos and replacing it with "real" text, and the occasional foray into network stuff in conjunction with vlc or netcat. By no means am I a pro with Bash - only in the last six months have I really began to understand how to use arrays rather than temp files - but I can usually accomplish what I set out to do no matter how ugly the coding! The potential cross-platform use of Python is probably one of the major reasons for my interesttho' I don't think I write anything anyone else would want...and although, as I look at my Python code so far, it's definitely hard-coded for a Linux system :-p. So much for that reasoning But here I am - I am looking forward to learning from everyone, but keep the terminology as simple as possible, if you please - I'm only now beginning to understand what objects arelol ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First program
Andre Engels wrote: On 3/12/10, yd wrote: Hi, I am new to programming, altough i have read a few books about OOP and O'Reily's Learning Python. I would like some critique on my first program, is it normal for it to be this long to do something simple? Well, many of your lines are user interface. Writing two lines of text to the user will in general cost you (at least) two lines of code. I know i could have turned some of these things into classes and functions but i don't know how to do that yet. I definitely see use for functions (long lists of if...elif.. are usually better modeled using functions and a dictionary); using classes feels like overkill for something this simple. Some critique of the algorithm and writing style or anything in general would help and any pointers would be appreciated. General remark: The usual number of spaces indented per level is 4, rather than the 2 that you use. This makes it easier to see the indentation level at first glance. #title Area calculator #author Yudhishthir Singh #welcome screen msg = 'Welcome to the area calculator program ' print(msg) print('-'*len(msg)) loop = 'y' print() while loop == 'y': #Choices menu print('Please select a shape\n') print('1. Rectangle') print('2. Square') print('3. Parallelogram ') print('4. Trapezoid ') print('5. Circle ') print('6. Ellipse') print('7. Traingle\n') print('-'*len(msg)) choice = input('\nPlease enter your choice: ') if choice.isdigit() ==True: choice = int(choice) 1. The if can be shortened to if choice.isdigit(): 2. This thing can be removed completely if you chance the if-statements below to if choice == "1" etcetera. if choice ==1: #Rect height = input('please enter the height: ') width = input('please enter the width: ') height = int(height) width = int(width) areaRectangle = height*width print('\nThe area of a rectangle with {0} height and {1} width is '.format(height,width),areaRectangle,'\n') I think it's ugly to mix styles here - either use format or use commas, not both elif choice ==2: #Square side = input('enter the height or width: ') side = int(side) areaSquare = side**2 print('\nThe area of a square with a height or width of {0} is '.format(side), areaSquare,'\n') elif choice ==3: #Parallelogram height = input('enter the height: ') base = input('enter the width aka base: ') height = int(height) base = int(base) areaParallelogram = height*base print('\nThe area of a parrallelogram with height {0} and width {1} is '.format(height,base), areaParallelogram,'\n') elif choice ==4: #Trapezoid height = input('enter the height: ') base1 = input('enter the width of shorter side: ') base2 = input('enter the width of longer side: ') height = int(height) base1 = int(base1) base2 = int(base2) areaTrapezoid = (height/2)*(base1+base2) print('\nThe area of a trapezoid with height {0} ,base {1} and {2} is '.format(height,base1,base2), areaTrapezoid, '\n') elif choice ==5: #Circle radius = input('radius: ') radius = int(radius) areaCircle = 3.14*(radius**2) print('\nThe area of a circle with radius {0} is '.format(radius), areaCircle, '\n') elif choice ==6: #Ellipse radius1 = input('enter length of radius 1: ') radius2 = input('enter length of radius 2: ') radius1 = int(radius1) radius2 = int(radius2) areaEllipse = 3.14*radius1*radius2 print('\nThe area of an ellipse with radii of length {0} and {1} is '.format(radius1,radius2), areaEllipse, '\n') elif choice ==7: #Triangle base = input('enter base: ') height = input('enter height: ') base = int(base) height = int(height) areaTriangle = (1/2 *base)*height print('\nThe area of a triange with height {0} and base {1} is '.format(height,base), areaTriangle, '\n') else: raise Exception('{0}, is not a valid choice'.format(choice)) This will cause the program to stop-with-error if something wrong is entered. I think that's quite rude. I would change this to: else: print('{0}, is not a valid choice'.format(choice)) Here's what I get from that, could you please explain why? >>> print('{0}, is not a valid choice'.format(choice)) Traceback (most recent call last): File "", line 1, in AttributeError: 'str' object has no attribute 'format' >>&
Re: [Tutor] First program
Luke Paireepinart wrote: On Fri, Mar 12, 2010 at 4:03 AM, yd <mailto:ydmt...@gmail.com>> wrote: Hi, I am new to programming, altough i have read a few books about OOP and O'Reily's Learning Python. I would like some critique on my first program, is it normal for it to be this long to do something simple? I know i could have turned some of these things into classes and functions but i don't know how to do that yet. Some critique of the algorithm and writing style or anything in general would help and any pointers would be appreciated. Thanks. One thing you should do is use more indentation. Your program structure is VERY hard to read with single space indentations. Consider using 4-spaces. This is not overtly long, I would say it's reasonable for a first program. There are some things that you could probably group together, though. Remember that code reuse is one of the core tenets of computer programming! One example: area of square, parallelogram and rectangle are all the same. You could do something like this (assuming user enters strings as choice (rather than ints)): if choice in ['rectangle', 'square', 'parallelogram']: height = int(raw_input("Height: ")) if choice != 'square': width = int(raw_input("Width: ")) else: width = height print "A %s with dimensions %sx%s has an area of %s." % (choice, height, width, width*height) Hello, Isn't it a little more understandable to use a construct like the following? print "The area of a " + Choice + "is " str(Width) + " x " + str(Height) + " equals " + str(Width * Height) + " square feet" The area of a rectangle is 12 x 10 equals 120 square feet. I find that putting the variables on the end like that, when you're not actually applying any special formatting to them makes it less readable when I'm debugging my stuff, or when someone else is reading my code, and trying to understand it. Later, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Opening a dos exe
Emile van Sebille wrote: On 3/10/2010 11:33 AM Armstrong, Richard J. said... The problem comes in that the dos program requires three inputs (input1.txt, input2.txt and input3.txt - see attached picture) but I cannot find a way of getting this information to the dos program from python. Any ideas? You could use os.system("startprogram.bat"), and create startprogram.bat to run the dos program, and feed it the files, either all at once, or one at a time via the command line if it accepts command line input. You could write out startprogram.bat programatically, just before you call it, then remove it after running it to reduce clutter. Hope this is what you're looking for. Later, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Escaping a single quote mark in a triple quoted string.
Hello, I am getting the following - >>> String = """http://www.rayslinks.com";>Ray's Links""" >>> String 'http://www.rayslinks.com";>Ray\'s Links' Note the magically appearing back slash in my result string. Now I tiry to escape the single quote. >>> String = """http://www.rayslinks.com";>Ray\'s Links""" >>> String 'http://www.rayslinks.com";>Ray\'s Links' Once again the unwanted back slash appears. >>> NewString = """'""" >>> NewString "'" Hmmm, no back slash this time... >>> String = """http://www.rayslinks.com";>Ray""" + """'""" + """s Links""" >>> String 'http://www.rayslinks.com";>Ray\'s Links' Why did quoting the single quote work in NewString when I triple quoted just the single quote, but not in the other examples where the result shows a back slash before my singe quote in String? Is there a proper way to do this? Thanks, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Opening a dos exe
Alan Gauld wrote: "Ray Parrish" wrote but I cannot find a way of getting this information to the dos program from python. Any ideas? You could use os.system("startprogram.bat"), and create startprogram.bat to run the dos program, and feed it the files, either all at once, or one at a time via the command line if it accepts command line input. I don't think you can do the second option with a bat file. There is no way to interactively respond to the program once it starts. Thats why WSH is better for that kind of interactive input. Or just use subprocess.Popen... OK, it was not clear to me that he needed to be interactive with the dos program. He just said he needed to feed those files to the dos program, and I assumed he meant on the command line within a dos box, which can indeed be solved by running a batch file, if the dos program accepts command line parameters.. A good tool for writing interactive scripts used to be WinBatch, but I haven't used, or seen it anywhere for years. It would have to be installed on the machine you wanted to get interactive with a dos program however. I remember WinBatch from back in the Windows 3.1 days, and am not sure if they are still keeping it up to date. Later, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First program
Steven D'Aprano wrote: On Sat, 13 Mar 2010 01:04:42 pm Ray Parrish wrote: print "A %s with dimensions %sx%s has an area of %s." % (choice, height, width, width*height) Hello, Isn't it a little more understandable to use a construct like the following? print "The area of a " + Choice + "is " str(Width) + " x " + str(Height) + " equals " + str(Width * Height) + " square feet" The area of a rectangle is 12 x 10 equals 120 square feet. I find that putting the variables on the end like that, when you're not actually applying any special formatting to them makes it less readable when I'm debugging my stuff, or when someone else is reading my code, and trying to understand it. Of course you are welcome to use whatever coding standards you like, but I think you will find that among experienced coders, you are in a vanishingly small minority. As a beginner, I found string interpolation confusing at first, but it soon became second-nature. And of course, there are legions of C coders who are used to it. I find an expression like: "The area of a " + Choice + "is " str(Width) + " x " + str(Height) + "equals " + str(Width * Height) + "square feet" difficult to follow: too many quotes, too many sub-expressions being added, too many repeated calls to str(), it isn't clear what is the template and what is being inserted into the template. It is too easy to miss a quote and get a SyntaxError, or to forget to add spaces where needed. To me, this is MUCH easier: template = "The area of a %s is %s x %s equals %s square feet" print template % (Width, Height Width*Height) One pair of quotes instead of five, no problems with remembering to add spaces around pieces, and no need to explicitly call str(). OK, that does seem a bit easier now to me. I'm going to have to read up on the %s, and any other formatting % codes there are however, since I'm dead green in Python yet. 8-) So, would I read about those in the string module portion of the documentation? Thanks, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First program
Alan Gauld wrote: "Ray Parrish" wrote print "A %s with dimensions %sx%s has an area of %s." % (choice, height, width, width*height) Isn't it a little more understandable to use a construct like the following? print "The area of a " + Choice + "is " str(Width) + " x " + str(Height) + " equals " + str(Width * Height) + " square feet" It depends on where you come from. Those of us brought up on C or COBOL are used to separating the presentation from the data. Those brought up with PASCAL and BASIC are used to iterleaving data with presentation. One thing - you don't need all the str() calls in your example, print already calls str() for you. Also comma separators are better than + signs since the plus operation on strings is quite expensive - you create a new string for each addition. HTH, Thanks for the tips. If I understand you correctly I can do the call this way? - print "The area of ", Choice, " is ", Width, " x ", Height, " equals ", (Width * Height), " square feet" That eliminates the redundancy, and is quite readable to me. I like it. 8-) Later, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First program
Luke Paireepinart wrote: On Sat, Mar 13, 2010 at 3:03 AM, Alan Gauld <mailto:alan.ga...@btinternet.com>> wrote: "Ray Parrish" mailto:c...@cmc.net>> wrote print "A %s with dimensions %sx%s has an area of %s." % (choice, height, width, width*height) Isn't it a little more understandable to use a construct like the following? print "The area of a " + Choice + "is " str(Width) + " x " + str(Height) + " equals " + str(Width * Height) + " square feet" It depends on where you come from. Those of us brought up on C or COBOL are used to separating the presentation from the data. Those brought up with PASCAL and BASIC are used to iterleaving data with presentation. One thing - you don't need all the str() calls in your example, print already calls str() for you. Also comma separators are better than + signs since the plus operation on strings is quite expensive - you create a new string for each addition. print actually doesn't call str if you use concatenation. So the str() calls are necessary if you do not use "," but use "+" instead. So there are at least 2 reasons why + is worse than comma. Another thing to be aware of is that if you use commas, print inserts a space in the string, which may be either an advantage or a disadvantage depending on what you're trying to do. -Luke Ahhh, thank you for the clarifications. for the cases where spaces are needed it the commas seem like a pretty good way to do it, but when I need to add together stuff with no spaces I'll try the formatted method. Thanks again, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First program
Luke Paireepinart wrote: Ray, please reply on-list in the future in case someone else has input. On Fri, Mar 12, 2010 at 8:01 PM, Ray Parrish <mailto:c...@cmc.net>> wrote: Luke Paireepinart wrote: print "A %s with dimensions %sx%s has an area of %s." % (choice, height, width, width*height) Isn't it a little more understandable to use a construct like the following? >>> print "The area of a " + Choice + "is " str(Width) + " x " + str(Height) + " equals " + str(Width * Height) + " square feet" The area of a rectangle is 12 x 10 equals 120 square feet. I find that putting the variables on the end like that, when you're not actually applying any special formatting to them makes it less readable when I'm debugging my stuff, or when someone else is reading my code, and trying to understand it. Your version creates at least 10 intermediate strings before outputting. Remember strings are immutable in Python. So you're constructing strings The area of a The area of a rectangle The area of a rectangle is 12 The area of a rectangle is 12 The area of a rectangle is 12 x 10 The area of a rectangle is 12 x 10 The area of a rectangle is 12 x 10 equals 120 The area of a rectangle is 12 x 10 equals 120 The area of a rectangle is 12 x 10 equals 120 square feet With string formatting you avoid all of these intermediate strings, so it's arguably more efficient. Other than just viewing from a performance standpoint though, I find it much easier to read my version, because any computation required takes place at the end of the line. For example, your inline str(width*height) requires you to read the whole line to see it. It's really a personal thing, it's easier for me to read the formatting version than the string concatenation version, in most cases. Now if you had used the comma convention I would have seen your point. This is, I think, the easiest to read of all 3 area = width * height print "The area of a", choice, "is", width, "x", height, ", which equals", area, "square feet." Also, why are you capitalizing variable names? That's a pretty unusual convention. -Luke Thanks for letting me know how inefficient my method is. I'll remember that, and apply your suggestions to my code from now on. So, you're saying that the commas method also does not suffer from the overhead of creating a bunch of individual strings? As far as the capitalizations, it's just a habit I've held over from my Visual Basic days, and earlier programming. It's a little easier for me to pick out the individual words in a variable like ThisPerson as opposed to thisperson. I have been made aware that Python standard coding practice requires lower case variable names, and as soon as I can force myself to do it that way, or can remember to post that way I will be adopting the in place standards and conventions. Is it actually supposed to be this_person? I read part of the standards document, but can not remember right off the top of my head if underlines between words is required. Thanks, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First program
Andre Engels wrote: On Sat, Mar 13, 2010 at 3:11 AM, Ray Parrish wrote: Andre Engels wrote: On 3/12/10, yd wrote: else: raise Exception('{0}, is not a valid choice'.format(choice)) This will cause the program to stop-with-error if something wrong is entered. I think that's quite rude. I would change this to: else: print('{0}, is not a valid choice'.format(choice)) Here's what I get from that, could you please explain why? You're probably using Python 2.4 or 2.5; the .format method has been introduced in Python 2.6, and is considered the 'standard' way of working in Python 3. For older Python versions, this should read print('%s, is not a valid choice'%(choice)) Yes, I'm using 2.45.2 as that is the highest version available in the Ubuntu repositories, and I'd like to keep it simple for users of programs i write. If I install a higher version from somewhere other than the repositories it will force users of my programs to do the same, and the repositories are the trusted source of software for Ubuntu, and other Linux users. Thanks for being so observant. Later, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Escaping a single quote mark in a triple quoted string.
Sander Sweers wrote: On 13 March 2010 18:33, Ray Parrish wrote: Hello, I am getting the following - String = """http://www.rayslinks.com";>Ray's Links""" String 'http://www.rayslinks.com";>Ray\'s Links' Note the magically appearing back slash in my result string. It is not really there. When you have a single quote in a single quote string it need to be escaped with a backslash. Simulary a double quote in a double quote string. The triple quote string does this for you. When you write the string to a file the backslash will "magically" disappear. Now I tiry to escape the single quote. String = """http://www.rayslinks.com";>Ray\'s Links""" String 'http://www.rayslinks.com";>Ray\'s Links' Once again the unwanted back slash appears. See above single quotes in single quote string need to be escaped. NewString = """'""" NewString "'" Hmmm, no back slash this time... Correct, here you have a single quote in a double quote string. String = """http://www.rayslinks.com";>Ray""" + """'""" + """s Links""" String 'http://www.rayslinks.com";>Ray\'s Links' Why did quoting the single quote work in NewString when I triple quoted just the single quote, but not in the other examples where the result shows a back slash before my singe quote in String? Is there a proper way to do this? You are trying to solve something that is not really a problem. What is however is your usage of a single quote in html text. You need to replace it with ' or ‘. Greets Sander Thanks for your quick answer. I'll accept that there will not be a back slash in my file when I write it then. I was not aware that single quotes were bad news in HTML. I don't think I've ever experienced a problem using them myself, but will adjust, and start using the & code for it instead. Later, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First program
Ken G. wrote: I am using Ubuntu 9.04 and I have versions 2.6.2 and 3.0.1+ installed. Look for IDLE in Add/Remove Applications. Perhaps, you may have a different version of Ubuntu. Ken Ray Parrish wrote: Yes, I'm using 2.45.2 as that is the highest version available in the Ubuntu repositories, and I'd like to keep it simple for users of programs i write. If I install a higher version from somewhere other than the repositories it will force users of my programs to do the same, and the repositories are the trusted source of software for Ubuntu, and other Linux users. Thanks for being so observant. Later, Ray Parrish That should have been version 2.5.2 without the 4 I typoed. I'm using Hardy Heron, 8.04, and plan to stick with it until version 10 comes out as it is the next LTS version. I'm eyeballing Idle in Synaptic, and it appears to be an IDE for version 2.5 of Python for my version of Ubuntu. Idle is available for version 2.4 there as well. I'm pretty used to writing all of my code with only the aid of syntax highlighting, but have been hankering for an editor that will allow tabbed, or collapsible functions, and collapsible block elements. Does Idle do that? I guess I'll just go ahead and install it, and give it a try. Some IDEs I don't like with their project centric viewpoint, and my inability to quickly absorb their project file structures details to the point I can use them. If that doesn't happen pretty much within ten or fifteen minutes I go back to gedit. 8-) Later, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Escaping a single quote mark in a triple quoted string.
Steven D'Aprano wrote: On Sun, 14 Mar 2010 04:33:57 am Ray Parrish wrote: Hello, I am getting the following - >>> String = """http://www.rayslinks.com";>Ray's Links""" >>> String 'http://www.rayslinks.com";>Ray\'s Links' Note the magically appearing back slash in my result string. You are confusing the printed representation of the string with the contents of the string. The backslash is not part of the string, any more than the leading and trailing quotes are part of the string. They are part of the display of the string. Consider: s = "ABC" # Three characters A B C. s # Looks like five? 'ABC' len(s) # No, really only three. 3 The quotes are not part of the string, but part of the printable representation. This is supposed to represent what you would type to get the string ABC. You have to type (quote A B C quote). Now consider: s = """A"'"B""" # Five chars A double-quote single-quote d-quote B s # Looks like eight? 'A"\'"B' len(s) # But actually only five. 5 When printing the representation of the string, Python always wraps it in quotation marks. If the contents include quotation marks as well, Python will escape the inner quotation marks if needed, but remember this is only for the display representation. If you want to see what the string looks like without the external quotes and escapes: print s A"'"B >>> NewString = """'""" >>> NewString "'" Hmmm, no back slash this time... In this case, the string itself only contains a single-quote, no double-quote, so when showing the representation, Python wraps the contents with double-quotes and there is no need to escape the single-quote. Python's rules for showing the representation of the string includes: * wrap the string contents in single quotes ' * unless the string contains single quotes, in which case wrap it in double quotes " and display the single quotes unescaped * unless the string contains double quotes as well, in which case wrap it in single quotes and escape the inner single quotes. But remember: this is only the display of the string, not the contents. Thank you, that was a very concise description, and has aided my comprehension greatly. Now if I can just keep it separate from the syntax in JavaScript, I'll be doing good. I keep a good record of these forum posts, so I can re-read this if necessary. Later, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Declaring a compound dictionary structure.
Hello, I am stuck on the following - # Define the Dates{} dictionary structure as a dictionary # containing two dictionaries, each of which contains a list. Dates = {Today:{ThisIPAddress:[]}, Tomorrow:{ThisIPAddress:[]}} How do I pass this declaration empty values for Today, Tomorrow, and ThisIPAddress to initially clare it? I have managed to pass it [] as an empty list, but passing # "" as an empty dictionary label does not work correctly. Dates = {"":"":[]}, "":{"":[]}} The above is what I tried, and that creates a dictionary with index values of "" for all of the key values from the previous declaration. Is there a way to create this comound dictionary structure with no key values defined at all to begin with? The reason I'd like to know is that with the second declaration the "" indexed keys have to be removed after assigning at least one key value with a non-blank name. The idea behind the structure is to sort through a server log that contains entries for two dates, collecting a pair of dictionaries of ip address indexed server log lines which can then be iterated over to extract daily visit counts, and other extractable data sorted by date, and visitor. The need would not arise if the log files did not contain two dates each, but my service provider rotates their server logs around 2 am, so I always get a few entries for the next day in every log file. Thanks, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] KeyError: '61.135.168.82' with dictionary.
Hello, The following code works interactively, but when ran from a script, I get the errors, after the second code block, which is the code from the script. >>> lineList = [] >>> thisIPAddress = '61.135.168.82' >>> date = "2010 3 12" >>> dates = {date:{thisIPAddress:lineList}} >>> dates[date][thisIPAddress] [] >>> dates[date][thisIPAddress].append(16) >>> dates[date][thisIPAddress] [16] >>> dates[date][thisIPAddress].append(17) >>> dates[date][thisIPAddress] [16, 17] >>> Script code begins here - thisIPAddress = columns[10] lineList = [] if date == "": date = columns[0] dates = {date:{thisIPAddress:lineList}} # For each date in the input file collect an array of log lines # for each unique ip address. date = columns[0] dates[date][thisIPAddress].append(eachLine) Error messages follow - Traceback (most recent call last): File "/home/ray/LogAnalyzer/iis-log-analyze.py", line 2519, in ReadInDaysLog(tempLogName, countryCodes) File "/home/ray/LogAnalyzer/iis-log-analyze.py", line 2241, in ReadInDaysLog dates[date][thisIPAddress].append(eachLine) KeyError: '61.135.168.82' As you can see, it is tossing a key error on the same ip address that was used in the interactive code successfully, I can not figure out what to change to make the script work. Does someone know why this happens? Thanks, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Speech recognition, and synthesis
Hello, Are there any Python libraries that deal with speech recognition, and speech synthesis? If so, where are they available, and are there any open source versions? Thanks for any help you can be. Later, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Declaring methods in modules.
Hello, I am working on some stuff, and I would like to be able to write a module which can be imported, and after it's been imported I would like to be able to access it's functions as methods. In other words, if I do the import of module ISPdetector, I want to then be able to make calls like the following - ipAddress = "123.123.123.123" emails = ipAddress.GetEmailAddresses() where GetEmailAddresses() is defined in module ISPdetector. Do I just wite that function in ISPdetector.py as a normally deffed function, or does it have to be part of a class within the module? Thanks for any help you can be. Later, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Passing headers with httplib
Hello, I am trying to figure out how to send cookie data with an httplib request command. Here is what the doc says - request( method, url[, body[, headers]]) This will send a request to the server using the HTTP request method method and the selector url. If the body argument is present, it should be a string of data to send after the headers are finished. The header Content-Length is automatically set to the correct value. The headers argument should be a mapping of extra HTTP headers to send with the request. My question is how do I formulate a "mapping" of a header for a few cookies? Here are the cookies I would like to send with the request - TVGID=029690D849714243A9DDEA34652CA804; Provider=Broadcast; __qca=P0-547310088-1271379357584; LastGrid=fmt=0&srvid=20442&gridmins=120&gridyr=2010&gridmo=4&griddy=15&gridhr=20&chanrow=1&genre=0&favchan=false&magic=1269|9898&magictype=0&zip=&music=1&ppv=1&24hr=1&HDTVOnly=false; s_cc=true; s_sq=%5B%5BB%5D%5D; wtpgcnt=1; s_vi=[CS]v1|25E3DAD0050118C7-610E60004530[CE]; base_domain_4631b4ff1e53d450c3f9726dd45be7de=tvguide.com; rsi_ct=2010_4_15:6; Thanks for any help you can be, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing headers with httplib
Ray Parrish wrote: Hello, I am trying to figure out how to send cookie data with an httplib request command. Here is what the doc says - request( method, url[, body[, headers]]) This will send a request to the server using the HTTP request method method and the selector url. If the body argument is present, it should be a string of data to send after the headers are finished. The header Content-Length is automatically set to the correct value. The headers argument should be a mapping of extra HTTP headers to send with the request. My question is how do I formulate a "mapping" of a header for a few cookies? Here are the cookies I would like to send with the request - TVGID=029690D849714243A9DDEA34652CA804; Provider=Broadcast; __qca=P0-547310088-1271379357584; LastGrid=fmt=0&srvid=20442&gridmins=120&gridyr=2010&gridmo=4&griddy=15&gridhr=20&chanrow=1&genre=0&favchan=false&magic=1269|9898&magictype=0&zip=&music=1&ppv=1&24hr=1&HDTVOnly=false; s_cc=true; s_sq=%5B%5BB%5D%5D; wtpgcnt=1; s_vi=[CS]v1|25E3DAD0050118C7-610E60004530[CE]; base_domain_4631b4ff1e53d450c3f9726dd45be7de=tvguide.com; rsi_ct=2010_4_15:6; Thanks for any help you can be, Ray Parrish OK, I got it figured, but still no luck, passing the cookies didn't help me get at the search results I was trying to get. Here is the code for passing cookies - connection = httplib.HTTPConnection("www.tvguide.com", port) connection.putrequest("GET", "/listings/default.aspx?keyword=Star+Trek") connection.putheader("Cookie", "TVGID=029690D849714243A9DDEA34652CA804; Provider=Broadcast; __qca=P0-547310088-1271379357584; LastGrid=fmt=0&srvid=20442&gridmins=120&gridyr=2010&gridmo=4&griddy=15&gridhr=20&chanrow=1&genre=0&favchan=false&magic=1269|9898&magictype=0&zip=&music=1&ppv=1&24hr=1&HDTVOnly=false; s_cc=true; s_sq=%5B%5BB%5D%5D; wtpgcnt=1; s_vi=[CS]v1|25E3DAD0050118C7-610E60004530[CE]; base_domain_4631b4ff1e53d450c3f9726dd45be7de=tvguide.com; rsi_ct=2010_4_15:8; rsi_segs=D04451_10006|D04451_10077|D04451_10089|D04451_10116; __utma=208178903.2088698592.1271379370.1271389872.1271398039.3; __utmc=208178903; __utmz=208178903.1271398041.3.3.utmccn=(referral)|utmcsr=tvguide.com|utmcct=/search/index.aspx|utmcmd=referral; zip=97424; ServiceID=20442; srvid=20442; ev1=star%20trek;") connection.endheaders() response = connection.getresponse() headers = response.getheaders() print headers fileContents = response.read() Later, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Boa Constructor list control
Hello, I am just learning how to use Boa Constructor to make GUI apps, and am having some problem with understanding the list control. The list control has a property called columns, but I cannot figure out how to add columns, and specify names for them. When I click the column property a small window opens up with it's title set to col1 something with the word "Name" in a label on it. Subsequent clicks on the column properry of the list control just brings this little window up again. I cannot change the text in the label of that small window to the name I want for a column, and I cannot figure out how to add more columns to the list control. When the small column window is selected no properties show for it in the Inspector window. Can anyone tell me how to use this control? I tried using the Boa Constructor help menu, and it led me to a very brief description of the list control, with no details on what it's properties were even. Thanks, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Boa Constructor list control
Ray Parrish wrote: Hello, I am just learning how to use Boa Constructor to make GUI apps, and am having some problem with understanding the list control. The list control has a property called columns, but I cannot figure out how to add columns, and specify names for them. When I click the column property a small window opens up with it's title set to col1 something with the word "Name" in a label on it. Subsequent clicks on the column properry of the list control just brings this little window up again. I cannot change the text in the label of that small window to the name I want for a column, and I cannot figure out how to add more columns to the list control. When the small column window is selected no properties show for it in the Inspector window. Can anyone tell me how to use this control? I tried using the Boa Constructor help menu, and it led me to a very brief description of the list control, with no details on what it's properties were even. Thanks, Ray Parrish OK, I've discovered the collection editor, and now know how to use it, but when I click the new button in the collection editor for a list control, it pops up an error message stating that the list needs to be created with the wx.LC_REPORT flag, and I have no idea how to accomplish that. Could someone please enlighten me? Thanks, Ray Parrish -- Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Help on finding the 1000th prime
I have posted this on other lists, but have just discovered this one. Can someone give me help on writing the code necessary to find the 1000th. prime number. I know I will have to use a while loop, but I can't seem to get the body of the code to function rightly. I would appreciate any help. I am taking the online course Introduction to Computer Science and Programming from the MIT website and this is one of their assignments. The on campus students are able to collaborate with one another, but I live in Ohio. Thanks, Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] A way to search archives?
Is there a way to search the archives? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] parsing a continuous log file
Hello I need some help. I am working with a program that dumps a continuous file while the program is running. This file contains loads of information and I am only looking for a small amount of the data. I have written the program below: import re,os fopen = open("c:\\data.txt",'r') lines = fopen.readlines() fopen.close() def parser(): ul = r"dataRate=(\w+)" count = 0 for line in lines: count = count + 1 match1 = re.search(ul,line) if match1: print match1.group(1) parser() data.txt file content dataRate=104 dataRate=107 dataRate=103 dataRate=102 this was an example the file contains much more. This works but it doesn't show me the results real time. I would like this program to keep on running while the program is running once the program is closed and the file stops growing it should exit. I was checking with google and came accross a command used in UNIX called the tail command. May be someone can help me to achieve the same result with modifying the above code? Also the file could be up to 200 MB long. Many thanks for your kind help. /Ray - Be a better sports nut! Let your teams follow you with Yahoo Mobile. Try it now.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] date conversion
I would like Python to convert a date returned by MySQL (2006-04-05) to a user readable format such as 05-Apr-2006 for display and then to convert it back to ISO format for update. What is the most convenient way of doing this? I'm struggling to understand the datetime module's functionality. Ray Allen ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Ftp files
Hi I have just started to learn Python and think it is a superb language. I am faced with an issue that I would like some help with. I need to fetch files on a daliy basis from a unix machine. I would like to run a batch command for this. I would also like to automate this task. The files are stored on the unix box; are hourly files with date and time as the file name. What I would like to do is log in to the relevant directory and fetch the files for that day. I have managed to log in to the ftp site and navigate to the directory where the files are. I have also used the following command to look for a particular day: dateMatch = str(localtime()[0])+str(localtime()[1])+str(localtime()[2]) This will give me the date portion of the string to search in the file name using: re.search(dateMatch,filename) I am now stuck on how to use the files = listdir(pathName) to get a list of the files and by using the following code: for i in files: matchFile = search(dateMatch,i) if matchFile: get the file What I would like to know is how to get the file using ftplib functions. Your expert advice would be very helpful. Please feel free to suggest some code and an explanation... I need help on the following: -How to get a function to return a list of the files on the directory -Using this list I should be able to use the for loop to match the date case and - fetch the files using the get command. How to use the get command to fetch the files in the list prevously where the match was found and store this in my local directory? - Also how to run this python file daily automatically? Looking forward to you responses.. BR Ray __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] control multiple FTP sessions using multiple ip connections via different com ports
Hi Kind people I have been successful to write an ftp script that logs into a server and collects files. What I would like to do but have no knowledge of is that I would like to run multiple ftp sessions using one laptop with two different connections. What I mean here is that you have a ethernet card connection to the ip world and then you have another connection using your EDGE terminal so in other words you have two ip address and I would like to write a script that controls which ip address to use or with com port to use. I was hoping someone could help to define how to force the ftp script to use the relevant connections on one laptop. You help and guidance will be most appreciated. Many thanks Ray - Never miss an email again! Yahoo! Toolbar alerts you the instant new Mail arrives. Check it out.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] control multiple FTP sessions using multiple ip connectionsvia different com ports
Hi Alan et al Many thanks for your time on this. I was referring to the client end. An EDGE terminal is a phone that has the capability of connecting to the internet. We use mobile phones to make a voice call that make use of a circuit switched connection. By using a GPRS connection we can use the mobile device to connect to the packet switched domain. You might have heard about making data connection using your phone like GPRS, 3G etc. EDGE is just faster than a GPRS connection and 3G is supposedly faster than GPRS and EDGE. May be I can give you more information about what I am trying to do. So you can understand what I am trying to achieve. Basically, I am trying to decide whether I should change my ADSL fixed solution to a higher speed connection using a mobile solution. Where I live the mobile operator is offering a mobile solution which is cheaper than my fixed solution .and is faster than my ADSL connection, please read on I have my ADSL broadband connection to my service provider that I use to connect to the internet. I have just bought a GPRS/EDGE/3G terminal and wanted to benchmark the speed I am getting by using my mobile device as opposed to my fixed connection. My desktop machine is connected to my ADSL provider using a USB modem which is assigned a particular COM port on my machine. Then I have connected my mobile handset also using a USB connection connected to a different COM port. Now I have two ip addresses ADSL COM port 4 with ip addres from my ADSL service provider Mobile Handset COM port 5 with another ip address from my mobile provider I have written a script that connects to a ftp server within my home country and downloads a file. But this script uses one of the connections above. There must be away to tell the script and control which connection to use. So I can get to see real time which connection is faster. So I can run the script pointing to one IP address and at the same time run another script using the other connection. I think there must be a method that finds out which connection is connected to which com port and then in my script I need to point towards that connection so my script knows which channel to use when downloading the file. I hope this helps sorry for too much text couldnt really find a simpler way to explain this. Once again I really appreciate the help on this forum./Ray Alan Gauld <[EMAIL PROTECTED]> wrote: "ray sa" wrote > I have been successful to write an ftp script that logs > into a server and collects files. > ...I would like to run multiple ftp sessions using one laptop > with two different connections. Do you mean you want the server on the laptop accepting using two connections or do you mean that you want the client on the laptop and have different sessions sending outgoing requests to the server via two different IP addresses? If the former its easy, just set up two servers, one on each IP address. The port will nbe the same on both, ISTR its port 21 for ftp? If you want to specify which IP address you send the client request from, I'm afraid I have no idea how you specify that. I've only ever used multiple network cards at the server end! > another connection using your EDGE terminal As a matter of interest what is an EDGE terminal? A new term for me... > I would like to write a script that controls which ip > address to use or with com port to use. Until we know which end you mean its hard to hgive more specific advice. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor - No need to miss a message. Get email on-the-go with Yahoo! Mail for Mobile. Get started.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] control multiple FTP sessions using multiple ipconnectionsvia different com ports
Hi Well now I have configured an old machine in the garage to run at the same time. I would really like to find out how to do this as it must be possible. I have been googling like mad and can't find how. Kind of frustrating when you don't know how. At the same time a challenge to seek. I am kind of hoping that someone on this forum will know how. In the mean time I can continue with my testing. Many thanks for your help; really appreciate it. /Ray Johan Geldenhuys <[EMAIL PROTECTED]> wrote: Will it be possible to disconnect one of the links during your test and reconnect it and disconnect the other connection once the ftp test is finished on the first connection? This way it will force the test script to use the active route to the internet. Not the most elegant way, but something to look at in the mean time. Johan - From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of ray sa Sent: 18 February 2007 04:16 AM To: Alan Gauld; tutor@python.org Subject: Re: [Tutor] control multiple FTP sessions using multiple ipconnectionsvia different com ports Hi Alan et al Many thanks for your time on this. I was referring to the client end. An EDGE terminal is a phone that has the capability of connecting to the internet. We use mobile phones to make a voice call that make use of a circuit switched connection. By using a GPRS connection we can use the mobile device to connect to the packet switched domain. You might have heard about making data connection using your phone like GPRS, 3G etc. EDGE is just faster than a GPRS connection and 3G is supposedly faster than GPRS and EDGE. May be I can give you more information about what I am trying to do. So you can understand what I am trying to achieve. Basically, I am trying to decide whether I should change my ADSL fixed solution to a higher speed connection using a mobile solution. Where I live the mobile operator is offering a mobile solution which is cheaper than my fixed solution .and is faster than my ADSL connection, please read on I have my ADSL broadband connection to my service provider that I use to connect to the internet. I have just bought a GPRS/EDGE/3G terminal and wanted to benchmark the speed I am getting by using my mobile device as opposed to my fixed connection. My desktop machine is connected to my ADSL provider using a USB modem which is assigned a particular COM port on my machine. Then I have connected my mobile handset also using a USB connection connected to a different COM port. Now I have two ip addresses ADSL COM port 4 with ip addres from my ADSL service provider Mobile Handset COM port 5 with another ip address from my mobile provider I have written a script that connects to a ftp server within my home country and downloads a file. But this script uses one of the connections above. There must be away to tell the script and control which connection to use. So I can get to see real time which connection is faster. So I can run the script pointing to one IP address and at the same time run another script using the other connection. I think there must be a method that finds out which connection is connected to which com port and then in my script I need to point towards that connection so my script knows which channel to use when downloading the file. I hope this helps sorry for too much text couldnt really find a simpler way to explain this. Once again I really appreciate the help on this forum./Ray Alan Gauld <[EMAIL PROTECTED]> wrote: "ray sa" wrote > I have been successful to write an ftp script that logs > into a server and collects files. > ...I would like to run multiple ftp sessions using one laptop > with two different connections. Do you mean you want the server on the laptop accepting using two connections or do you mean that you want the client on the laptop and have different sessions sending outgoing requests to the server via two different IP addresses? If the former its easy, just set up two servers, one on each IP address. The port will nbe the same on both, ISTR its port 21 for ftp? If you want to specify which IP address you send the client request from, I'm afraid I have no idea how you specify that. I've only ever used multiple network cards at the server end! > another connection using your EDGE terminal As a matter of interest what is an EDGE terminal? A new term for me... > I would like to write a script that controls which ip > address to use or with com port to use. Until we know which end you mean its hard to hgive more specific advice. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ---
Fat Injections For Buttock Enhancement
Fat Injections For Buttock Enhancement Fat injections to the buttocks is an alternative treatment to traditional buttock (gluteal) implants. Fat injections use the patient's own tissues and one gets the bonus of cosmetic reduction in the harvest site as well. Fat grafts, however, have a major disadvantage in that their survival is not guaranteed. The concentration of fat and the addition of platelet-rich plasma concentrate is my current approach to improving fat graft survival, particularly in a large injection site such as the buttocks. http://urlsh.com/go.php?j4q4fLh8 The Pros And Cons Of Cosmetic Surgery One of the many reasons why cosmetic surgery is so popular is because it has a number of pros or plus sides. For starters, cosmetic surgery can help to improve your appearance. Cosmetic surgery is different than reconstructive surgery and many other lifesaving surgeries, because it is optional. Those who undergo cosmetic surgery are usually just looking to improve their appearance. As nice as it is to look attractive, it is also important to note that you will likely see an improvement in your self-confidence, as well as your self-esteem. http://urlsh.com/go.php?YhsaXujY When Celebrity Plastic Surgery Has Gone Bad - Why Did it Happen? Just because you are famous and h00; google_ad_format = "160x600_as"; google_ad_channel = "8427791634"; google_color_border = "FF"; google_color_bg = "FF"; google_color_link = "006792"; google_color_url = "006792"; google_color_text = "00"; //--> [Tutor] Doing this in reverse? Alan Gilfoy Re: [Tutor] Doing this in reverse? Marc Tompkins Re: [Tutor] Doing this in reverse? Kent Johnson Re: [Tutor] Doing this in reverse? Marc Tompkins Re: [Tutor] Doing this in reverse? Kent Johnson Re: [Tutor] Doing this in reverse? Marc Tompkins Re: [Tutor] Doing this in reverse? Kent Johnson Reply via email to
[Tutor] Syntax error with if statement
Hello, I haven't been programming for a while and today I am working on something and have encountered an error I cannot figure out. Here is my code: thisFile = column[6] if thisFile == "/Images/My%20Face.JPG" CallCount += 1 print CallCount And here is the error message: ray@RaysComputer:~$ python /home/ray/EmailCount/CountEmails.py File "/home/ray/EmailCount/CountEmails.py", line 41 if thisFile == "/Images/My%20Face.JPG" ^ SyntaxError: invalid syntax Any help you can be will be much appreciated. Later, Ray Parrish -- The Unknown Lead Player, Ray Parrish http://www.facebook.com/pages/The-Unknown-Lead-Player/123388551041130?sk=wall Linux dpkg Software Report script set.. http://www.rayslinks.com/LinuxdpkgSoftwareReport.html Ray's Links, a variety of links to usefull things, and articles by Ray. http://www.rayslinks.com Writings of "The" Schizophrenic, what it's like to be a schizo, and other things, including my poetry. http://www.writingsoftheschizophrenic.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Introduction
Thanks for the welcome - I'll take a look at your recommendation. Ray On 08/18/2012 10:08 AM, Alex Clark wrote: > Hi Ray, > > On 2012-08-18 16:36:40 +, Ray said: > >> Hello. I am new to the mailing list and to Python. My knowledge of >> Python comes almost strictly from Nick Parlante's classes on YouTube >> that I've watched over the last week or so. >> >> I'm not certain why I'm diving into Python. My only coding experience >> has been using Bash scripts on my Ubuntu system for the past half dozen >> years, and so far I'm not particularly convinced that Python has any >> advantage FOR ME over what I have been using. >> >> In my Bash scripts I make generous use of sed and grep, with the >> occasional use of awk -- batch renaming of files, pulling exif date >> information from (manually) downloaded jpegs and adding that date to the >> front of file names, removing url '%' coding on photos and replacing it >> with "real" text, and the occasional foray into network stuff in >> conjunction with vlc or netcat. By no means am I a pro with Bash - only >> in the last six months have I really began to understand how to use >> arrays rather than temp files - but I can usually accomplish what I set >> out to do no matter how ugly the coding! >> >> The potential cross-platform use of Python is probably one of the major >> reasons for my interesttho' I don't think I write anything anyone >> else would want...and although, as I look at my Python code so far, it's >> definitely hard-coded for a Linux system :-p. So much for that >> reasoning >> >> But here I am - I am looking forward to learning from everyone, but keep >> the terminology as simple as possible, if you please - I'm only now >> beginning to understand what objects arelol > > > Welcome! Based on what you describe above, you might enjoy `Text > Processing in Python`: > > > - http://gnosis.cx/TPiP/ > > > Alex > > >> ___ >> 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] Introduction
GUI? Moi? Hahahawellnow that you mention it, I wonder Ray On 08/18/2012 10:25 AM, Alan Gauld wrote: > On 18/08/12 17:36, Ray wrote: > >> I'm not certain why I'm diving into Python. My only coding experience >> has been using Bash scripts on my Ubuntu system for the past half dozen >> years, and so far I'm not particularly convinced that Python has any >> advantage FOR ME over what I have been using. > > Python may not give you any new capability for the kinds of things you > describe but what you should find is that the code although maybe a > smidge longer will be much easier to maintain. It will often run a > little bit faster too (occasionally a lot faster) and use less > computing resources. > > As with anything there will be a learning curve where it will feel a > lot easier to just "knock something together is bash" but in time the > Python approach will become more natural. Of course there will still > be plenty of room for OS one liners. I still use bash and awk for > short one-off jobs. But for things you do frequently Python is usually > a better long term bet. And of course you can overlay a nice GUI to > make those tools easier to use... > >> In my Bash scripts I make generous use of sed and grep, with the >> occasional use of awk > > Remember that python can do all of those jobs natively, so resist the > temptation to just use os.system() or the SubProcess module. Thee is a > place for those, but its not to do what awk/sed etc can do - thats > usually better kept within Python. > >> else would want...and although, as I look at my Python code so far, it's >> definitely hard-coded for a Linux system :-p. So much for that >> reasoning > > We look forward to seeing some of it in the future when you ask > questions. But bear in mind my comments about avoiding os.system() etc > unless its the last resort. > > HTH, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Escaping globs for glob.iglob()
The code: curDir = os.getcwd() znDir = shutil.abspath('../') baseDir = shutil.abspath('../../') Files = glob.iglob(os.path.join(znDir, '*')) print Files for moveFile in Files: print moveFile shutil.move(moveFile, curDir) Nothing happens. The 'print...moveFile' never happens, even though print Files shows it to be an iglob generator object. After reading over the glob docs and working the directories backward manually, I realized that one of the directory names in the znDir path begins with '[1st]'. According to the docs, glob is apparently seeing that as a character range. No problem, I'll simply escape the '[' and ']' with backslashes. I used: znDir = znDir.replace('[', '\[') and then znDir = znDir.replace(']', '\]') No such luck. Glob still does not recognize the file glob in znDir/*. Later in the code I will be using creating symbolic links, and I wish to use the absolute path rather than the relative path. Any idea of how to sanitize this path so that I can get glob to work? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Escaping globs for glob.iglob()
On 08/20/2012 11:05 PM, Peter Otten wrote: > Ray Jones wrote: > >> The code: >> >> curDir = os.getcwd() >> znDir = shutil.abspath('../') >> baseDir = shutil.abspath('../../') >> >> Files = glob.iglob(os.path.join(znDir, '*')) >> print Files >> >> for moveFile in Files: >> print moveFile >> shutil.move(moveFile, curDir) >> >> Nothing happens. The 'print...moveFile' never happens, even though print >> Files shows it to be an iglob generator object. >> >> After reading over the glob docs and working the directories backward >> manually, I realized that one of the directory names in the znDir path >> begins with '[1st]'. According to the docs, glob is apparently seeing >> that as a character range. No problem, I'll simply escape the '[' and >> ']' with backslashes. I used: >> >> znDir = znDir.replace('[', '\[') >> and then >> znDir = znDir.replace(']', '\]') >> >> No such luck. Glob still does not recognize the file glob in znDir/*. >> Later in the code I will be using creating symbolic links, and I wish to >> use the absolute path rather than the relative path. >> >> Any idea of how to sanitize this path so that I can get glob to work? > Try > > znDir = znDir.replace("[", "[[]") That never occurred to me. Excellent. > Alternatively use os.listdir(znDir): > > [os.path.join(znDir, name) for name in os.listdir(znDir)] I've actually used this similarly in the past. I don't know why I got hung up on glob! ;) > For a non-trivial file pattern: > > pattern = "*tmp*.py" > files = [os.path.join(znDir, name) for name in > fnmatch.filter(os.listdir(znDir), pattern)] I looked at fnmatch.filter and didn't see how I could use it in this instance - it's crystal clear now. Thanks for the help. I think it's going to work now! Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Escaping globs for glob.iglob()
On 08/21/2012 12:59 AM, Alan Gauld wrote: > On 21/08/12 06:42, Ray Jones wrote: > >>Files = glob.iglob(os.path.join(znDir, '*')) >>print Files >> >>for moveFile in Files: >> print moveFile >> >> Nothing happens. The 'print...moveFile' never happens, even though print >> Files shows it to be an iglob generator object. > > Good but does it contain anything? > If not the loop will never execute. > Did you try plain glob() which returns a list? Easier to see what the > result set looks like. > Yes, I did try glob in the shell. It returned '[]' with the absolute path or any relative path that included the directory with the '[1st]' in it...which is what drew my focus to that portion of the path name to begin with. cheers. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] subprocess.Popen help
Does anyone know of a link to a really good tutorial that would help me with subprocess.Popen? a tutorial that uses really small words and more examples than explanation? After 15 years of scripting, I'm ashamed to say that I'm still not all that familiar with input, output, pipes, etc. much beyond a simple 'ls | ws -l' or &2>/dev/null scenarios. The docs for Popen have left me completely boggled, and I'm not seeing much available on Google search. Any suggestions? Thanks. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hello Python Tutor - help please!
I highly recommend the Google Python class that is found on YouTube. The first video is found at http://www.youtube.com/watch?v=tKTZoB2Vjuk The supporting class materials and assignments are found at http://code.google.com/edu/languages/google-python-class/ . This series of videos begins at a pretty basic level, but subsequent videos increase the difficulty level pretty rapidly. Don't despair - the concept of how to properly manipulate strings, lists, tuples, and other objects is rather daunting, but if you're working on your doctoral studies, you already know that complex concepts aren't simply soaked up like water to a sponge ;). Ray On 08/22/2012 03:10 AM, Cecilia Chavana-Bryant wrote: > Dear all, > > I am just returning to my doctoral studies after a 7-month medical > leave and desperately trying to catch up for lost time. I am > COMPLETELY new to programming, well, I did try learning C for 3 weeks > 3 yrs ago (with very little success) but had to stop and then spent 2 > years in the Amazon climbing trees (lots more enjoyable than learning > to programme!) and collecting loads of field data that I now need to > post-process and analyse. By the way, the 3 weeks I spent trying to > learn C really ended up being spent trying to get to grips with using > a terminal for the first time in my life. > > Since getting back to work, I was advised to try learning Python > instead of C as it is a much easier first language to learn. I have > been trying, but again, to not great success. I started following "A > Primer on Scientific programming with Python" but I kept getting lost > and stuck, specially on the exercises. I have also been advised that I > should not try to learn programming by following guides but by trying > to write the programmes I need to analyse my data. Although I can > understand the logic behind this last bit of advise (it gives context > and direction to the learning process) I have also gotten stuck trying > this approach as "I do not know how to programme!". Thus, I was hoping > that some of you can remember how you got started and point me towards > any really good interactive learning guides/materials and/or have a > good learning strategy for a complete beginner. I have searched the > web and was overwhelmed by choice of tutorials and guides. I have > skimmed through a couple of tutorials but then fail to see how all > that relates to my own work and I get stuck with what seems like basic > important concepts so I don't progress. I then think I should try to > make some progress with my own data analysing and go back to trying to > learn to write a programme for my specific needs and get stuck again > because this requires more advanced skills then the basic programming > concepts I have been reading about on the learning guides. So, I am > now feeling VERY frustrated and have no idea what on Earth I am doing! > Can anyone please offer guidance in my learning process? I don't know > how and what I should be spending my time learning first and/or if I > should focus my learning towards the skill areas I will require to > write my specific programmes, although I have no idea what these are. > I would like advise on finding some really good interactive(let you > know if your solution to an exercise is correct or not) and or video > tutorials that give you feedback on the solutions you write to > exercises. > > Many thanks in advance for all your help, it will be much appreciated! > > > > Cecilia Chavana-Bryant > DPhil Candidate - Remote sensing and tropical phenology > Environmental Change Institute > School of Geography and the Environment > University of Oxford > South Parks Road, Oxford, OX1 3QY > Web: http://www.eci.ox.ac.uk/teaching/doctoral/chavanabryantcecilia.php > Tel Direct: +44 (0)1865 275861 > Fax: +44 (0)1865 275885 > > > ___ > 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] subprocess.Popen help...thanks
Thanks to all who responded. I'm deeply into some of the links provided, and my understanding has greatly increased. Ray On 08/22/2012 12:59 AM, Andreas Perstinger wrote: > On 22.08.2012 03:39, Ray Jones wrote: >> Does anyone know of a link to a really good tutorial that would help me >> with subprocess.Popen? a tutorial that uses really small words and more >> examples than explanation? After 15 years of scripting, I'm ashamed to >> say that I'm still not all that familiar with input, output, pipes, etc. >> much beyond a simple 'ls | ws -l' or &2>/dev/null scenarios. The >> docs for Popen have left me completely boggled, and I'm not seeing much >> available on Google search. Any suggestions? > > What about this tutorial: > http://jimmyg.org/blog/2009/working-with-python-subprocess.html > > or Doug Hellmann's PyMOTW page about subprocess: > http://www.doughellmann.com/PyMOTW/subprocess/index.html > > Bye, Andreas > ___ > 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] Python working with Bash....arrrggggh!
As I code Python, I find myself falling back on Bash to handle basic OS tasks. How do you gurus deal with Python --> Bash conflicts? For example, if I wish to test if a file exists, I might do test = Popen('[ -f file-i-want-to-test-for ]') But the moment I invoke Bash for a test, I must deal with the fact that Bash returns a zero for true and a non-zero for false. But in Python, zero is false and non-zero is true. So if the file exists, the variable 'test' will be zero since that is what was returned by Bash. But if I want to test the variable for the existence of the file, I have to test the opposite: 'if not test:' because Python sees the zero as False. Does it become second nature to work with these conflicts? Or do you find it more expedient bypass the OS shell and work almost exclusively with Python? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python working with Bash....arrrggggh!
On 08/23/2012 09:53 PM, aklei...@sonic.net wrote: >> As I code Python, I find myself falling back on Bash to handle basic OS >> tasks. How do you gurus deal with Python --> Bash conflicts? >> >> For example, if I wish to test if a file exists, I might do >> >> test = Popen('[ -f file-i-want-to-test-for ]') >> >> But the moment I invoke Bash for a test, I must deal with the fact that >> Bash returns a zero for true and a non-zero for false. But in Python, >> zero is false and non-zero is true. So if the file exists, the variable >> 'test' will be zero since that is what was returned by Bash. But if I >> want to test the variable for the existence of the file, I have to test >> the opposite: 'if not test:' because Python sees the zero as False. >> >> Does it become second nature to work with these conflicts? Or do you >> find it more expedient bypass the OS shell and work almost exclusively >> with Python? > try > >>>> import os.path >>>> os.path.exists(path) > or >>>> os.path.isfile(file_name) That seems much cleaner to me than testing to see if 'os.listdir' contains a specific file. Thanks. I am forever confused, however, on which methods can be found where. I just spent quarter of an hour searching in sys,* os.*, and shutil.*. for a 'kill' command that I knew I'd seen beforeI found it hidden in subprocess.Popen. Arrrgggh. These various imports are going to drive me to drink! Thanks for the response. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python working with Bash....arrrggggh!
On 08/23/2012 10:37 PM, eryksun wrote: > On Thu, Aug 23, 2012 at 11:55 PM, Ray Jones wrote: > >> For example, if I wish to test if a file exists, I might do >> >> test = Popen('[ -f file-i-want-to-test-for ]') >> >> But the moment I invoke Bash for a test, I must deal with the fact that >> Bash returns a zero for true and a non-zero for false. But in Python, > Please see os.path: > > http://docs.python.org/library/os.path > > That said, you can use check_call and check_output if you want a more > Pythonic interface. These raise an exception for a non-zero return > code. For example: > > # check.py > > from subprocess import check_call, CalledProcessError > > try: > > # in Debian [ is at /usr/bin/[ > rc = check_call(["/usr/bin/[", "-f", "check.py", "]"]) > print "success:", rc > > # or pass the command string to the shell > rc = check_call("[ -f check.py ]", shell=True) > print "success:", rc > > # force a failure > rc = check_call("[ -f notfound ]", shell=True) > print "success:", rc # this won't execute > > except CalledProcessError as e: > print "failed: %d" % e.returncode Ah, yes. Thanks for the reminder that the check_call automatically interprets the True/False returns from the OS. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python working with Bash....arrrggggh!
On 08/24/2012 12:02 AM, Steven D'Aprano wrote: > On 24/08/12 16:27, Ray Jones wrote: > >> I am forever confused, however, on which methods can be found where. I >> just spent quarter of an hour searching in sys,* os.*, and shutil.*. for >> a 'kill' command that I knew I'd seen beforeI found it hidden in >> subprocess.Popen. Arrrgggh. These various imports are going to drive me >> to drink! > > Possibly you've already started the drive? *wink* > > There is an os.kill. > > > http://docs.python.org/library/os.html#os.kill Yes, I'd found that, but that requires a file descriptor rather than a file object - and I haven't advanced to file descriptors yet ;) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] 2.7.3 'CalledProcessError' error....why?
My code: try: subprocess.check_call(['ping', '-w1', ip]) except CalledProcessError: print 'System', ip, 'is not responding. Exiting' sys.exit(4) else: return None The result: Traceback (most recent call last): File "./testing.py", line 222, in main() File "./testing.py", line 170, in main ip, port, endTime = parse_command_line(args) File "./testing.py", line 111, in parse_command_line ip = do_ip(args) File "./testing.py", line 85, in do_ip ping_ip(ip) File "./testing.py", line 44, in ping_ip except CalledProcessError: NameError: global name 'CalledProcessError' is not defined I didn't think Python return errors needed to be defined. I'll work around it with call_output, but what the heck is going on here? What do I not understand? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 2.7.3 'CalledProcessError' error....why?
On 08/24/2012 04:14 PM, Emile van Sebille wrote: > On 8/24/2012 3:36 PM Ray Jones said... >> My code: >> >>try: >> subprocess.check_call(['ping', '-w1', ip]) >>except CalledProcessError: >> print 'System', ip, 'is not responding. Exiting' >> sys.exit(4) >>else: return None >> >> The result: >> >> Traceback (most recent call last): >>File "./testing.py", line 222, in >> main() >>File "./testing.py", line 170, in main >> ip, port, endTime = parse_command_line(args) >>File "./testing.py", line 111, in parse_command_line >> ip = do_ip(args) >>File "./testing.py", line 85, in do_ip >> ping_ip(ip) >> File "./testing.py", line 44, in ping_ip >> except CalledProcessError: > > Try it as: > > except subprocess.CalledProcessError, e > print e.output It worked like a charm. Thanks. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] 2.7.3 Popen argument issues
Is there a method by which I can get an exact representation of command line arguments passed by Popen as seen by the called program? The argument error I receive shows me an argument that looks exactly like the argument that I use with Bash (it should - I copied and pasted it) - but the Bash version works while the Python version doesn't. The purpose is to capture http streaming video to a file and also split it out to a local port so that I can pop in and monitor where I am in the stream. Here is my Bash call to vlc (it works): vlc http://"$HOST":$PORT -I dummy --sout '#duplicate{dst="transcode{vb=400}:std{access=file,mux=avi,dst=testing.avi}",dst="std{access=http,mux=mpjpeg,dst=127.0.0.1:11300}"}' & Here is my Python call to vlc (error response to follow): vlcExec = sp.Popen(['vlc', 'http://' + ip + ':' + port, '-I dummy', '--sout \'#duplicate{dst="transcode{vb=400}:std{access=file,mux=avi,dst=outFile + '.avi}",dst="std{access=http,mux=mpjpeg,dst=127.0.0.1:11300}"}\'']) (That is not an escaped double quote at the end - that is " \' " and " ' "). Here is the resulting error from vlc: vlc: unknown option or missing mandatory argument `--sout '#duplicate{dst="transcode{vb=400}:std{access=file,mux=avi,dst=testing.avi}",dst="std{access=http,mux=mpjpeg,dst=127.0.0.1:11300}"}'' ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 2.7.3 Popen argument issues
On 08/25/2012 10:19 PM, eryksun wrote: > On Sat, Aug 25, 2012 at 11:02 PM, eryksun wrote: >> out_file = "testing.avi" >> out_ip = "127.0.0.1" >> out_port = "11300" >> dst_file = '"transcode{vb=400}:std{access=file,mux=avi,dst=%s}"' % out_file >> dst_http = '"std{access=http,mux=mpjpeg,dst=%s:%s}"' % (out_ip, out_port) >> sout = "'#duplicate{dst=%s,dst=%s}'" % (dst_file, dst_http) >> >> cmd = "vlc http://%s:%s -I dummy --sout %s" % (ip, port, sout) >> >> p = subprocess.Popen(cmd.split()) > Wow... That was silly of me. Don't use split(). It would split up > arguments that have internal spaces. Just build the list. > > sout = "#duplicate{dst=%s,dst=%s}" % (dst_file, dst_http) > > cmd = ["vlc", "http://%s:%s"; % (ip, port), "-I", "dummy", "--sout", sout] > p = subprocess.Popen(cmd) [0x8d42554] stream_out_standard stream out error: no mux specified or found by extension [0x8d42134] main stream output error: stream chain failed for `standard{mux="",access=""#duplicate{dst="transcode{vb=400}",dst="std{access=file,mux=avi,dst=testing.avi}",dst="std{access=http,mux=mpjpeg,dst=localhost:11300}"}""}' Notice the addition of `standard{mux="",access='' ' before the `#duplicate' . I think --sout adds a default combination if it doesn't find a proper argument. Unfortunately, I know a bit less about vlc command line arguments than I do about Python's generation of those arguments ;) I had originally patched together the vlc command line from examples on the web. I think I'll go back and refamiliarize myself with vlc's command line and see if I can interweave my new understanding of how Python creates arguments with some further vlc knowledge. Thanks a bunch for the help. If you get an epiphany, I'm always open to suggestions ;) Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 2.7.3 Popen argument issues
On 08/26/2012 05:57 AM, Don Jennings wrote: > > On Aug 26, 2012, at 12:25 AM, tutor-requ...@python.org > <mailto:tutor-requ...@python.org> wrote: > >> Message: 2 >> Date: Sat, 25 Aug 2012 17:46:08 -0700 >> From: Ray Jones mailto:crawlz...@gmail.com>> >> To: tutor@python.org <mailto:tutor@python.org> >> Subject: [Tutor] 2.7.3 Popen argument issues >> Message-ID: <503971d0.5040...@gmail.com >> <mailto:503971d0.5040...@gmail.com>> >> Content-Type: text/plain; charset=ISO-8859-1 >> >> Is there a method by which I can get an exact representation of command >> line arguments passed by Popen as seen by the called program? The >> argument error I receive shows me an argument that looks exactly like >> the argument that I use with Bash (it should - I copied and pasted it) - >> but the Bash version works while the Python version doesn't. >> >> The purpose is to capture http streaming video to a file and also split >> it out to a local port so that I can pop in and monitor where I am in >> the stream. >> >> Here is my Bash call to vlc (it works): >> >> vlc http://"$HOST":$PORT -I dummy --sout >> '#duplicate{dst="transcode{vb=400}:std{access=file,mux=avi,dst=testing.avi}",dst="std{access=http,mux=mpjpeg,dst=127.0.0.1:11300}"}' > > Notice that the above call ends in a single quote? > >> & >> >> Here is my Python call to vlc (error response to follow): >> >> vlcExec = sp.Popen(['vlc', 'http://' + ip + ':' + port, '-I dummy', >> '--sout >> \'#duplicate{dst="transcode{vb=400}:std{access=file,mux=avi,dst=outFile >> + '.avi}",dst="std{access=http,mux=mpjpeg,dst=127.0.0.1:11300}"}\'']) >> >> (That is not an escaped double quote at the end - that is " \' " and >> " ' "). >> >> Here is the resulting error from vlc: >> >> vlc: unknown option or missing mandatory argument `--sout >> '#duplicate{dst="transcode{vb=400}:std{access=file,mux=avi,dst=testing.avi}",dst="std{access=http,mux=mpjpeg,dst=127.0.0.1:11300}"}'' > > Notice that this one ends in a double quote? Those are **definitely > not** the same :>) I noticed that too. It took me a while to see why the difference Notice that vlc added a backtick before quoting the '--sout' string. That additional quote is the close of the backtick that it used to quote the string. ;) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 2.7.3 Popen argument issues
On 08/26/2012 07:12 AM, eryksun wrote: > On Sun, Aug 26, 2012 at 7:55 AM, Ray Jones wrote: >> [0x8d42554] stream_out_standard stream out error: no mux specified or >> found by extension >> [0x8d42134] main stream output error: stream chain failed for >> `standard{mux="",access=""#duplicate{dst="transcode{vb=400}",dst="std{access=file,mux=avi,dst=testing.avi}",dst="std{access=http,mux=mpjpeg,dst=localhost:11300}"}""}' >> >> >> Notice the addition of `standard{mux="",access='' ' before the >> `#duplicate' . I think --sout adds a default combination if it doesn't >> find a proper argument. Unfortunately, I know a bit less about vlc >> command line arguments than I do about Python's generation of those >> arguments ;) > But the Bash call worked? > > cmd = 'vlc http://"HOST":PORT -I dummy --sout > \'#duplicate{dst="transcode{vb=400}:std{access=file,mux=avi,dst=testing.avi}",dst="std{access=http,mux=mpjpeg,dst=127.0.0.1:11300}"}\'' > > print '\n'.join(shlex.split(cmd)) # shlex.split parses like the shell > > Output: > > vlc > http://HOST:PORT > -I > dummy > --sout > #duplicate{dst="transcode{vb=400}:std{access=file,mux=avi,dst=testing.avi}",dst="std{access=http,mux=mpjpeg,dst=127.0.0.1:11300}"} Yes, the Bash call worked (in fact I tried it just prior to sending the original message just to be sure). I guess I'm a bit confused about 'splitting' the arguments. You said that Python splits arguments on spaces. What exactly happens to the arguments if we split them up into individual strings separated by commas? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 2.7.3 Popen argument issues
On 08/27/2012 05:45 AM, eryksun wrote: > Most programs expect their arguments to have been tokenized as the > shell would as a matter of convention. So, for example, if vlc gets > "-I" in argv[1] it expects that argv[2] will be a value such as > "dummy". A value of "-I dummy" in argv[1] in principle shouldn't work. > In practice vlc seems pretty flexible and accepts it both ways. Thanks for the explanation. By the way, my call to vlc now works. Thanks for breaking up the parts of the argument into variables - it helped me understand greatly both what was happening on the command line and how to make code more readable. What worked was to remove the extra quotes from around the argument parts and placing them around the %s formatting inside 'sout'. I'm not certain why that made a difference (BTW, I had gotten the dst_file portion to work, but the dst_http kept failing. I finally used the debug switch vlc and 'less' to compare the outputs of the working Bash call and the non-working Python call.well, it did finally jump out at me that the working call contained a 'mpjpeg' mux while the non-working call was misnamed a 'mjpeg' mux. ) Thanks for your help - I have a greater understanding of what's going on. When I'm 80, I might be able to claim guruship like you! ;) Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Installing modules with easy_install
I'm working on another Python replacement for a Bash script, and I ran into a need for enhanced time zone functions. Following directions I found on a web site, I did the following: # easy_install --upgrade pytz Searching for pytz Reading http://pypi.python.org/simple/pytz/ Reading http://pytz.sourceforge.net Reading http://sourceforge.net/project/showfiles.php?group_id=79122 Reading http://www.stuartbishop.net/Software/pytz Reading http://sourceforge.net/projects/pytz/ Best match: pytz 2012d Downloading http://pypi.python.org/packages/2.7/p/pytz/pytz-2012d-py2.7.egg#md5=e6f9219ae6eff242f13c6700413df69e Processing pytz-2012d-py2.7.egg creating /usr/local/lib/python2.7/dist-packages/pytz-2012d-py2.7.egg Extracting pytz-2012d-py2.7.egg to /usr/local/lib/python2.7/dist-packages Adding pytz 2012d to easy-install.pth file Installed /usr/local/lib/python2.7/dist-packages/pytz-2012d-py2.7.egg Processing dependencies for pytz Finished processing dependencies for pytz Everything I'm reading suggests that now I should have the pytz module available to me. But from iPython: In [1]: import pytz --- ImportError Traceback (most recent call last) /home/ray/ in () ImportError: No module named pytz In [2]: import pytz-2012d File "", line 1 import pytz-2012d ^ SyntaxError: invalid syntax So what do I need to do to get Python to recognize this module? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Installing modules with easy_install
On 08/28/2012 11:06 AM, Peter Otten wrote: > Ray Jones wrote: > >> I'm working on another Python replacement for a Bash script, and I ran >> into a need for enhanced time zone functions. Following directions I >> found on a web site, I did the following: >> >> # easy_install --upgrade pytz >> Searching for pytz >> Reading http://pypi.python.org/simple/pytz/ >> Reading http://pytz.sourceforge.net >> Reading http://sourceforge.net/project/showfiles.php?group_id=79122 >> Reading http://www.stuartbishop.net/Software/pytz >> Reading http://sourceforge.net/projects/pytz/ >> Best match: pytz 2012d >> Downloading >> http://pypi.python.org/packages/2.7/p/pytz/pytz-2012d- > py2.7.egg#md5=e6f9219ae6eff242f13c6700413df69e >> Processing pytz-2012d-py2.7.egg >> creating /usr/local/lib/python2.7/dist-packages/pytz-2012d-py2.7.egg >> Extracting pytz-2012d-py2.7.egg to /usr/local/lib/python2.7/dist-packages >> Adding pytz 2012d to easy-install.pth file >> >> Installed /usr/local/lib/python2.7/dist-packages/pytz-2012d-py2.7.egg >> Processing dependencies for pytz >> Finished processing dependencies for pytz >> >> >> Everything I'm reading suggests that now I should have the pytz module >> available to me. But from iPython: >> >> >> In [1]: import pytz >> > --- >> ImportError Traceback (most recent call >> last) >> >> /home/ray/ in () >> >> ImportError: No module named pytz > Do you have multiple python installations on your machine? Do you run > easy_install in one and ipython in another? Perhaps. But the module is not accessible from the 'python' shell, from 'idle', or from iPython. As I peruse Synaptic I find I have active installations of Ubuntu's basic python, python2.7, and python2.7-minimal. But are these separate installations? Virtually every system package thinks it's dependent on each one of these python packages. Suggestions? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Installing modules with easy_install
On 08/28/2012 12:35 PM, Steven D'Aprano wrote: > On 29/08/12 03:41, Ray Jones wrote: >> I'm working on another Python replacement for a Bash script, and I ran >> into a need for enhanced time zone functions. Following directions I >> found on a web site, I did the following: >> >> # easy_install --upgrade pytz > [...] >> Everything I'm reading suggests that now I should have the pytz module >> available to me. But from iPython: > >> ImportError: No module named pytz > > > Any time you get mysterious errors in iPython, or IDLE, or any other > add-on to Python, it is important to determine whether the problem is > with Python itself, or the add-on. > > In this case, start up the vanilla Python interactive environment by > entering "python" at the $ prompt, then "import pytz" at the >>> prompt. > > If you get an error: > > - copy and paste the full traceback > > - show us the contents of sys.path > > > You can also determine how many Python installations you have. At the > bash $ prompt, type: > > python TAB TAB > > (that is, press the TAB key twice is succession, do not type the > letters "t" "a" "b") > > and your shell will list the possible executable Python's on your > system. Copy and paste that output. > I tried importing the module with each of the three shells that I have on my system (I think I need to get rid of idle - I never use it anymore): python, ipython, and idle. None of them recognize the module. Discovering which python binaries are available shows that I have /usr/bin/python and /usr/bin/python2.7. /usr/bin/python is a link to /usr/bin/python2.7. My sys.path shows the following: ['', '', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/pymodules/python2.7/gtk-2.0', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode', '/usr/lib/python2.7/dist-packages/IPython/Extensions', u'/home/ray/.ipython'] Aha! The sys path is in /usr/lib but the module was installed in /usr/local/lib. What's the easiest fix for this? Creating a link to the module in the OS, or adding (or changing) the sys.path? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Installing modules with easy_install
On 08/28/2012 12:44 PM, Peter Otten wrote: > Ray Jones wrote: > >> On 08/28/2012 11:06 AM, Peter Otten wrote: >>> Ray Jones wrote: >>> >>>> I'm working on another Python replacement for a Bash script, and I ran >>>> into a need for enhanced time zone functions. Following directions I >>>> found on a web site, I did the following: >>>> >>>> # easy_install --upgrade pytz >>>> Searching for pytz >>>> Reading http://pypi.python.org/simple/pytz/ >>>> Reading http://pytz.sourceforge.net >>>> Reading http://sourceforge.net/project/showfiles.php?group_id=79122 >>>> Reading http://www.stuartbishop.net/Software/pytz >>>> Reading http://sourceforge.net/projects/pytz/ >>>> Best match: pytz 2012d >>>> Downloading >>>> http://pypi.python.org/packages/2.7/p/pytz/pytz-2012d- >>> py2.7.egg#md5=e6f9219ae6eff242f13c6700413df69e >>>> Processing pytz-2012d-py2.7.egg >>>> creating /usr/local/lib/python2.7/dist-packages/pytz-2012d-py2.7.egg >>>> Extracting pytz-2012d-py2.7.egg to >>>> /usr/local/lib/python2.7/dist-packages Adding pytz 2012d to >>>> easy-install.pth file >>>> >>>> Installed /usr/local/lib/python2.7/dist-packages/pytz-2012d-py2.7.egg >>>> Processing dependencies for pytz >>>> Finished processing dependencies for pytz >>>> >>>> >>>> Everything I'm reading suggests that now I should have the pytz module >>>> available to me. But from iPython: >>>> >>>> >>>> In [1]: import pytz >>>> > --- >>>> ImportError Traceback (most recent call >>>> last) >>>> >>>> /home/ray/ in () >>>> >>>> ImportError: No module named pytz >>> Do you have multiple python installations on your machine? Do you run >>> easy_install in one and ipython in another? >> Perhaps. But the module is not accessible from the 'python' shell, from >> 'idle', or from iPython. >> >> As I peruse Synaptic I find I have active installations of Ubuntu's >> basic python, python2.7, and python2.7-minimal. But are these separate >> installations? > No, I suspected that you had a system python and a self-compiled one, i. e. > that you have both > > /usr/local/bin/python > > and > > /usr/bin/python > > If that were the case then you should be able to import pytz into one of > these. Bingo! Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Installing modules with easy_install
On 08/28/2012 12:35 PM, Steven D'Aprano wrote: > On 29/08/12 03:41, Ray Jones wrote: >> I'm working on another Python replacement for a Bash script, and I ran >> into a need for enhanced time zone functions. Following directions I >> found on a web site, I did the following: >> >> # easy_install --upgrade pytz > [...] >> Everything I'm reading suggests that now I should have the pytz module >> available to me. But from iPython: > >> ImportError: No module named pytz > > > Any time you get mysterious errors in iPython, or IDLE, or any other > add-on to Python, it is important to determine whether the problem is > with Python itself, or the add-on. > > In this case, start up the vanilla Python interactive environment by > entering "python" at the $ prompt, then "import pytz" at the >>> prompt. > > If you get an error: > > - copy and paste the full traceback > > - show us the contents of sys.path > > > You can also determine how many Python installations you have. At the > bash $ prompt, type: > > python TAB TAB > > (that is, press the TAB key twice is succession, do not type the > letters "t" "a" "b") > > and your shell will list the possible executable Python's on your > system. Copy and paste that output. Oops. No, I see that /usr/local/lib/python2.7/dist-packages is included in the sys.path. Now what? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Installing modules with easy_install
On 08/28/2012 12:52 PM, eryksun wrote: > On Tue, Aug 28, 2012 at 2:39 PM, Ray Jones wrote: >>> Do you have multiple python installations on your machine? Do you run >>> easy_install in one and ipython in another? >> Perhaps. But the module is not accessible from the 'python' shell, from >> 'idle', or from iPython. >> >> As I peruse Synaptic I find I have active installations of Ubuntu's >> basic python, python2.7, and python2.7-minimal. But are these separate >> installations? Virtually every system package thinks it's dependent on >> each one of these python packages. >> >> Suggestions? > Those are not separate installations. The python package depends on > python2.7 and python-minimal. The latter depends on python2.7-minimal. > You should be able to install pytz from the Ubuntu repository. Search > for the package python-tz. If you install from the repository, be sure > to manually delete the old installation in the local dist-packages > directory. I took out the pytz egg package and installed from Synaptic (I had looked there originally, but I searched pytz rather than python-tz). I now have an importably pytz. So that particular issue is cleared up, but what about modules that aren't available in Synaptic? It seems I still have an issue with easy_install, no? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Installing modules with easy_install
On 08/28/2012 01:11 PM, eryksun wrote: > On Tue, Aug 28, 2012 at 4:00 PM, Ray Jones wrote: >> Oops. No, I see that /usr/local/lib/python2.7/dist-packages is included >> in the sys.path. Now what? > Good, but does sys.path contain > /usr/local/lib/python2.7/dist-packages/pytz-2012d-py2.7.egg? No. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Installing modules with easy_install
On 08/28/2012 01:11 PM, eryksun wrote: > On Tue, Aug 28, 2012 at 4:00 PM, Ray Jones wrote: >> Oops. No, I see that /usr/local/lib/python2.7/dist-packages is included >> in the sys.path. Now what? > Good, but does sys.path contain > /usr/local/lib/python2.7/dist-packages/pytz-2012d-py2.7.egg? More info: /usr/lib/python2.7/dist-packages does not contain a easy-install.pth file. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Installing modules with easy_install
On 08/28/2012 01:35 PM, Emile van Sebille wrote: > On 8/28/2012 1:17 PM Ray Jones said... >> On 08/28/2012 01:11 PM, eryksun wrote: >>> On Tue, Aug 28, 2012 at 4:00 PM, Ray Jones wrote: >>>> Oops. No, I see that /usr/local/lib/python2.7/dist-packages is >>>> included >>>> in the sys.path. Now what? >>> Good, but does sys.path contain >>> /usr/local/lib/python2.7/dist-packages/pytz-2012d-py2.7.egg? >> More info: >> >> /usr/lib/python2.7/dist-packages does not contain a easy-install.pth >> file. >> > > You installed this with easy_install, so the version of python therein > referenced is the same one that now should have access to it. > > Try : which easy_install > > then cat the result. The first line points to the executable python > that installed pytz. On my local system this looks like: > > > head -1 `which easy_install` > #! /usr/bin/python > > copy and paste in the result, then import pytz from there and paste in > the results if it doesn't work. #! /usr/bin/python I think you come late to the party, but jump in - there's lots of room! We have solved the pytz problem by quarantining the pytz*.egg and installing python-tz from the Debian system. But while pytz now works, it does not address the problem of easy-install-ed modules not being recognized by python (btw, in perusing the /usr/local/bin/.../dist-packages I also found a shodan module (whatever that is) that python does not recognize - and I don't find shodan in the Debian packages). Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] running more than one python program at the same time
On 08/28/2012 03:30 PM, Benjamin Fishbein wrote: > Hello, > I wrote a program that I want to have running 24/7. But the problem is that I > also want to write and run other programs. I'm using Idle and it won't let me > run more than one script at a time. Do you know if there's a way to do this? > Or do I need to buy a second computer? > Thanks, > Ben Can you make each script executable and run them without idle? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Using a calling program to change Python script arguments
As an aid to learning Python, I am currently in the process of converting my Bash scripts into Python scripts. Through the years, as I have accumulated a variety of sites, I have been maintaining a half dozen or so Bash scripts that basically do the same thing: log me into a streaming video site and record the stream. So as I make this conversion, it's becoming obvious to me that as my Python skill increases, I will be making changes to these scripts. But that means maintaining all these scripts in parallel with each other. I'm considering creating calling scripts (either Bash or another Python script), all of which call a single Python capture script. Each calling script would have its own info concerning IP, port, user name, password, http or rtsp, time zone info, length of capture time, etc., and then those scripts would pass their information to the single Python script, greatly easing the maintenance issue. But that's a ton of command line arguments to pass to the Python capture script and have it parse. Is there another method for one Python script to call/import/execute a Python script and integrate the name space so that the variables in each of the calling scripts would be directly usable by the Python module/child process/whatever without passing arguments either via line arguments (yeccchhh!) or function calls (considerably better)? Arguably, once the calling script passed the info to the main script, it really wouldn't need to be there at all. So how high is this pie-in-the-sky dream of mine? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using a calling program to change Python script arguments
On 08/31/2012 02:19 PM, Alan Gauld wrote: > On 31/08/12 18:05, Ray Jones wrote: > >> script and have it parse. Is there another method for one Python script >> to call/import/execute a Python script and integrate the name space so >> that the variables in each of the calling scripts would be directly >> usable by the Python module/child process/whatever without passing >> arguments either via line arguments (yeccchhh!) or function calls > > > Just create a module with the variables in it. > > Then import and access that module data in all your scripts. > > eg. > > import mysitedata > print mysitedata.myValue Backasswards was I again. I was thinking of loading the main from my calling program. I will try that. The only thing I would have to pass on the command line then is which module I want to import for the site I want to access. Okay. Now I must figure out how to create the module and have my calling script look in the right place ;) Thanks. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using a calling program to change Python script arguments
On 08/31/2012 04:58 PM, Alan Gauld wrote: > > Creating a module is just a matter of creating a standard python file > > <start of myvar.py -> > #! /bin/python# you don't even really need a shebang for modules! > myVar = 66 > < end of myvar.py --> > > import myvar > print myvar.myVal > > > And so long as the location of the module is in your sys.path > (or in the PYHONPATH environment variable) python will find it. Yep. I got my 'pymodules' directory created, and I will append it to the sys.path list a run time. So far it appears to work in testing modenext we'll see what happens in real life! Thanks. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] 2.7.3 generator objects
I was playing with os.walk today. I can use os.walk in a for loop (does that make it an iterator or just an irritable? ^_^), but if I assign os.walk to 'test' (test = os.walk()), that variable becomes a generator object that does not work in a for loop. From what I can tell, it's supposed to work in a generator function using 'yield', but I'm at a loss at how that all works. I suppose I should just stick with using the os.walk in the for loop, but I'd like to make sense of the whole thing. Please someone explain this to me? Thanks. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 2.7.3 generator objects
On 09/01/2012 11:39 PM, Alan Gauld wrote: > On 02/09/12 06:44, Ray Jones wrote: >> I was playing with os.walk today. I can use os.walk in a for loop (does >> that make it an iterator or just an irritable? ^_^), but if I assign >> os.walk to 'test' (test = os.walk()), that variable becomes a >> generator object that does not work in a for loop. > > > It does for me > > >>> home = os.walk('/home/alang/src/Python') > >>> for root,dirs,files in home: > ... print root > ... > /home/alang/src/Python > /home/alang/src/Python/modcopy > /home/alang/src/Python/modcopy/src > >>> > > What happened when you tried? I'll be dipped. It worked - the first time, anyway. It wouldn't go a second round. Don't I have to reset the object somehow? When I originally tried it, I placed print root print dirs print files within the for loop, and I ended up with nuthin'. Or perhaps it flashed by while I wasn't watching, and it wouldn't do it a second time??? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 2.7.3 generator objects
On 09/01/2012 11:57 PM, eryksun wrote: > To be an iterable in general, it suffices to have either an __iter__ > method or a __getitem__ method. Here are the glossary definitions: > http://docs.python.org/glossary.html#term-iterable > http://docs.python.org/glossary.html#term-iterator After a few times re-reading, I'm beginning to get a glimmer > Also, here is the PEP for simple generators: > http://www.python.org/dev/peps/pep-0255/ but this is complete Greek! ;) But didn't I read somewhere that you can reset an iterator to go through the whole process again? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running a script in the background
This is only tangentially related to the thread. Someone mentioned that so long as a script didn't require user input or output to the user, it could run silently in the background. But is there a way for a Python (2.7.3) script to determine whether it was called by the user or called by something like cron or kalarm? That way user inputs could be used when called by a user, but defaults could be used if run by a bot. Or is this more of a Linux question? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running a script in the background
On 09/02/2012 03:30 PM, Alan Gauld wrote: > On 02/09/12 23:14, Ray Jones wrote: >> could run silently in the background. But is there a way for a Python >> (2.7.3) script to determine whether it was called by the user or called >> by something like cron or kalarm? That way user inputs could be used >> when called by a user, but defaults could be used if run by a bot. > > Yes you can query the user via the os module.(getuid or getlogin for > example) > >> Or is this more of a Linux question? > > The details are likely to be implementation dependant, differing even > between local hosts since it depends on how the admin has set up the > user for cron etc > Thanks. I'll add this to my to-learn list (It's frustrating to come up with questions and answers faster than I can assimilate it all :-p) Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running a script in the background (offshoot - sorry, OP)
On 09/02/2012 06:03 PM, Steven D'Aprano wrote: > On Sun, Sep 02, 2012 at 03:14:53PM -0700, Ray Jones wrote: >> This is only tangentially related to the thread. Someone mentioned that >> so long as a script didn't require user input or output to the user, it >> could run silently in the background. But is there a way for a Python >> (2.7.3) script to determine whether it was called by the user or called >> by something like cron or kalarm? That way user inputs could be used >> when called by a user, but defaults could be used if run by a bot. > The usual way to detect this is by checking whether or not there is a > terminal available. > > os.isatty(sys.stdout.fileno()) > > If the script is running directly in a console, isatty will return True; > if it is running from cron, or via a pipe or similar, then it will > return False. Okay. Your solution works with cron - it does not work with kalarm (KDE's system alarm). The only reason I'm using kalarm rather than cron to begin with is that kalarm is TZ aware while anacron only looks at the system TZ (i.e. with kalarm I can start each task based on its own individual time zone). I read that fcron is fully TZ aware, but when I tried to install it, it wanted to automatically remove anacron and the entire kubuntu-desktop! Now this definitely gets into the Linux side of things. I'll go hit the Ubuntu forums and see what I can find. Thanks, everyone. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;)
I have directory names that contain Russian characters, Romanian characters, French characters, et al. When I search for a file using glob.glob(), I end up with stuff like \x93\x8c\xd1 in place of the directory names. I thought simply identifying them as Unicode would clear that up. Nope. Now I have stuff like \u0456\u0439\u043e. These representations of directory names are eventually going to be passed to Dolphin (my file manager). Will they pass to Dolphin properly? Do I need to run a conversion? Can that happen automatically within the script considering that the various types of characters are all mixed together in the same directory (i.e. # coding: Latin-1 at the top of the script is not going to address all the different types of characters). While on the subject, I just read through the Unicode info for Python 2.7.3. The history was interesting, but the implementation portion was beyond me. I was looking for a way for a Russian 'backward R' to look like a Russian 'backward R' - not for a bunch of \xxx and \ux stuff. Can someone point me to a page that will clarify the concepts, not just try to show me the Python implementation of what I already don't understand? ;) Thanks Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;)
On 09/05/2012 02:57 AM, Walter Prins wrote: > Hi Ray, > > On 5 September 2012 10:42, Ray Jones wrote: >> Can someone point me to a page that will clarify the concepts, not just >> try to show me the Python implementation of what I already don't >> understand? ;) > Try the following 2 links which should hopefully help: > > http://www.joelonsoftware.com/articles/Unicode.html > http://nedbatchelder.com/text/unipain.html > "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)" Right up my alley! ;) Thank-you. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;)
On 09/05/2012 03:33 AM, Peter Otten wrote: > Ray Jones wrote: > >> I have directory names that contain Russian characters, Romanian >> characters, French characters, et al. When I search for a file using >> glob.glob(), I end up with stuff like \x93\x8c\xd1 in place of the >> directory names. I thought simply identifying them as Unicode would >> clear that up. Nope. Now I have stuff like \u0456\u0439\u043e. > >>> files = [u"\u0456\u0439\u043e"] # files = glob.glob(unicode_pattern) >>> print files > [u'\u0456\u0439\u043e'] > > To see the actual characters print the unicode strings individually: > >>>> for file in files: > ... print file > ... > ійо Aha! That works. >> These representations of directory names are eventually going to be >> passed to Dolphin (my file manager). Will they pass to Dolphin properly? > How exactly do you "pass" these names? I will be calling Dolphin with subprocess.call() and passing the directories as command line arguments. > $ cat tmp.py > # -*- coding: utf-8 -*- > print u"Я" > $ python tmp.py > Я > $ python tmp.py | cat > Traceback (most recent call last): > File "tmp.py", line 2, in > print u"Я" > UnicodeEncodeError: 'ascii' codec can't encode character u'\u042f' in > position 0: ordinal not in range(128) > > You can work around that by specifying the appropriate encoding explicitly: > > $ python tmp2.py iso-8859-5 | cat > � > $ python tmp2.py latin1 | cat > Traceback (most recent call last): > File "tmp2.py", line 4, in > print u"Я".encode(encoding) > UnicodeEncodeError: 'latin-1' codec can't encode character u'\u042f' in > position 0: ordinal not in range(256) > But doesn't that entail knowing in advance which encoding you will be working with? How would you automate the process while reading existing files? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;)
On 09/05/2012 04:52 AM, Peter Otten wrote: > Ray Jones wrote: > >> >> But doesn't that entail knowing in advance which encoding you will be >> working with? How would you automate the process while reading existing >> files? > If you don't *know* the encoding you *have* to guess. For instance you could > default to UTF-8 and fall back to Latin-1 if you get an error. While > decoding non-UTF-8 data with an UTF-8 decoder is likely to fail Latin-1 will > always "succeed" as there is one codepoint associated with every possible > byte. The result howerver may not make sense. Think > > for line in codecs.open("lol_cat.jpg", encoding="latin1"): > print line.rstrip() :)) So when glob reads and returns garbley, non-unicode file names\xb4\xb9is it making a guess as to which encoding should be used for that filename? Does Linux store that information when it saves the file name? And (most?) importantly, how can I use that fouled up file name as an argument in calling Dolphin? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;)
On 09/05/2012 07:31 AM, eryksun wrote: > On Wed, Sep 5, 2012 at 5:42 AM, Ray Jones wrote: >> I have directory names that contain Russian characters, Romanian >> characters, French characters, et al. When I search for a file using >> glob.glob(), I end up with stuff like \x93\x8c\xd1 in place of the >> directory names. I thought simply identifying them as Unicode would >> clear that up. Nope. Now I have stuff like \u0456\u0439\u043e. > This is just an FYI in case you were manually decoding. Since glob > calls os.listdir(dirname), you can get Unicode output if you call it > with a Unicode arg: > > >>> t = u"\u0456\u0439\u043e" > >>> open(t, 'w').close() > > >>> import glob > > >>> glob.glob('*') # UTF-8 output > ['\xd1\x96\xd0\xb9\xd0\xbe'] > > >>> glob.glob(u'*') > [u'\u0456\u0439\u043e'] Yes, I played around with that somein my lack of misunderstanding, I thought that adding the 'u' would pop the characters out at me the way they should appear. Silly me ;) > Regarding subprocess.Popen, just use Unicode -- at least on a POSIX > system. Popen calls an exec function, such as posix.execv, which > handles encoding Unicode arguments to the file system encoding. > > On Windows, the _subprocess C extension in 2.x is limited to calling > CreateProcessA with char* 8-bit strings. So Unicode characters beyond > ASCII (the default encoding) trigger an encoding error. subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) Dolphin's error message: 'The file or folder /my_home/testdir/\u044c\u043e\u0432 does not exist' But if I copy the characters as seen by Bash's shell and paste them into my subprocess.call(), Dolphin recognizes the directory just fine. So is Dolphin unicode-dead, or am I missing something? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;)
On 09/05/2012 07:51 AM, Ray Jones wrote: > subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) > > Dolphin's error message: 'The file or folder > /my_home/testdir/\u044c\u043e\u0432 does not exist' > > But if I copy the characters as seen by Bash's shell and paste them into > my subprocess.call(), Dolphin recognizes the directory just fine. > > So is Dolphin unicode-dead, or am I missing something? > > > Ray Answering myself here. I suspect I'm missing something because once within the folders, Dolphin properly recognizes the characterseven so far as writing Arabic and Hebrew "backward"I wonder Sure enough. If I use the glob.glob() non-unicode characters (\x93\xbe) on the command line, Dolphin understands it just fine. Thanks all. Ray (Still wondering where unicode fits into all this) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unicode? UTF-8? UTF-16? WTF-8? ;)
On 09/05/2012 08:18 AM, eryksun wrote: > On Wed, Sep 5, 2012 at 10:51 AM, Ray Jones wrote: >> subprocess.call(['dolphin', '/my_home/testdir/\u044c\u043e\u0432']) >> >> Dolphin's error message: 'The file or folder >> /my_home/testdir/\u044c\u043e\u0432 does not exist' > "\u" only codes a BMP character in unicode literals, i.e. u"unicode > literal". You forgot the 'u'. What with all the 'u's floating around in the unicode escape characters, I didn't realize I needed to add yet another one! You're right. It worked. Thank-you everyone. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hey.need help on time
On 09/06/2012 12:51 AM, eryksun wrote: > On Thu, Sep 6, 2012 at 3:21 AM, Keitaro Kaoru wrote: >> been trying to change this so it wont use my server time. but my >> actual time here in the us.EST. havent been able to figure it out >> >> def sstime(user, body, m): >> os.environ['TZ'] = 'US/Eastern' > Now just call time.tzset(), and it should work. Why the additional step of calling time.tzset()? Once os.environ['TZ'] is set, I've found that time.localtime() responds to the new TZ without anything extra. Is that a difference in versions (2.7.3 here)? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help
On 09/03/2012 07:39 AM, Jack Little wrote: > > Ok, I am somewhat new to python, and I am making a text-based RPG. I get a > > weird error with this code: > > > > > > #A Python text-RPG > > #A Jak Production > > #APOC > > global ammo > > global health > > global lives > > global exp > > global food > > ammo=55 > > health = 100 > > lives=10 > > exp = 0 > > food = 30 > > > > def part1(): > >print "50 Days After The Outbreak:You are standing outside of the Empire > > State Building." > >print "Vines, plants, dirt, and grime cover its once-regal surfaces. > > Huh." > >print "I guess if 80% of the world is dead, more people are concerned > > about survival than sightseeing.God." > >print "Generally,us survivors tend to band together. Mostly it is for > > good. Not the bandits." > >print " Bandit:'Hey you! What you got in that bag?" > >print "I recognized this Bandit as Sam Cabelo. He was the janitor at my > > office building. Not the nicest fellow." > >answer = raw_input("Type 'show' or 'run away' then hit the 'Enter' > > button.") > >if answer == "SHOW" or answer == "Show" or answer == "show": > >print "Ahhh. Nice .45 you got there. And some food.Hand it over.(He > > says this like a threat, reinforced by that revolver in his hand" > >answer2 = raw_input("Type either Hand it over or flee") > >if answer2 == "HAND IT OVER" or answer2 == "Hand it over" or answer2 > > == "hand it over": > >print "Bandit: Good Job.. Go on now" > >ammo=ammo-15 > > I'll take a stab at it. You are using attempting to modify a global variable within a procedure. Procedure variables are separate from global variables. Global variables must be passed into a procedure using something on the order of 'part1(ammo)', and then returned back from the procedure with a 'return ' Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hey.need help on time
On 09/06/2012 02:08 AM, eryksun wrote: > On Thu, Sep 6, 2012 at 4:25 AM, Ray Jones wrote: >> Why the additional step of calling time.tzset()? Once os.environ['TZ'] >> is set, I've found that time.localtime() responds to the new TZ without >> anything extra. Is that a difference in versions (2.7.3 here)? > It shouldn't strictly be necessary using glibc. I checked the source. > glibc localtime calls __tz_convert() on each call, which calls > tzset_internal() to update the TZ setting. However, I don't think > that's guaranteed in all C runtimes. As the Python docs say, > "[c]hanging the TZ environment variable without calling tzset *may* > change the local timezone used by methods such as localtime, but this > behaviour should not be relied on." Got ya. I'll remember that. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Making big 'uns into little 'uns
I have a multiple 'if' expression that I need to drastically reduce in size, both for readability and to keep errors from creeping in. For example, I would like to have the variable 'test' point to the a location 'grid[rcount-1][ccount-1]' so that everywhere I would use 'grid.', I could replace it with 'test' How would I accomplish that? Thanks. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making big 'uns into little 'uns
On 09/06/2012 07:15 AM, Dave Angel wrote: > On 09/06/2012 09:56 AM, Ray Jones wrote: >> I have a multiple 'if' expression that I need to drastically reduce in >> size, both for readability and to keep errors from creeping in. >> >> For example, I would like to have the variable 'test' point to the a >> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >> 'grid.', I could replace it with 'test' How would I accomplish that? >> >> Thanks. >> >> > Easiest way: switch to C++ > > There is no preprocessor in Python, and no addresses. There are some > places you could fake such stuff, but not the expression you have. > > If I HAD to do something like this for Python, I'd write a > preprocessor. But one reason I came to Python is its elegance, and a > preprocessor isn't elegant. Well, of all the. a REAL programming language. I mean, even Bash ;;)) Anyway, it was a shot. Thanks. Ray > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making big 'uns into little 'uns
On 09/06/2012 07:33 AM, Peter Otten wrote: > Ray Jones wrote: > >> I have a multiple 'if' expression that I need to drastically reduce in >> size, both for readability and to keep errors from creeping in. >> >> For example, I would like to have the variable 'test' point to the a >> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >> 'grid.', I could replace it with 'test' How would I accomplish that? >>>> class Grid(object): > ... def __init__(self, rows): > ... self.rows = rows > ... def __getitem__(self, index): > ... return self.rows[index] > ... @property > ... def test(self): > ... return self[-1][-1] > ... Excellent! Now I am going to save this message for the time when I've advanced to classes and objects! Thanks, Peter. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making big 'uns into little 'uns
On 09/06/2012 07:35 AM, Jerry Hill wrote: > On Thu, Sep 6, 2012 at 10:15 AM, Ray Jones wrote: >> Well, of all the. a REAL programming language. I mean, even >> Bash ;;)) >> >> Anyway, it was a shot. Thanks. > There's almost certainly a way to accomplish your goal of simplifying > your giant nested if statements. It just doesn't involve pointers. > Perhaps if you mocked up a representative example for us to look at > and play with, someone could come up with a suggestion. > > For instance, if your set of if statements is emulating what would be > done with a case statement in other languages, dictionary based > dispatch may be a cleaner way to do the same thing in python. > Thanks for the reply, Jerry. I actually can do it relatively easily with just a few nested 'if' statements.I was trying multiple tests within the same 'if' statement. I'm simplifying it by changing into a 0-based loop rather than a 1-based loop (don't have to worry about the '-1' stuff). I'm not certain where I'm going with it yet - it's a udacity assignment that I'm still trying to work out in my head. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making big 'uns into little 'uns
On 09/06/2012 07:48 AM, Dave Angel wrote: >>> On 09/06/2012 09:56 AM, Ray Jones wrote: >>>> I have a multiple 'if' expression that I need to drastically reduce in >>>> size, both for readability and to keep errors from creeping in. >>>> >>>> For example, I would like to have the variable 'test' point to the a >>>> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >>>> 'grid.', I could replace it with 'test' How would I accomplish that? >>>> >>>> Thanks. >>>> >>>> >>> > I don't know your use-case. For that matter, I don't even know what > semantics you mean by the grid[xx][yy] expression. For example, are > grid, rcount, and ccount globals? Or are you constraining 'test' to > only be used in the context where they are all visible? Or are you > defining this location as the offset within grid where rcount and ccount > happen to point to right now? I can see maybe a dozen "reasonable" > meanings, each requiring a different sets of constructs in the language > or its preprocessor. > > One thing you can do in Python, but not in any other language I've used, > is to define a class instance property. For example, if you were > willing to use q.test instead of test, you could do something like: > > class Q(object): > @property > def test(self): > return grid[rcount-1][ccount-1] > > That would give you readonly access to an object defined by 3 variables > that have to be visible to the Q code. And you could make the > expression more complex if grid is defined elsewhere, for example. > > Now once you do q = Q(), you can use > q.test instead of the larger expression. > > Lots of other possibilities in Python. But not with exactly your > original syntax. Using this one as is would be ugly code, as is your > original example. So presumably you have an actual use-case where this > makes sense, other than saving typing. > Basically it's as simple as ensuring that an array consists of integers, and that those integers fall within a certain range. Rather than using multiple 'if' statements, I was (am, at this point) using multiple tests within a single 'if' statement. Nothing earth-shatteringly difficult, but I was simply looking for a way to shorten the overall test expression with a recursive(? is that the term) variable. No problem though. Thanks. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making big 'uns into little 'uns
On 09/06/2012 08:29 AM, Walter Prins wrote: > Hi Ray, > > On 6 September 2012 15:59, Ray Jones wrote: >> Basically it's as simple as ensuring that an array consists of integers, >> and that those integers fall within a certain range. Rather than using >> multiple 'if' statements, I was (am, at this point) using multiple tests >> within a single 'if' statement. Nothing earth-shatteringly difficult, >> but I was simply looking for a way to shorten the overall test >> expression with a recursive(? is that the term) variable. No problem though. > By array I suppose you mean "list of lists of items"? Yes. > Anyway, if you have such a structure, and you want to "visit" each in > turn to check it, you can do this: > > for sublist in grid: > for item in sublist: > # code to check if "item" is in range goes here > > The above obviously doesn't actually track the "row" or "column" > you're checking. If you'd like to keep track of what "row"/"column" > you're on, you can for example do: > > for row, sublist in enumerate(grid): > for col, item in enumerate(sublist): > # code to check if "item" is in range goes here Our homework "monitor" complains if we use code that hasn't been discussed in session yet. We haven't even progressed to 'range' in the for loops yet - I don't think 'enumerate' would be appreciated. lol Technically, any variable pointer that I had managed to drum up here would have been frowned upon, but I didn't figure it would have been a serious breach. I've got a pretty good handle on doing it the "hard way". I'm swatting bugs right now... :)) Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making big 'uns into little 'uns
On 09/06/2012 10:05 AM, Alan Gauld wrote: > On 06/09/12 14:56, Ray Jones wrote: >> I have a multiple 'if' expression that I need to drastically reduce in >> size, both for readability and to keep errors from creeping in. >> >> For example, I would like to have the variable 'test' point to the a >> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >> 'grid.', I could replace it with 'test' How would I accomplish that? > > > I may have missed some messages but this is context free. > What are these multiple if statements? > Why would "reducing" them improve readability? It might make them > shorter but more cryptic. > > As to the other question, is > > test = grid[rcount-1][ccount-1] > > too obvious? > I went out to the kitchen for a bit to eat an hour or so ago and suddenly did a face-palm! Duh! I'm going to have to quit dog-sitting for my niece - these all-nighters are killing my thinking ability! Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making big 'uns into little 'uns
On 09/06/2012 05:31 PM, Steven D'Aprano wrote: > On 06/09/12 23:56, Ray Jones wrote: >> I have a multiple 'if' expression that I need to drastically reduce in >> size, both for readability and to keep errors from creeping in. >> >> For example, I would like to have the variable 'test' point to the a >> location 'grid[rcount-1][ccount-1]' so that everywhere I would use >> 'grid.', I could replace it with 'test' How would I accomplish that? > > Um, am I missing something blindingly obvious here? > > What about this? > > test = grid[rcount-1][ccount-1] # I can never think of good names... > if test < 1: > process(test) > elif test == 1: > do_something_different(test, 2, 3, 4) > elif 1 < test <= 100: > do_another_thing(test, "ham", "cheese") > # and so on... > No, you're not missing something blindingly obvious - I was! Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making big 'uns into little 'uns
On 09/06/2012 05:34 PM, Steven D'Aprano wrote: > On 07/09/12 01:33, Ray Jones wrote: > >> Our homework "monitor" complains if we use code that hasn't been >> discussed in session yet. > > The good old "teaching by enforced ignorance" method. > Actually I like what they're doing. First of all, this is a CS101 class - not a Python class. I've done some (relatively - from my viewpoint) advanced programming by knowing what I wanted to accomplish and finding a (in the past) Bash tool to accomplish it. In fact, as I've been converting my Bash scripts to Python, I've been doing pretty much the same thing (which is why I subscribed to this list ;) ). But somewhere along the line I will be trying to do something that a specific tool won't accomplish: I'll have to use my brain! I've never known what I could and could not accomplish without another, stronger, tool, so I never really tried. Now I'm learning to apply my mind to problems that I KNOW can be accomplished with basic code and applying my mind to solving the problems. ;) Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] urllib2.urlopen(....., timeout=)
2.7.3 According to the docs, urlopen has a timeout capability. But it says that the timeout = '' I've tried integers as the timeout value, I've tried floatsit doesn't complain about my values, but neither does it timeout. Can anyone point me to the solution to getting the urlopen to timeout if the target system isn't responding for some reason? What kind of objects is it expecting? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] urllib2.urlopen(....., timeout=)
On 09/07/2012 08:33 AM, Steven D'Aprano wrote: > On 08/09/12 01:16, Ray Jones wrote: >> 2.7.3 >> According to the docs, urlopen has a timeout capability. But it says >> that the timeout = '' > > Which docs are those? According to these docs: > > http://docs.python.org/library/urllib2.html > > "The optional timeout parameter specifies a timeout in seconds for > blocking operations like the connection attempt (if not specified, > the global default timeout setting will be used). This actually > only works for HTTP, HTTPS and FTP connections." > I was looking at the doc strings(?) in iPython's help system. > Can you give an actual working example of what you have tried, what > you expect to happen, and what actually happens? > See my response to Dave Angel, and thanks for the reply. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] urllib2.urlopen(....., timeout=)
On 09/07/2012 08:32 AM, Dave Angel wrote: > On 09/07/2012 11:16 AM, Ray Jones wrote: >> 2.7.3 >> According to the docs, urlopen has a timeout capability. But it says >> that the timeout = '' >> >> I've tried integers as the timeout value, I've tried floatsit >> doesn't complain about my values, but neither does it timeout. Can >> anyone point me to the solution to getting the urlopen to timeout if the >> target system isn't responding for some reason? What kind of objects is >> it expecting? >> > I'm curious why the docstring says... timeout = > but have no clues for you. > > See http://docs.python.org/library/urllib2.html > > which says: > > The optional /timeout/ parameter specifies a timeout in seconds for > blocking operations like the connection attempt (if not specified, the > global default timeout setting will be used). This actually only works > for HTTP, HTTPS and FTP connections. > > So I'd figure it wants an int, or maybe a float, as you've tried. is it > possible that you're opening something which is neither HTTP, HTTPS nor > FTP? What parameters exactly are you passing to urlopen ? My urlopen string is the following: urllib2.urlopen('http://%s:%s' % (ip, port), 'timeout = 2') Aha! See my problem? I just noticed it. I've been treating the 'timeout' portion as though I'm passing it as a command line parameter or something. I removed the quotes and all is swell! Y'all are awesome. Even when you don't have enough information to know the solution you help me! :) Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Seeing response from authorization page with urllib2
If I open a web page in my browser, I get a pop-up window that informs me that I need to provide authorization information. But often, in addition, that little pop-up window will give me some additional information supplied by the page itself. For example, the chromium browser pop-up might say, "The server requires a username and password. The server says: x" But when I attempt to get any part of an authorization-required page using urllib2.urlopen(), I immediately receive the 401 error. Even the intended object variable is left in an undefined state, so using info() doesn't seem to work. How can I get that information from the server? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] 2.7.3 documentation gripe (feel free to ignore)
6.5. The del <http://docs.python.org/reference/simple_stmts.html#del> statement *del_stmt* ::= "del" target_list <http://docs.python.org/reference/simple_stmts.html#grammar-token-target_list> Deletion is recursively defined very similar to the way assignment is defined. Rather than spelling it out in full details, here are some hints. === They call this DOCUMENTATION??? "it's similar to such and such - you figure it outhere are the hints"! Bah! I hope their code is better than the documentation. :-p Ray P.S. Not a request for help - I can find the answers. Just a comment on the documentation in general ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] (2.7.3) Inexplicable change of type
The code: def split_string(source,splitlist): idx = 0 while idx < len(splitlist): if splitlist[idx] in source: source = ' '.join(source.split(splitlist[idx])) idx += 1 source = source.split(' ') print "source is", source, "and its type is", type(source) # <-- while "'' in source:# <-- source = source.remove('') return source out = split_string('Hi! I am your Assistant Instructor, Peter.', '! ,.') print out The result: source is ['Hi', '', 'I', 'am', 'your', 'Assistant', 'Instructor', '', 'Peter', ''] and its type is Traceback (most recent call last): File "/tmp/pytmp.py", line 18, in out = split_string('Hi! I am your Assistant Instructor, Peter.', '! ,.') File "/tmp/pytmp.py", line 13, in split_string while '' in source: TypeError: argument of type 'NoneType' is not iterable Between the two arrows, 'source' inexplicably switches from to . Why? Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (2.7.3) Inexplicable change of type
On 09/14/2012 02:07 AM, Steven D'Aprano wrote: > On 14/09/12 18:43, Ray Jones wrote: > >> Between the two arrows, 'source' inexplicably switches from >> to. Why? > > source.remove('') does not do what you think it does. Checking the > Fine Manual is always a good idea, or experimentation at the interactive > interpreter: [...] > So source = source.remove(' ') replaces source with None instead of the > list, which is then lost. > > By the way, at the interactive interpreter you can also say: > > > help(list.remove) > > to read some documentation on the method. > I did use the help() on that, but I missed the 'in place' part. That would explain things! :)) Thanks. Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (2.7.3) Inexplicable change of type
Thanks for the responses. I knew it had to be something stupid ;)). Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 2.7.3 documentation gripe (feel free to ignore)
On 09/14/2012 02:32 AM, Steven D'Aprano wrote: > On 14/09/12 17:29, Ray Jones wrote: >> >> 6.5. The del >> <http://docs.python.org/reference/simple_stmts.html#del> statement > [...] >> They call this DOCUMENTATION??? "it's similar to such and such - you >> figure it outhere are the hints"! > I'm honestly not sure that there would be any advantage to spelling out > in gory detail over a page and a half how del works, but if you think the > documentation is lacking, remember that Python is an open-source project > and community input is welcome and desired. > Great reply to sour grapes! lol I'll remember that ;). Ray ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to run this block of code dozens of times
On 09/17/2012 02:46 AM, eryksun wrote: > On Sun, Sep 16, 2012 at 11:17 PM, Steven D'Aprano wrote: >> Other uses are: >> >> * a single leading underscore usually means "private, don't touch" >> >> * double leading and trailing underscore names have special meaning >> to Python, e.g.: > There's also the _() function for I18N: Hey, I've been on that freeway - up around Chicago, right? ;) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor