From dcmoody2 at gmail.com Sun Feb 1 02:54:48 2015 From: dcmoody2 at gmail.com (Daniel M) Date: Sat, 31 Jan 2015 20:54:48 -0500 Subject: [Tutor] decision loops Message-ID: Hello. I'm a complete beginner and I?m trying to write a very basic script to convert temperatures, just for some practice. I have that part down, but I can?t figure out how to make the script switch between the two. What I would like it to do is let the user go back to the ?What do you wish to convert?? part when a character is entered instead of a number for ?temperature??. I tried using elif m == *char* print (*"What do you wish to convert to?"*) temp = raw_input(*">> "*) but it seems useless regardless of where I put it. It gives me the error ? return eval(raw_input(prompt)) File "", line 1, in NameError: name 't' is not defined? when I enter a character. I?m sure I?m missing something very obvious but I can?t seem to figure it out. Where am I going wrong? def *ftoc*(x): #Fahrenheit to Celsius x == float y = x-32.0 z = y * 5.0 return z //9.0 def *ctof*(x): #Celsius to Fahrenheit x == float y = x * 9.0 z = y // 5.0 return z + 32.0 print (*"What do you wish to convert to?"*) temp = raw_input(*">> "*) while temp == *"c"* or temp == *"f"* and not temp == *"q"*: if temp == *"c"*: m = float(input(*"temperature?"*)) print ftoc(m) print *"Celcius"* elif temp == *"f"*: m = float(input(*"temperature?"*)) print ctof(m) print (*"Farenheit"*) elif temp == *"q"*: break From steve at pearwood.info Sun Feb 1 11:14:36 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 1 Feb 2015 21:14:36 +1100 Subject: [Tutor] decision loops In-Reply-To: References: Message-ID: <20150201101435.GM2498@ando.pearwood.info> Hello Daniel, and welcome! On Sat, Jan 31, 2015 at 08:54:48PM -0500, Daniel M wrote: > Hello. I'm a complete beginner and I?m trying to write a very basic script > to convert temperatures, just for some practice. I have that part down, but > I can?t figure out how to make the script switch between the two. What I > would like it to do is let the user go back to the ?What do you wish to > convert?? part when a character is entered instead of a number for > ?temperature??. I tried using > > elif m == *char* > > print (*"What do you wish to convert to?"*) > > temp = raw_input(*">> "*) Why are there asterisks around parts of your code? That's a syntax error in Python. I'm guessing that you didn't type them yourself, and that your email program is doing it. You should set your email program to only send plain text, not "Rich Text" or formatted text or HTML or whatever silly thing it is trying to do. > but it seems useless regardless of where I put it. It gives me the error ? > return eval(raw_input(prompt)) In the code you show below, there is no mention of eval. So that is your first mistake: whether you intended to or not (I'm pretty sure it wasn't deliberate!) you are telling us falsehoods. The code you say you are running is not the code you are actually running. How can we tell what you are doing wrong when we cannot see what you are doing? Mistake number two is using eval. As a beginner, there are three rules you should remember about eval: (1) If you think you might need to use eval, you don't. (2) If you are positive that you really do need to use eval, you probably don't. (3) For experts only -- if you are sure that you need to use eval, you might. The problems with eval are: - its slow - its tricky to use right except for the simplest cases - it can be dangerous and introduce serious security holes in your code if you aren't careful > File "", line 1, in > > NameError: name 't' is not defined? when I enter a character. Mistake number three: I'm guessing that you didn't enter any old character. I'm guessing you entered 't' rather than 's' or '3' or '.' or some other character. Your mistake is to make us guess: when asking for help, you should tell us what you did specifically, not vaguely. In this case, I think I can reproduce your problem: py> eval(raw_input("Enter a character: ")) Enter a character: t Traceback (most recent call last): File "", line 1, in File "", line 1, in NameError: name 't' is not defined I don't get that error from any random character, only from t. If I type a different character, I get a different error. Why? Because of eval. You're telling Python to evaluate what you typed as if it were code: py> eval(raw_input("Enter a character: ")) Enter a character: len([1, 2, 3]) + 1000 1003 You don't need eval here. It does nothing useful. What you want is simply raw_input(prompt). Hope that helps. -- Steve From skpsharma at gmail.com Sun Feb 1 13:09:17 2015 From: skpsharma at gmail.com (sathya kumar Prasanna) Date: Sun, 1 Feb 2015 17:39:17 +0530 Subject: [Tutor] first post Message-ID: Hi guys, I am completely new to programming and have never had the opportunity to do attempt coding before. However I have started now and am facing my first problem. The code is as shown, I need to *fill in the blanks* such that when the code is run it gives the answer as "True". #Please help. # Make sure that the_flying_circus() returns True def the_flying_circus(): if ________: # Start coding here! # Don't forget to indent # the code inside this block! elif ________: # Keep going here. # You'll want to add the else statement, too! Thanks and Regards Mr. Sathyakumar Sharma, Developmental Engineer, Dr. T. M. A. Pai Planetarium, Manipal Center for Natural Sciences, Manipal University, Madhav Nagar, Manipal-576104, Karnataka Phone: +91 820 2571922 | +91 820 2923557 | +91 820 2923571 http:/ / sharma-astronomy.weebly.com From alan.gauld at btinternet.com Sun Feb 1 15:19:53 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 01 Feb 2015 14:19:53 +0000 Subject: [Tutor] decision loops In-Reply-To: References: Message-ID: On 01/02/15 01:54, Daniel M wrote: > I can?t figure out how to make the script switch between the two. What I > would like it to do is let the user go back to the ?What do you wish to > convert?? part when a character is entered instead of a number for > ?temperature??. I tried using That's quite a complex task you've set yourself. You need to differentiate numbers and characters even though you read them all as characters from the users. It might be simpler just to keep the numeric and character processing separate for now. And maybe for good. Also your subject says 'decision loops' Those are two completely separate things. decisions are made using if/elif/else constructs loops are repetitions involving 'for' or 'while' constructs (and a few more advamced ones later) You probably need both to solve your problem but do not confuse or merge the two ideas in your mind. At this stage we appear to only be dealing with decisions. The loops can wait till later. > elif m == *char* > print (*"What do you wish to convert to?"*) > temp = raw_input(*">> "*) The asterisks don't make sense, I'm guessing your mail program put them in because you made it bold or some-such? Please always use plain text when sending code. However, we can't really make much sense of it even without asterisks because we have no context. We don't know what 'm' is, where it comes from etc. Also m == char only makes sense if you have defined a variable called char somewhere, again we can't see it. Or are you simply trying to explain that you want to test m to see if it is a character? Its not clear. Don't make us guess. > but it seems useless regardless of where I put it. It gives me the error ? > return eval(raw_input(prompt)) And that line doesn't seem to appear in your code anywhere? And its only a bit of an error message, please always send us the whole error because its full of useful information. > File "", line 1, in > > NameError: name 't' is not defined? when I enter a character. This suggests that you passed a 't' to eval. The 't' must have come from the raw_input() but again you didn't tell us that we have to guess. I assume you get a slightly differnt error if you enter, say, a 'v' or a 'w'? > missing something very obvious but I can?t seem to figure it out. Probably but you aren't giving us enough specific detail to be able to help you reliably. > def *ftoc*(x): #Fahrenheit to Celsius > x == float > y = x-32.0 > z = y * 5.0 > return z //9.0 x = float doesn't do anything useful here. It assigns a new name (x) to the float type convertion function. I'm guessing(again) that what you really meant was x = float(x) to force x to be a floating point number? Also // produces integer division. I'm pretty sure you want regular float division z/9.0 > def *ctof*(x): #Celsius to Fahrenheit > x == float > y = x * 9.0 > z = y // 5.0 > return z + 32.0 Pretty much the same comments as above > print (*"What do you wish to convert to?"*) > temp = raw_input(*">> "*) > while temp == *"c"* or temp == *"f"* and not temp == *"q"*: > if temp == *"c"*: > m = float(input(*"temperature?"*)) > print ftoc(m) > print *"Celcius"* > elif temp == *"f"*: > m = float(input(*"temperature?"*)) > print ctof(m) > print (*"Farenheit"*) > elif temp == *"q"*: > break OK, Now we see where 'm' fits in, although your char test above is missing. Also we see you using input() instead of raw_input() That's nearly always a mistake. Its better to use raw_input() and then explicitly convert to the type you want(which you do here anyway) So use: m = float(raw_input("temperature?")) Finally you probably want the unit selection inside the while loop so try something like this skeleton code: while True: temp = raw_input("What do you wish to convert to?") if temp == 'q': break if temp == "c": m = float(raw_input("temperature?")) print ftoc(m) print "Celcius" elif temp == "f": m = float(raw_input("temperature?")) print ctof(m) print ("Farenheit") -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From davea at davea.name Sun Feb 1 15:23:47 2015 From: davea at davea.name (Dave Angel) Date: Sun, 01 Feb 2015 09:23:47 -0500 Subject: [Tutor] first post In-Reply-To: References: Message-ID: <54CE36F3.9010703@davea.name> On 02/01/2015 07:09 AM, sathya kumar Prasanna wrote: > Hi guys, > > I am completely new to programming Welcome to the Python tutor forum. Thanks for posting in text format, but you forgot to describe your Python version and operating system. > and have never had the opportunity to do > attempt coding before. However I have started now and am facing my first > problem. > The code is as shown, I need to *fill in the blanks* such that when the > code is run it gives the answer as "True". > > #Please help. > > # Make sure that the_flying_circus() returns True > def the_flying_circus(): > if ________: # Start coding here! > # Don't forget to indent > # the code inside this block! > elif ________: > # Keep going here. > # You'll want to add the else statement, too! > You forgot to post the rest of the assignment. As it stands, one answer could be: def the_flying_circus(): if "the moon" == "green cheese": pass elif 6*9 == 42: pass else: pass return True Naturally, the function contents don't matter much if you don't call it, so you'd need to add a line like: print( repr(the_flying_circus()) ) to actually call the function. -- DaveA From breamoreboy at yahoo.co.uk Sun Feb 1 15:34:45 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 01 Feb 2015 14:34:45 +0000 Subject: [Tutor] first post In-Reply-To: References: Message-ID: On 01/02/2015 12:09, sathya kumar Prasanna wrote: > Hi guys, > > I am completely new to programming and have never had the opportunity to do > attempt coding before. However I have started now and am facing my first > problem. > The code is as shown, I need to *fill in the blanks* such that when the > code is run it gives the answer as "True". > > #Please help. > > # Make sure that the_flying_circus() returns True > def the_flying_circus(): > if ________: # Start coding here! > # Don't forget to indent > # the code inside this block! > elif ________: > # Keep going here. > # You'll want to add the else statement, too! > > Thanks and Regards > Mr. Sathyakumar Sharma, That's easy, simply add "Return True" as the last line of your function. However I suspect that you haven't asked the correct question. Did you actually mean "How do I test that the call to the_flying_circus returns True?"? If I'm correct in Python you normally check for "truthiness" as opposed to the actual values "True" and "False". Hence:- if the_flying_circus(): doThis() else: doThat() -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at btinternet.com Sun Feb 1 15:28:57 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 01 Feb 2015 14:28:57 +0000 Subject: [Tutor] Fwd: Re: Lost message re serial comms In-Reply-To: <002101d03e29$6e28e720$4a7ab560$@net> References: <002101d03e29$6e28e720$4a7ab560$@net> Message-ID: <54CE3829.6060600@btinternet.com> This was the problematic serial question. *From:*Doug Basberg [mailto:dbasberg at comcast.net] *Sent:* Friday, January 30, 2015 5:29 PM *To:* 'tudor at python.org' *Subject:* doing rs232 serial with binary data ?? with pyserial?? Hello group; I am new to python and worked mostly in C & C++ (and assembly). I do embedded controls and usually use the internet or LAN to log data and do controls. So, in Python I found pyserial and wish to use it to send binary to controlled devices (in this case to a Modbus protocol solar charge controller (TriStar TS-60). In C++ I would setup ?structs? or class attributes to hold the byte oriented commands and controller responses and then send them to rs232 as binary. I do not see how to do that with pyserial. What I need is to send and receive binary (not strings) over rs232. In this case from/to a Raspberry Pi (RPI) controller to/from the solar charge controller. The RPI runs apache server to handle the network. Any suggestions will be greatly appreciated. I have been using Python2.7 so far. Thanks Doug From steve at pearwood.info Sun Feb 1 15:53:03 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 2 Feb 2015 01:53:03 +1100 Subject: [Tutor] first post In-Reply-To: References: Message-ID: <20150201145303.GN2498@ando.pearwood.info> Hi, and welcome! My answers are below, interleaved between your comments. On Sun, Feb 01, 2015 at 05:39:17PM +0530, sathya kumar Prasanna wrote: > Hi guys, > > I am completely new to programming and have never had the opportunity to do > attempt coding before. However I have started now and am facing my first > problem. > The code is as shown, I need to *fill in the blanks* such that when the > code is run it gives the answer as "True". I think the question you have been asked is underspecified. There are so many possibly ways to answer this, and it isn't clear which ones are acceptable. So I'm going to guess. > #Please help. > > # Make sure that the_flying_circus() returns True > def the_flying_circus(): > if ________: # Start coding here! > # Don't forget to indent > # the code inside this block! > elif ________: > # Keep going here. > # You'll want to add the else statement, too! I think they are hoping to demonstrate an if...elif...else block. But as given, the question is silly, because the function takes no arguments and always returns the same result! So, as a programmer, I would answer that by writing: def the_flying_circus(): # a terrible name for this function return True but unfortunately that doesn't answer the question of "fill in the blanks", so we have to write a silly function that does needless work in order to satisfy the question. (I think you can tell I do not think much of this question. Is it from Code Academy?) So let's try again: def the_flying_circus(): if 23 > 1000: # This is never true, so we can return anything. return False elif 1000 > 23: # This is always true, so return True. return True else: # This is dead code (unreachable), it will never run. return False This should, I think, satisfy the question: it demonstrates an if clause, an elif clause and an else clause. And it always returns True. If you are wondering about the name of the function, the programming language "Python" is not named after the snake, but after a British comedy program of the 1970s called "Monty Python's Flying Circus", or just Monty Python for short: http://en.wikipedia.org/wiki/Monty_Python Consequently, there is a common practice in Python programming circles of using Monty Python related terms. -- Steve From breamoreboy at yahoo.co.uk Sun Feb 1 15:56:37 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 01 Feb 2015 14:56:37 +0000 Subject: [Tutor] Fwd: Re: Lost message re serial comms In-Reply-To: <54CE3829.6060600@btinternet.com> References: <002101d03e29$6e28e720$4a7ab560$@net> <54CE3829.6060600@btinternet.com> Message-ID: On 01/02/2015 14:28, Alan Gauld wrote: > This was the problematic serial question. > > *From:*Doug Basberg [mailto:dbasberg at comcast.net] > *Sent:* Friday, January 30, 2015 5:29 PM > *To:* 'tudor at python.org' > *Subject:* doing rs232 serial with binary data ?? with pyserial?? > > Hello group; > > I am new to python and worked mostly in C & C++ (and assembly). I do > embedded controls and usually use the internet or LAN to log data and do > controls. > > So, in Python I found pyserial and wish to use it to send binary to > controlled devices (in this case to a Modbus protocol solar charge > controller (TriStar TS-60). > > In C++ I would setup ?structs? or class attributes to hold the byte > oriented commands and controller responses and then send them to rs232 > as binary. I do not see how to do that with pyserial. > > What I need is to send and receive binary (not strings) over rs232. In > this case from/to a Raspberry Pi (RPI) controller to/from the solar > charge controller. The RPI runs apache server to handle the network. > > Any suggestions will be greatly appreciated. I have been using > Python2.7 so far. > > Thanks > > Doug > I'm no expert but I think you need the struct module from the standard library https://docs.python.org/2/library/struct.html#module-struct This list is geared towards beginners to Python and/or programming. If you try the struct module and run into problems please ask further questions on the main Python mailing list available at https://mail.python.org/mailman/listinfo/python-list, as gmane.comp.python.general or news:comp.lang.python -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at btinternet.com Sun Feb 1 23:14:08 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 01 Feb 2015 22:14:08 +0000 Subject: [Tutor] Fwd: Re: Lost message re serial comms In-Reply-To: <54CE3829.6060600@btinternet.com> References: <002101d03e29$6e28e720$4a7ab560$@net> <54CE3829.6060600@btinternet.com> Message-ID: On 01/02/15 14:28, Alan Gauld wrote: > So, in Python I found pyserial and wish to use it to send binary to > controlled devices (in this case to a Modbus protocol solar charge > controller (TriStar TS-60). > > In C++ I would setup ?structs? or class attributes to hold the byte > oriented commands and controller responses and then send them to rs232 > as binary. I do not see how to do that with pyserial. Its not a PySerial function but Python allows you to define classes which can hold yoiuur data for you just like C++ Any reasonable python tutorial will tell you about the syntax. Alternatively you could use the more advanced data types in Python to do the same thing, either a dictionary or even a list or tuple could be used. > What I need is to send and receive binary (not strings) over rs232. The struct module is possibly what you need. It contains functions somewhat like sprintf() and sscanf() in C. You can convert binary data into byte strings and vice versa. > this case from/to a Raspberry Pi (RPI) controller to/from the solar > charge controller. The RPI runs apache server to handle the network. The type of computer is probably irrelevant for this case, although the OS and python version are not. Lets assume Linux and Python 2.7 Pyserial and struct and a dictionary or class should do all you need. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dedmons at comcast.net Sun Feb 1 21:16:07 2015 From: dedmons at comcast.net (D.Edmons) Date: Sun, 01 Feb 2015 12:16:07 -0800 Subject: [Tutor] GUI Message-ID: <54CE8987.3000708@comcast.net> Hi, Background: I've compiled both python2 and python3 and am starting to learn them well enough to do a GUI application that requires UTF-8. I've done quite a bit of maintenance programming (fixing bugs, minor updates, etc) but the only major application I've written was a disk driver for RT-11X on Linux using FUSE (quite a project, considering that I had no specification!). Anyway, I suspect that I'll have to use python3 to take advantage of the UTF-8 (is there a __FUTURE__ option for python2?). I've done some very minor GUI stuff, but what I need is an application that will do Hebrew (left <-- right) that actually attempts to "get it right". Also, I'm creating a Hebrew Dictionary database and my GUI will have to work with it (ie. it is the whole purpose of this exercise). I started out with Perl, but haven't made much progress. Python kept coming up in my searches, so I'm attempting to switch over. Here are the major features I hope to incorporate into the application: ?) Hebrew keyboard application that will easily switch back and forth between English and Hebrew character sets. Key assignments will be user defined or easily reprogrammed so that both standard and custom configurations can be made: (ie similar to http://www.lexilogos.com/keyboard/hebrew.htm ) ?) Dual screen editor for simplified search and replace (hebrew with nikkud, with option to ignore the nikkud/vowels to find shoreshim/roots) feature. One window will be the compiled dictionary. The second window will be any Hebrew text (Torah, Siddur, etc...). The application will--hopefully--automatically search the "dictionary" based upon the current cursor and add the English definition of the Hebrew word with a click or two. (I'm learning Hebrew, as I go, studying every week, if not every day.) ?) Obviously, a menu bar with tools and other standard GUI bits and pieces. Actual Request: I'm running an older Debian Linux, that doesn't upgrade very well. Is there anybody willing to help me at least get started or point me in the right direction? Time isn't a huge factor. I've been working on the database for five years now (using sqlite 3.7.3 and UTF-8 text). Knowledge of Hebrew would be a *huge* plus, but isn't required in any way. I'm currently reading the Tutorials I've gleaned from the Python homepage. I've never written more than trivial GUI applications. I currently use leafpad for my UTF-8 editor. Though it is a little buggy--this should be fixed if I can get my libraries uptodate--it handles the UTF-8 text as well as I expect it to, whereas others don't. Thus, leafpad would be a reasonable model for the editor. (btw, I got this e-mail link from the Website Tutorial which is supposed to be included in the distro--I haven't checked.) Shalom, Dale Edmons/ ??????? ???? ????????? From cristian.distefano at isprambiente.it Mon Feb 2 08:52:23 2015 From: cristian.distefano at isprambiente.it (Cristian Di Stefano) Date: Mon, 02 Feb 2015 08:52:23 +0100 Subject: [Tutor] Assistance with UnicodeDecodeError In-Reply-To: <54CD5AE9.40604@davea.name> References: <54CD5AE9.40604@davea.name> Message-ID: <54CF2CB7.20704@isprambiente.it> Hi Dave, you should set the correct encoding (maybe utf-8) in order to handle data from web. You cannot handle unicode data with simple string, you should encode to ASCII or manage data with the unicode type Best Cristian Il 31/01/2015 23:44, Dave Angel ha scritto: > On 01/31/2015 08:37 AM, J Mberia wrote: >> Hi, >> > > Welcome to Python tutor. Thanks for posting using text email, and for > specifying both your Python version and Operating system. > >> I am teaching myself programming in python and assistance with >> UnicodeDecodeError >> >> I am trying to scrap text from a website using Python 2.7 in windows >> 8 and >> i am getting this error *"**UnicodeDecodeError: 'charmap codec can't >> encode >> character u'\u2014 in position 11231 character maps to "* >> >> *How do i resolve? Pls assist.* >> > > You can start by posting the whole error message, including the stack > trace. Then you probably should include an appropriate segment of > your code. > > The message means that you've got some invalid characters that you're > trying to convert. That can either be that the data is invalid, or > that you're specifying the wrong encoding, directly or implicitly. > --- Questa e-mail ? stata controllata per individuare virus con Avast antivirus. http://www.avast.com From davea at davea.name Mon Feb 2 09:30:59 2015 From: davea at davea.name (Dave Angel) Date: Mon, 02 Feb 2015 03:30:59 -0500 Subject: [Tutor] Assistance with UnicodeDecodeError In-Reply-To: <54CF2CB7.20704@isprambiente.it> References: <54CD5AE9.40604@davea.name> <54CF2CB7.20704@isprambiente.it> Message-ID: <54CF35C3.10301@davea.name> On 02/02/2015 02:52 AM, Cristian Di Stefano wrote: > Hi Dave, > > you should set the correct encoding (maybe utf-8) in order to handle > data from web. You cannot handle unicode data with simple string, you > should encode to ASCII or manage data with the unicode type > > Best > Cristian > Please don't top-post, as it confuses who wrote what part and in what sequence. But I can see you're already confused, as you're addressing me when replying to J Mberia. In any case, one cannot encode to ASCII, so you have to be much more explicit in what you're trying to say. Or just wait till the OP clarifies his own code. > Il 31/01/2015 23:44, Dave Angel ha scritto: >> On 01/31/2015 08:37 AM, J Mberia wrote: >>> Hi, >>> >> -- DaveA From bw_dw at fastmail.fm Mon Feb 2 14:45:08 2015 From: bw_dw at fastmail.fm (dw) Date: Mon, 02 Feb 2015 05:45:08 -0800 Subject: [Tutor] Wondering about a project Message-ID: <1422884708.2252746.221956693.3C62378E@webmail.messagingengine.com> Hi Python gang. In my Ubuntu system, I'm pondering a first GUI Python project: 1) Prompt for a user input string. The intended string would be a youtube URL 2) Call youtube-dl to download the file 3) When the file is downloaded, call GnomePlayer or VLC to play the file I'm new at Python and haven't built a GUI application yet. I wonder if this project would be over my head? Perhaps I should attempt to build it in terminal mode first? -- Bw_dw at fastmail.net From maurice.horan at thomsonreuters.com Mon Feb 2 14:46:29 2015 From: maurice.horan at thomsonreuters.com (maurice.horan at thomsonreuters.com) Date: Mon, 2 Feb 2015 13:46:29 +0000 Subject: [Tutor] os module question Message-ID: <703CC1FDC2ABC449B5383FB0A18C8E525E47C880@UK2P-ERFMMBX16.ERF.thomson.com> Hi, This is my first post. I'm a sysadmin and I'm new enough to python so I'm trying to practice. I'm want to run a script that takes a server name from the command line and takes that servername which queries an internal asset database. I thought I could use the os module to take servername and run a command against it to query the database and then populate a variable. If the variable is equal to none it produces an error message in red, if it's successful then it prints it in green. I left a comment in for the first. Basically I have trouble with two things: 1) Get the server to take the hostname and use it to run a command against it 2) Send a variable (as opposed to a string) to the function to print Thanks for reading geveryone! Maurice #!/usr/bin/env python import sys import os hostname = sys.argv[1] no_of_args = len(sys.argv) # Colours for pass and fail class bcolours: PASS = '\033[32m' FAIL = '\033[31m' ENDC = '\033[0m' def disable(self): self.PASS = '' self.FAIL = '' self.ENDC = '' def print_red(string): red_string = bcolours.FAIL + string + bcolours.ENDC print(red_string) def print_green(string): green_string = bcolours.PASS + string + bcolours.ENDC print(green_string) if no_of_args != 2: print_red("Incorrect number of arguments entered") sys.exit(1) #hostname_ppid = os.system('queryhost', '-c patch', hostname) hostname_ppid1 = "queryhost -c patch 'hostname'" hostname_ppid = os.system(hostname_ppid1) if hostname_ppid == "None": print_red("No PPID") sys.exit(1) else: print_green(hostname_ppid) sys.exit(1) ________________________________ This e-mail is for the sole use of the intended recipient and contains information that may be privileged and/or confidential. If you are not an intended recipient, please notify the sender by return e-mail and delete this e-mail and any attachments. Certain required legal entity disclosures can be accessed on our website. From alan.gauld at btinternet.com Mon Feb 2 17:30:01 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 02 Feb 2015 16:30:01 +0000 Subject: [Tutor] Wondering about a project In-Reply-To: <1422884708.2252746.221956693.3C62378E@webmail.messagingengine.com> References: <1422884708.2252746.221956693.3C62378E@webmail.messagingengine.com> Message-ID: On 02/02/15 13:45, dw wrote: > Hi Python gang. > In my Ubuntu system, I'm pondering a first GUI Python project: > 1) Prompt for a user input string. > The intended string would be a youtube URL > 2) Call youtube-dl to download the file > 3) When the file is downloaded, call GnomePlayer or VLC to play the file > > I'm new at Python and haven't built a GUI application yet. > I wonder if this project would be over my head? > Perhaps I should attempt to build it in terminal mode first? Its usually a good idea to build a command line version first and in this case I'd say essential. The GUI bit is so trivial compared to the back end section that it should be simple - an input box and a button or two. Its much easier to build a GUI on top of something you know works, especially when you are new to GUIs! Your biggest choice is which GUI framework to use. Tkinter is the standard library option but wxPython, PyGTK and PyQt/pySide are also popular although third party downloads. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Feb 2 18:01:01 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 02 Feb 2015 17:01:01 +0000 Subject: [Tutor] os module question In-Reply-To: <703CC1FDC2ABC449B5383FB0A18C8E525E47C880@UK2P-ERFMMBX16.ERF.thomson.com> References: <703CC1FDC2ABC449B5383FB0A18C8E525E47C880@UK2P-ERFMMBX16.ERF.thomson.com> Message-ID: On 02/02/15 13:46, maurice.horan at thomsonreuters.com wrote: > This is my first post. I'm a sysadmin and I'm new enough to python so I'm trying to practice. Welcome to the list. It looks like you are running a Unix variant but it helps to tell us exactly which OS and Python version. > I'm want to run a script that takes a server name from the command line and > takes that servername which queries an internal asset database. > I thought I could use the os module to take servername and run a > command against it to query the database and then populate > a variable. You can, although you will also want the subprocess module to run the shell commands. Thee are several functions that will execute external programs in the os module but they are all deprecated in favour of subprocess which is safer and more flexible. > Basically I have trouble with two things: > 1) Get the server to take the hostname and use it to run a command against it os.uname() will return a tuple. The second item is the hostname > 2) Send a variable (as opposed to a string) to the function to print myfunc('astring') # call func with string myvar = 'astring' # assign string to a variable myfunc(myvar) # call func with variable notice where the quotes go...and that there are no $ or % signs needed to indicate variables, as per the shell/perl etc. > #!/usr/bin/env python > > import sys > import os > > hostname = sys.argv[1] > no_of_args = len(sys.argv) > > # Colours for pass and fail > class bcolours: > PASS = '\033[32m' > FAIL = '\033[31m' > ENDC = '\033[0m' > > def disable(self): > self.PASS = '' > self.FAIL = '' > self.ENDC = '' I'm not sure if you realize what this does? It does not change the values defined above. It creates local values in a specific object instance. I'll assume you know what the colour values are for your own terminal... > def print_red(string): > red_string = bcolours.FAIL + string + bcolours.ENDC > print(red_string) > > def print_green(string): > green_string = bcolours.PASS + string + bcolours.ENDC > print(green_string) And I assume you tested these at the >>> prompt. > if no_of_args != 2: > print_red("Incorrect number of arguments entered") > sys.exit(1) > > #hostname_ppid = os.system('queryhost', '-c patch', hostname) > hostname_ppid1 = "queryhost -c patch 'hostname'" > hostname_ppid = os.system(hostname_ppid1) This why you need subprocess. os.system only returns the error code, it will not let you access the command output. Read the subprocess docs they give many examples to show how to use it. I suspect you want something like: query = subprocess.Popen(['queryhost', '-c patch', hostname], stdout=subvprocess.PIPE) hostname_ppid = query.communicate()[0] It looks (and is) complicated compared to os.system() but its more secure and offers a lot of flexibility. Its well worth the extra pain. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Mon Feb 2 18:13:45 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 02 Feb 2015 17:13:45 +0000 Subject: [Tutor] GUI In-Reply-To: <54CE8987.3000708@comcast.net> References: <54CE8987.3000708@comcast.net> Message-ID: On 01/02/15 20:16, D.Edmons wrote: > I've compiled both python2 and python3 and am starting to learn them > well enough to do a GUI application that requires UTF-8. OK, We can help with the basics, thats what this group is for. Learning Python and its standard library. > Anyway, I suspect that I'll have to use python3 to take advantage of the > UTF-8 (is there a __FUTURE__ option for python2?). Python2 can work with unicode but its more effort than in Python 3 so I suspect you should go straight to Python 3. > minor GUI stuff, but what I need is an application that will do Hebrew > (left <-- right) that actually attempts to "get it right". Also, I'm > creating a Hebrew Dictionary database and my GUI will have to work with > it (ie. it is the whole purpose of this exercise). Don't expect a whole heap of support from the GUIs. A lot of the work will have to come from you. I suspect the standard GUI framework Tkinter is not going to be your best bet. You might find that PyQt or PyGTK will offer better multi lingual support (although thats just a guess on my part!). > I started out with Perl, but haven't made much progress. Python kept > coming up in my searches, so I'm attempting to switch over. Python or Perl do much the same thing. Python is easier to read (although being a Python group I'm biased...) > the major features I hope to incorporate into the application: > ?) Hebrew keyboard application that will easily switch back and > forth between English and Hebrew character sets. Key assignments will > be user defined or easily reprogrammed so that both standard and custom > configurations can be made: (ie similar to > http://www.lexilogos.com/keyboard/hebrew.htm ) I've no idea how you support that in a GUI. It may well be beyond the scope of this list too. I suspect that once you identify your target GUI framework that their support forums will be better suited to answer. > ?) Dual screen editor for simplified search and replace (hebrew > with nikkud, with option to ignore the nikkud/vowels to find > shoreshim/roots) feature. One window will be the compiled dictionary. > The second window will be any Hebrew text (Torah, Siddur, etc...). The > application will--hopefully--automatically search the "dictionary" based > upon the current cursor and add the English definition of the Hebrew > word with a click or two. (I'm learning Hebrew, as I go, studying every > week, if not every day.) This sounds very advanced for a first project (but then, so is a device driver!) Certainly probably beyond this lists scope. > ?) Obviously, a menu bar with tools and other standard GUI bits and > pieces. Yep, that kind of stuff we might help with. But again the GUI support forum is likely to be better still. > Actual Request: > > I'm running an older Debian Linux, that doesn't upgrade very well. Is > there anybody willing to help me at least get started or point me in the > right direction? We don't really provide 1-1 mentoring. You ask questions on the list and the list members answer. You might be very lucky and find someone who is familiar with your problem domain, but its a long shot. > Knowledge of Hebrew would be a *huge* plus, but isn't required in any > ... Thus, leafpad would be a reasonable model for the editor. Again thats a pretty specialized set of skills on top of Python. You might try the main Python mailing list/nesgroup. You have a bigger audience there to find someone suitable to help you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From marc.tompkins at gmail.com Mon Feb 2 21:59:05 2015 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 2 Feb 2015 12:59:05 -0800 Subject: [Tutor] GUI In-Reply-To: References: <54CE8987.3000708@comcast.net> Message-ID: On Mon, Feb 2, 2015 at 9:13 AM, Alan Gauld wrote: > Don't expect a whole heap of support from the GUIs. A lot of the work will > have to come from you. > I suspect the standard GUI framework Tkinter is not going to be your best > bet. You might find that PyQt or PyGTK will offer better multi lingual > support (although thats just a guess on my part!). > Might I also suggest wxPython? I tried Tk and Qt early on, but found that wx fit my needs much better (and I like the looks of the result better too.) I have little to no experience with LTR handling myself, but there's a very good, active support list for wxPython and I suspect that someone on that list may have insights that can help... wxpython-users at googlegroups.com From breamoreboy at yahoo.co.uk Mon Feb 2 22:18:21 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Feb 2015 21:18:21 +0000 Subject: [Tutor] GUI In-Reply-To: References: <54CE8987.3000708@comcast.net> Message-ID: On 02/02/2015 20:59, Marc Tompkins wrote: > On Mon, Feb 2, 2015 at 9:13 AM, Alan Gauld > wrote: > >> Don't expect a whole heap of support from the GUIs. A lot of the work will >> have to come from you. >> I suspect the standard GUI framework Tkinter is not going to be your best >> bet. You might find that PyQt or PyGTK will offer better multi lingual >> support (although thats just a guess on my part!). >> > > Might I also suggest wxPython? I tried Tk and Qt early on, but found that > wx fit my needs much better (and I like the looks of the result better too.) > I have little to no experience with LTR handling myself, but there's a very > good, active support list for wxPython and I suspect that someone on that > list may have insights that can help... > wxpython-users at googlegroups.com For the type of work the OP has previously described I doubt that wxPython fits the bill as the Python 3 version called Phoenix is still in development. More here http://wiki.wxpython.org/ProjectPhoenix -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From cs at zip.com.au Mon Feb 2 22:38:15 2015 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 3 Feb 2015 08:38:15 +1100 Subject: [Tutor] os module question In-Reply-To: References: Message-ID: <20150202213815.GA67848@cskk.homeip.net> On 02Feb2015 17:01, alan.gauld at btinternet.com wrote: >On 02/02/15 13:46, maurice.horan at thomsonreuters.com wrote: >>Basically I have trouble with two things: >>1) Get the server to take the hostname and use it to run a command against it > >os.uname() will return a tuple. >The second item is the hostname That gets this machine's hostname. The OP wants to use an arbitrary machine's hostname, since he's looking up an asset db. He needs to use the sys.argv array. (We he's doing as it turns out, so not to worry.) Cheers, Cameron Simpson I must really get a thinner pencil. I can't manage this one a bit. It writes all manner of things I don't intend. - rheney at csugrad.cs.vt.edu (Bolo Mk XXXIX) From marc.tompkins at gmail.com Mon Feb 2 22:48:47 2015 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 2 Feb 2015 13:48:47 -0800 Subject: [Tutor] GUI In-Reply-To: References: <54CE8987.3000708@comcast.net> Message-ID: On Mon, Feb 2, 2015 at 1:18 PM, Mark Lawrence wrote: > On 02/02/2015 20:59, Marc Tompkins wrote: > >> On Mon, Feb 2, 2015 at 9:13 AM, Alan Gauld >> wrote: >> >> Don't expect a whole heap of support from the GUIs. A lot of the work >>> will >>> have to come from you. >>> I suspect the standard GUI framework Tkinter is not going to be your best >>> bet. You might find that PyQt or PyGTK will offer better multi lingual >>> support (although thats just a guess on my part!). >>> >>> >> Might I also suggest wxPython? I tried Tk and Qt early on, but found that >> wx fit my needs much better (and I like the looks of the result better >> too.) >> I have little to no experience with LTR handling myself, but there's a >> very >> good, active support list for wxPython and I suspect that someone on that >> list may have insights that can help... >> wxpython-users at googlegroups.com >> > > For the type of work the OP has previously described I doubt that wxPython > fits the bill as the Python 3 version called Phoenix is still in > development. More here http://wiki.wxpython.org/ProjectPhoenix > Still under development, true - but all but a few of the controls are up and running, and a lot of the people on the list are using Phoenix now. (Not I - I'm still using 2.7 - but I've been following developments with interest.) From breamoreboy at yahoo.co.uk Mon Feb 2 23:10:43 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 02 Feb 2015 22:10:43 +0000 Subject: [Tutor] GUI In-Reply-To: References: <54CE8987.3000708@comcast.net> Message-ID: On 02/02/2015 21:48, Marc Tompkins wrote: > On Mon, Feb 2, 2015 at 1:18 PM, Mark Lawrence > wrote: > >> On 02/02/2015 20:59, Marc Tompkins wrote: >> >>> On Mon, Feb 2, 2015 at 9:13 AM, Alan Gauld >>> wrote: >>> >>> Don't expect a whole heap of support from the GUIs. A lot of the work >>>> will >>>> have to come from you. >>>> I suspect the standard GUI framework Tkinter is not going to be your best >>>> bet. You might find that PyQt or PyGTK will offer better multi lingual >>>> support (although thats just a guess on my part!). >>>> >>>> >>> Might I also suggest wxPython? I tried Tk and Qt early on, but found that >>> wx fit my needs much better (and I like the looks of the result better >>> too.) >>> I have little to no experience with LTR handling myself, but there's a >>> very >>> good, active support list for wxPython and I suspect that someone on that >>> list may have insights that can help... >>> wxpython-users at googlegroups.com >>> >> >> For the type of work the OP has previously described I doubt that wxPython >> fits the bill as the Python 3 version called Phoenix is still in >> development. More here http://wiki.wxpython.org/ProjectPhoenix >> > > Still under development, true - but all but a few of the controls are up > and running, and a lot of the people on the list are using Phoenix now. > (Not I - I'm still using 2.7 - but I've been following developments with > interest.) > So wxPython Phoenix 1.0 doesn't get released until all controls are up and running, which might be tomorrow, might be this time next year. I therefore could not recommend using it to someone who's trying to put a Hebrew Dictionary database together. Much better IMHO to use something that's already proven in the field. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at btinternet.com Tue Feb 3 00:15:54 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 02 Feb 2015 23:15:54 +0000 Subject: [Tutor] GUI In-Reply-To: References: <54CE8987.3000708@comcast.net> Message-ID: On 02/02/15 20:59, Marc Tompkins wrote: >> I suspect the standard GUI framework Tkinter is not going to be your best >> bet. You might find that PyQt or PyGTK will offer better multi lingual >> support (although thats just a guess on my part!). > > Might I also suggest wxPython? I tried Tk and Qt early on, but found that > wx fit my needs much better (and I like the looks of the result better too.) I, too, like wxPython, but I don't recall it having any explicit support for multi-lingual display whereas I think I've seen references to Qt and GTk supporting it via native widgets. That's why I left it out this time. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From bw_dw at fastmail.fm Mon Feb 2 19:42:19 2015 From: bw_dw at fastmail.fm (dw) Date: Mon, 02 Feb 2015 10:42:19 -0800 Subject: [Tutor] Wondering about a project Message-ID: <1422902539.2909453.222095713.2C79052C@webmail.messagingengine.com> Well I've made some progress in terminal mode. The OS is Ubuntu 12.04 LXDE desktop This script works. It prompts for the url, lets the user confirm download and then runs the video in Gnome-Player. Once Gnome-Player is dropped by the user, it prompts to either move the file to storage or delete. Then returns for another round. ----------------------------------------------- #!/usr/bin/python from subprocess import call import glob,re,shutil,os,time geturl="" while True: call(["clear"]) geturl= input("Enter Youtube URL ") if len(geturl)==0: break def unquote(geturl): return re.compile('%([0-9a-fA-F]{2})',re.M).sub(lambda m: chr(int(m.group(1),16)), geturl) print("Download %s?" %geturl) answer= raw_input("Press ENTER to continue: ") call(["youtube-dl", geturl]) #get the youtube video file names YTfile=glob.glob('./*.mp4') print("%s Youtube files: "%(YTfile)) #clean up the file names for x in range(len(YTfile)): YTfile[x] = YTfile[x][2:] print("%s: "+str(x)+" "+YTfile[x]+'\n') #now play the youtube video #for x in range(len(YTfile)): call(["gnome-mplayer", YTfile[0]]) #Decide to save the file or delete it dofile = raw_input('Save or Delete: S or D ') if dofile=='S': #save the file by moving it into folder for x in range(len(YTfile)): shutil.move(YTfile[x],'/home/user/Documents/YOUTUBEFILES') #delete the file else: os.remove(YTfile[0]) print("Deleted %s "%YTfile[0]) time.sleep( 3 ) -- Bw_dw at fastmail.net From alan.gauld at btinternet.com Tue Feb 3 13:12:42 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 03 Feb 2015 12:12:42 +0000 Subject: [Tutor] Wondering about a project In-Reply-To: <1422902539.2909453.222095713.2C79052C@webmail.messagingengine.com> References: <1422902539.2909453.222095713.2C79052C@webmail.messagingengine.com> Message-ID: On 02/02/15 18:42, dw wrote: > geturl="" You don't really need this since you assign it inside the loop. > while True: > call(["clear"]) > geturl= input("Enter Youtube URL ") > if len(geturl)==0: > break > > def unquote(geturl): > return re.compile('%([0-9a-fA-F]{2})',re.M).sub(lambda m: > chr(int(m.group(1),16)), geturl) Its not a good idea to define a functin inside a loop. Everytime the loop is executed you redefine the function all over again, which is a waste. Keep the function definitions out of your main code. > print("Download %s?" %geturl) > answer= raw_input("Press ENTER to continue: ") If you are using Python2.7 then you should also use raw_input above to get the url. > call(["youtube-dl", geturl]) > > #get the youtube video file names > YTfile=glob.glob('./*.mp4') > print("%s Youtube files: "%(YTfile)) > > #clean up the file names > for x in range(len(YTfile)): > YTfile[x] = YTfile[x][2:] > print("%s: "+str(x)+" "+YTfile[x]+'\n') this would be prettier using enumerate: for x, file in enumerate(YTFile): YTFile[x] = file[2:] print("%s:%d" % (file, x)) > #now play the youtube video > #for x in range(len(YTfile)): Again this would be prettier using normal python style for file in YTFile: > call(["gnome-mplayer", YTfile[0]]) > > #Decide to save the file or delete it > dofile = raw_input('Save or Delete: S or D ') > if dofile=='S': You will get annoyed always having to press shift key to get caps. You should check for one case after forcing conversion: if dofile.upper() == 'S': Although after writing a GUI that will be less of an issue because you'll be using a dialog to get the choice. > #save the file by moving it into folder > for x in range(len(YTfile)): > shutil.move(YTfile[x],'/home/user/Documents/YOUTUBEFILES') Again, don't use indexing, Let python do the work, its more reliable. for file in YTFile: shutil.move(file, 'your/path') > #delete the file > else: > os.remove(YTfile[0]) > print("Deleted %s "%YTfile[0]) > time.sleep( 3 ) Note that this else will delete the file even if the user presses 's' instead of 'S' unless you do the upper conversion I show above. It will also delete the file if the user happens to hit return before 's'... I'd recommend an explicit test for 'D' here. But again, not an issue in a GUI version. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From davea at davea.name Tue Feb 3 14:28:43 2015 From: davea at davea.name (Dave Angel) Date: Tue, 03 Feb 2015 08:28:43 -0500 Subject: [Tutor] Wondering about a project In-Reply-To: References: <1422902539.2909453.222095713.2C79052C@webmail.messagingengine.com> Message-ID: <54D0CD0B.105@davea.name> On 02/03/2015 07:12 AM, Alan Gauld wrote: > On 02/02/15 18:42, dw wrote: > You forgot to tell us the Python version you're targeting. From various clues in your code, I have to assume you're using 2.7, but if I'm wrong, there are other comments I should have made. >> geturl="" > > You don't really need this since you assign it inside the loop. > >> while True: >> call(["clear"]) >> geturl= input("Enter Youtube URL ") Need to use raw_input() for version 2.7. As it stands, you're requiring the user to enter quotes around his response, and taking the risk that if he doesn't, or if they're unmatched, he might be doing some unexpected things. >> if len(geturl)==0: >> break >> >> def unquote(geturl): >> return re.compile('%([0-9a-fA-F]{2})',re.M).sub(lambda m: >> chr(int(m.group(1),16)), geturl) > > Its not a good idea to define a functin inside a loop. > Everytime the loop is executed you redefine the function all over again, > which is a waste. Keep the function definitions out of > your main code. > >> print("Download %s?" %geturl) >> answer= raw_input("Press ENTER to continue: ") > > If you are using Python2.7 then you should also use > raw_input above to get the url. > >> call(["youtube-dl", geturl]) >> >> #get the youtube video file names >> YTfile=glob.glob('./*.mp4') >> print("%s Youtube files: "%(YTfile)) >> You need to decide here whether there might be more than one file to play and/or delete. If your design says there's just one file, then you should ensure that, perhaps by deleting the others before the loop below, or by printing an error message. I'll assume you're designing for the possibility of multiple files on that Youtube page. I don't know youtube-dl well enough to know if that's possible. >> #clean up the file names >> for x in range(len(YTfile)): >> YTfile[x] = YTfile[x][2:] >> print("%s: "+str(x)+" "+YTfile[x]+'\n') > > this would be prettier using enumerate: > > for x, file in enumerate(YTFile): > YTFile[x] = file[2:] > print("%s:%d" % (file, x)) > >> #now play the youtube video That's now "videos", plural. >> #for x in range(len(YTfile)): > > Again this would be prettier using normal python style > for file in YTFile: for myfile in YTFile: call(["gnome-mplayer", myfile) Besides which, if you had uncommented the range thing, you'd need to change the [0] below to [x]. Otherwise you'd be playing the first file multiple times. > >> call(["gnome-mplayer", YTfile[0]]) >> >> #Decide to save the file or delete it >> dofile = raw_input('Save or Delete: S or D ') >> if dofile=='S': Here again, your design has to decide whether it'll be all or nothing. I'll assume you'll be either saving them all, or deleting them all. > > You will get annoyed always having to press shift key to > get caps. You should check for one case after forcing > conversion: > > if dofile.upper() == 'S': > > > Although after writing a GUI that will be less of an > issue because you'll be using a dialog to get the choice. > >> #save the file by moving it into folder save the files by moving them into folder >> for x in range(len(YTfile)): >> shutil.move(YTfile[x],'/home/user/Documents/YOUTUBEFILES') > > Again, don't use indexing, Let python do the work, its more reliable. > > for file in YTFile: > shutil.move(file, 'your/path') > >> #delete the file >> else: >> os.remove(YTfile[0]) >> print("Deleted %s "%YTfile[0]) >> time.sleep( 3 ) You're only deleting the first one. Need a loop here as well. > > Note that this else will delete the file even if the user presses 's' > instead of 'S' unless you do the upper conversion I show above. > It will also delete the file if the user happens to hit return > before 's'... > I'd recommend an explicit test for 'D' here. > But again, not an issue in a GUI version. > > -- DaveA From mark.warren at usd258.net Tue Feb 3 16:22:07 2015 From: mark.warren at usd258.net (Mark Warren) Date: Tue, 3 Feb 2015 09:22:07 -0600 Subject: [Tutor] Macintosh Help with Python Message-ID: Can you help me through a phone number or chat on working with Python? -- Mark Warren Humboldt Unified School District # 258 801 New York Street Humboldt, Kansas 66748 Phone -- (620) 704-1527 From alan.gauld at btinternet.com Tue Feb 3 18:19:05 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 03 Feb 2015 17:19:05 +0000 Subject: [Tutor] Macintosh Help with Python In-Reply-To: References: Message-ID: On 03/02/15 15:22, Mark Warren wrote: > Can you help me through a phone number or chat on working with Python? > Sorry Mark, this is a mailing list. We can answer questions posted by email. If you tell us what it is you want to do somebody can describe the process for you. There are also a ton of videos on YouTube on using Python on different platforms. Here is one for MacOSX: https://www.youtube.com/watch?feature=player_detailpage&v=BE1wDsLzOJA But there are many others. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From jugurtha.hadjar at gmail.com Tue Feb 3 22:12:09 2015 From: jugurtha.hadjar at gmail.com (Jugurtha Hadjar) Date: Tue, 03 Feb 2015 22:12:09 +0100 Subject: [Tutor] Why is an instance smaller than the sum of its components? Message-ID: <54D139A9.70308@gmail.com> Hello, I was writing something and thought: Since the class had some 'constants', and multiple instances would be created, I assume that each instance would have its own data. So this would mean duplication of the same constants? If so, I thought why not put the constants in memory once, for every instance to access (to reduce memory usage). Correct me if I'm wrong in my assumptions (i.e: If instances share stuff). So I investigated further.. >>> import sys >>> sys.getsizeof(5) 12 So an integer on my machine is 12 bytes. Now: >>> class foo(object): ... def __init__(self): ... pass >>> sys.getsizeof(foo) 448 >>> sys.getsizeof(foo()) 28 >>> foo >>> foo() <__main__.foo object at 0xXXXXXXX - Second weird thing: >>> class bar(object): ... def __init__(self): ... self.w = 5 ... self.x = 6 ... self.y = 7 ... self.z = 8 >>> sys.getsizeof(bar) 448 >>> sys.getsizeof(foo) 448 >>> sys.getsizeof(bar()) 28 >>> sys.getsizeof(foo()) 28 >>> sys.getsizeof(bar().x) 12 >>> sys.getsizeof(bar().y) 12 Summary questions: 1 - Why are foo's and bar's class sizes the same? (foo's just a nop) 2 - Why are foo() and bar() the same size, even with bar()'s 4 integers? 3 - Why's bar()'s size smaller than the sum of the sizes of 4 integers? Thanks.. -- ~Jugurtha Hadjar, From dyoo at hashcollision.org Tue Feb 3 22:57:45 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 3 Feb 2015 13:57:45 -0800 Subject: [Tutor] Why is an instance smaller than the sum of its components? In-Reply-To: <54D139A9.70308@gmail.com> References: <54D139A9.70308@gmail.com> Message-ID: >>>> class bar(object): > ... def __init__(self): > ... self.w = 5 > ... self.x = 6 > ... self.y = 7 > ... self.z = 8 > >>>> sys.getsizeof(bar()) > 28 > 3 - Why's bar()'s size smaller than the sum of the sizes of 4 integers? But what is the documented behavior of sys.getsizeof? Reading... https://docs.python.org/3/library/sys.html#sys.getsizeof Ah. The following phrase in the documentation seems to apply directly to your question: "Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to." But the docs there also have a link to a recursive getsizeof() recipe that does what I think you intend. Take a look at that recipe. Good luck! From emile at fenx.com Tue Feb 3 22:59:27 2015 From: emile at fenx.com (Emile van Sebille) Date: Tue, 03 Feb 2015 13:59:27 -0800 Subject: [Tutor] Why is an instance smaller than the sum of its components? In-Reply-To: <54D139A9.70308@gmail.com> References: <54D139A9.70308@gmail.com> Message-ID: On 2/3/2015 1:12 PM, Jugurtha Hadjar wrote: > Hello, > > I was writing something and thought: Since the class had some > 'constants', and multiple instances would be created, I assume that each > instance would have its own data. So this would mean duplication of the > same constants? If so, I thought why not put the constants in memory > once, for every instance to access (to reduce memory usage). > > Correct me if I'm wrong in my assumptions (i.e: If instances share stuff). > > So I investigated further.. > > >>> import sys > >>> sys.getsizeof(5) > 12 > > > So an integer on my machine is 12 bytes. > > Now: > > >>> class foo(object): > ... def __init__(self): > ... pass > > >>> sys.getsizeof(foo) > 448 > > >>> sys.getsizeof(foo()) > 28 > > >>> foo > > >>> foo() > <__main__.foo object at 0xXXXXXXX > > > - Second weird thing: > > >>> class bar(object): > ... def __init__(self): > ... self.w = 5 > ... self.x = 6 > ... self.y = 7 > ... self.z = 8 > > >>> sys.getsizeof(bar) > 448 > >>> sys.getsizeof(foo) > 448 > >>> sys.getsizeof(bar()) > 28 > >>> sys.getsizeof(foo()) > 28 > > >>> sys.getsizeof(bar().x) > 12 > >>> sys.getsizeof(bar().y) > 12 > > > Summary questions: > > 1 - Why are foo's and bar's class sizes the same? (foo's just a nop) i'm not sure on this one. > 2 - Why are foo() and bar() the same size, even with bar()'s 4 integers? neither foo() nor bar() return anything explicitly, so both return the default none > 3 - Why's bar()'s size smaller than the sum of the sizes of 4 integers? same as above. From dyoo at hashcollision.org Tue Feb 3 23:25:54 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 3 Feb 2015 14:25:54 -0800 Subject: [Tutor] Why is an instance smaller than the sum of its components? In-Reply-To: References: <54D139A9.70308@gmail.com> Message-ID: >> >> Summary questions: >> >> 1 - Why are foo's and bar's class sizes the same? (foo's just a nop) > > > i'm not sure on this one. > >> 2 - Why are foo() and bar() the same size, even with bar()'s 4 integers? > > > neither foo() nor bar() return anything explicitly, so both return the > default none This needs correction. I think you're thinking of regular functions. But 'foo' and 'bar' are the names of the classes, so this is instance construction. To demonstrate the difference: ##################################### >>> class foo(object): pass ... >>> foo() <__main__.foo object at 0x7f27655c0fd0> ##################################### Compare what we see here to: ###################################### >>> def bar(): pass ... >>> bar() >>> ###################################### where the interactive evaluator is suppressing output of the None value. From zachary.ware+pytut at gmail.com Tue Feb 3 23:28:10 2015 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Tue, 3 Feb 2015 16:28:10 -0600 Subject: [Tutor] Why is an instance smaller than the sum of its components? In-Reply-To: References: <54D139A9.70308@gmail.com> Message-ID: On Tue, Feb 3, 2015 at 3:59 PM, Emile van Sebille wrote: > On 2/3/2015 1:12 PM, Jugurtha Hadjar wrote: >> 2 - Why are foo() and bar() the same size, even with bar()'s 4 integers? > > neither foo() nor bar() return anything explicitly, so both return the > default none This is not correct, foo() and bar() return a foo instance and a bar instance, respectively; not None. For the OP: while this will probably be a nice exercise for learning more about Python's internals, please keep in mind that 9 times out of 10 you won't need to worry about memory usage in Python, especially not before you've proven to yourself that your program is using more memory than is acceptable. -- Zach From __peter__ at web.de Tue Feb 3 23:40:03 2015 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Feb 2015 23:40:03 +0100 Subject: [Tutor] Why is an instance smaller than the sum of its components? References: <54D139A9.70308@gmail.com> Message-ID: Jugurtha Hadjar wrote: > Hello, > > I was writing something and thought: Since the class had some > 'constants', and multiple instances would be created, I assume that each > instance would have its own data. So this would mean duplication of the > same constants? If so, I thought why not put the constants in memory > once, for every instance to access (to reduce memory usage). CPython already does this for many common values, e. g. small integers and variable names >>> a = 42 >>> b = 42 >>> a is b True >>> a = 300 >>> b = 300 >>> a is b False It also performs constant folding over a single compilation: >>> a = 300; b = 300; a is b True > Correct me if I'm wrong in my assumptions (i.e: If instances share stuff). > > So I investigated further.. > > >>> import sys > >>> sys.getsizeof(5) > 12 > > > So an integer on my machine is 12 bytes. > > Now: > > >>> class foo(object): > ... def __init__(self): > ... pass > > >>> sys.getsizeof(foo) > 448 > > >>> sys.getsizeof(foo()) > 28 > > >>> foo > > >>> foo() > <__main__.foo object at 0xXXXXXXX To know its class the foo instance only needs a reference to the class object, not a complete copy of the class. This is typically provided by putting a pointer into the instance, and this consumes only 8 bytes on 64- bit systems. > - Second weird thing: > > >>> class bar(object): > ... def __init__(self): > ... self.w = 5 > ... self.x = 6 > ... self.y = 7 > ... self.z = 8 > > >>> sys.getsizeof(bar) > 448 > >>> sys.getsizeof(foo) > 448 > >>> sys.getsizeof(bar()) > 28 > >>> sys.getsizeof(foo()) > 28 > > >>> sys.getsizeof(bar().x) > 12 > >>> sys.getsizeof(bar().y) > 12 The instances of most user-defined classes use a dict to hold references to the attributes, and only the memory consumed by the pointer to that dict is reported. If all referenced values were included, what would you expect to be the size of `a` below >>> class A: pass ... >>> a = A() >>> a.a = a >>> sys.getsizeof(a) 56 > Summary questions: > > 1 - Why are foo's and bar's class sizes the same? (foo's just a nop) Assigning attributes in the initializer only affects the instance; Python doesn't scan the code to reserve slots for these attributes. When the instance is created the initialiser is executed and every self.x = value basically results in self.__dict__["x"] = value > 2 - Why are foo() and bar() the same size, even with bar()'s 4 integers? To get a more realistic idea of the objects' size you can include the size of __dict__. That grows in bursts: >>> class A: pass ... >>> a = A() >>> old_size = sys.getsizeof(a.__dict__) >>> for i in range(1000): ... setattr(a, "x" + str(i), i) ... new_size = sys.getsizeof(a.__dict__) ... if new_size != old_size: ... print(i, "a.__dict__ grows from", old_size, "to", new_size) ... old_size = new_size ... 3 a.__dict__ grows from 96 to 192 11 a.__dict__ grows from 192 to 320 21 a.__dict__ grows from 320 to 576 43 a.__dict__ grows from 576 to 1088 85 a.__dict__ grows from 1088 to 2112 171 a.__dict__ grows from 2112 to 4160 341 a.__dict__ grows from 4160 to 8256 683 a.__dict__ grows from 8256 to 16448 > 3 - Why's bar()'s size smaller than the sum of the sizes of 4 integers? >From the above follows that this is not a meaningful question for a standard user-defined class. They all use __dict__ to store the interesting stuff. But there is a way to reserve space for attributes in the instance: >>> class A: ... __slots__ = () ... >>> class B: ... __slots__ = ("a",) ... >>> class C: ... __slots__ = ("a", "b") ... >>> class D: ... __slots__ = tuple("a" + str(i) for i in range(100)) ... >>> for K in A, B, C, D: ... print(K.__name__, sys.getsizeof(K())) ... A 16 B 48 C 56 D 840 >>> b = B() >>> sys.getsizeof(b) 48 >>> b.a = 42 >>> sys.getsizeof(b) 48 >>> (840-48)/99 8.0 And that looks very much like one 64-bit pointer per attribute. From jugurtha.hadjar at gmail.com Tue Feb 3 23:40:33 2015 From: jugurtha.hadjar at gmail.com (Jugurtha Hadjar) Date: Tue, 03 Feb 2015 23:40:33 +0100 Subject: [Tutor] Why is an instance smaller than the sum of its components? In-Reply-To: References: <54D139A9.70308@gmail.com> Message-ID: <54D14E61.8040004@gmail.com> On 02/03/2015 10:57 PM, Danny Yoo wrote: > But what is the documented behavior of sys.getsizeof? > > Reading... > > https://docs.python.org/3/library/sys.html#sys.getsizeof > Ah ! I was reading this: https://docs.python.org/2/library/sys.html#sys.getsizeof The unlocking phrase: > "Only the memory consumption directly attributed to the object is > accounted for, not the memory consumption of objects it refers to." > seems to be present in the Python 3 doc, but not in Python 2's. I'll make sure to include the version in my future questions. > But the docs there also have a link to a recursive getsizeof() recipe > that does what I think you intend. Take a look at that recipe. > > > Good luck! > Yeap, I see that. Thanks for your time! -- ~Jugurtha Hadjar, From jugurtha.hadjar at gmail.com Tue Feb 3 23:52:17 2015 From: jugurtha.hadjar at gmail.com (Jugurtha Hadjar) Date: Tue, 03 Feb 2015 23:52:17 +0100 Subject: [Tutor] Why is an instance smaller than the sum of its components? In-Reply-To: References: <54D139A9.70308@gmail.com> Message-ID: <54D15121.6050001@gmail.com> On 02/03/2015 11:28 PM, Zachary Ware wrote: > > For the OP: while this will probably be a nice exercise for learning > more about Python's internals, please keep in mind that 9 times out of > 10 you won't need to worry about memory usage in Python, especially > not before you've proven to yourself that your program is using more > memory than is acceptable. > Thanks for the pointer, I was scratching the itch on my way to do something else... But this stuff is fascinating and hard to resist! -- ~Jugurtha Hadjar, From steve at pearwood.info Wed Feb 4 00:18:16 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 4 Feb 2015 10:18:16 +1100 Subject: [Tutor] Why is an instance smaller than the sum of its components? In-Reply-To: <54D139A9.70308@gmail.com> References: <54D139A9.70308@gmail.com> Message-ID: <20150203231816.GV2498@ando.pearwood.info> On Tue, Feb 03, 2015 at 10:12:09PM +0100, Jugurtha Hadjar wrote: > Hello, > > I was writing something and thought: Since the class had some > 'constants', and multiple instances would be created, I assume that each > instance would have its own data. So this would mean duplication of the > same constants? Not necessarily. Consider: class A(object): spam = 23 def __init__(self): self.eggs = 42 In this case, the "spam" attribute is on the class, not the instance, and so it doesn't matter how many A instances you have, there is only one reference to 23 and a single copy of 23. The "eggs" attribute is on the instance. That means that each instance has its own separate reference to 42. Does that mean a separate copy of 42? Maybe, maybe not. In general, yes: if eggs was a mutable object like a list, or a dict, say: self.eggs = [] then naturally it would need to be a separate list for each instance. (If you wanted a single list shared between all instances, put it on the class.) But with immutable objects like ints, strings and floats, there is an optimization available to the Python compiler: it could reuse the same object. There would be a separate reference to that object per instance, but only one copy of the object itself. Think of references as being rather like C pointers. References are cheap, while objects themselves could be arbitrarily large. With current versions of Python, the compiler will intern and re-use small integers and strings which look like identifiers ("alpha" is an identifier, "hello world!" is not). But that is subject to change: it is not a language promise, it is an implementation optimization. However, starting with (I think) Python 3.4 or 3.5, Python will optimize even more! Instances will share dictionaries, which will save even more memory. Each instance has a dict, which points to a hash table of (key, value) records: __dict__ ----> [ UNUSED UNUSED (ptr to key, ptr to value) UNUSED ... ] __dict__ ----> [ UNUSED UNUSED (ptr to key, ptr to value) UNUSED ... ] For most classes, the instances a and b will have the same set of keys, even though the values will be different. That means the pointers to keys are all the same. So the new implementation of dict will optimize that case to save memory and speed up dictionary access. > If so, I thought why not put the constants in memory > once, for every instance to access (to reduce memory usage). > > Correct me if I'm wrong in my assumptions (i.e: If instances share stuff). In general, Python will share stuff if it can, although maybe not *everything* it can. > So I investigated further.. > > >>> import sys > >>> sys.getsizeof(5) > 12 > > > So an integer on my machine is 12 bytes. A *small* integer is 12 bytes. A large integer can be more: py> sys.getsizeof(2**100) 26 py> sys.getsizeof(2**10000) 1346 py> sys.getsizeof(2**10000000) 1333346 > Now: > > >>> class foo(object): > ... def __init__(self): > ... pass > > >>> sys.getsizeof(foo) > 448 > > >>> sys.getsizeof(foo()) > 28 > > >>> foo > > >>> foo() > <__main__.foo object at 0xXXXXXXX The *class* Foo is a fairly large object. It has space for a name, a dictionary of methods and attributes, a tuple of base classes, a table of weak references, a docstring, and more: py> class Foo(object): ... pass ... py> dir(Foo) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__'] py> vars(Foo) mappingproxy({'__qualname__': 'Foo', '__module__': '__main__', '__doc__': None, '__weakref__': , '__dict__': }) py> Foo.__base__ py> Foo.__bases__ (,) The instance may be quite small, but of course that depends on how many attributes it has. Typically, all the methods live in the class, and are shared, while data attributes are per-instance. > - Second weird thing: > > >>> class bar(object): > ... def __init__(self): > ... self.w = 5 > ... self.x = 6 > ... self.y = 7 > ... self.z = 8 > > >>> sys.getsizeof(bar) > 448 > >>> sys.getsizeof(foo) > 448 Nothing weird here. Both your Foo and Bar classes contain the same attributes. The only difference is that Foo.__init__ method does nothing, while Bar.__init__ has some code in it. If you call sys.getsizeof(foo.__init__.__code__) and compare it to the same for bar, you should see a difference. > >>> sys.getsizeof(bar()) > 28 > >>> sys.getsizeof(foo()) > 28 In this case, the Foo and Bar instances both have the same size. They both have a __dict__, and the Foo instance's __dict__ is empty, while the Bar instance's __dict__ has 4 items. Print: print(foo().__dict__) print(bar().__dict__) to see the difference. But with only 4 items, Bar's items will fit in the default sized hash table. No resize will be triggered and the sizes are the same. Run this little snippet of code to see what happens: d = {} for c in "abcdefghijklm": print(len(d), sys.getsizeof(d)) d[c] = None > Summary questions: > > 1 - Why are foo's and bar's class sizes the same? (foo's just a nop) Foo is a class, it certainly isn't a NOP. Just because you haven't given it state or behaviour doesn't mean it doesn't have any. It has the default state and behaviour that all classes start off with. > 2 - Why are foo() and bar() the same size, even with bar()'s 4 integers? Because hash tables (dicts) contain empty slots. Once the hash table reaches 50% full, a resize is triggered. > 3 - Why's bar()'s size smaller than the sum of the sizes of 4 integers? Because sys.getsizeof tells you the size of the object, not the objects referred to by the object. Here is a recipe for a recursive getsizeof: http://code.activestate.com/recipes/577504 -- Steve From davea at davea.name Wed Feb 4 00:21:13 2015 From: davea at davea.name (Dave Angel) Date: Tue, 03 Feb 2015 18:21:13 -0500 Subject: [Tutor] Why is an instance smaller than the sum of its components? In-Reply-To: <54D139A9.70308@gmail.com> References: <54D139A9.70308@gmail.com> Message-ID: <54D157E9.8010307@davea.name> On 02/03/2015 04:12 PM, Jugurtha Hadjar wrote: > Hello, > Lots of other good comments, so I'll just remark on one point. > > >>> class bar(object): > ... def __init__(self): > ... self.w = 5 > ... self.x = 6 > ... self.y = 7 > ... self.z = 8 > If these really are "constants," meaning the same value for all instances, then you can make them class attributes instead of instance attributes. I'd advise doing this to avoid bugs, not to save memory, though if you have lots of instances, it'll certainly save memory. >>> class bar(object): ... w = 5 ... x = 6 ... def __init__(self): ... self.y = 7 ... self.z = 8 At this point, all instances will have a self.w of 5, and a self.x of 6. But they'll each have a self.y and self.z which could change independently. -- DaveA From bw_dw at fastmail.fm Tue Feb 3 23:46:15 2015 From: bw_dw at fastmail.fm (dw) Date: Tue, 03 Feb 2015 14:46:15 -0800 Subject: [Tutor] Wondering about a project Message-ID: <1423003575.3446625.222733485.14A898AB@webmail.messagingengine.com> Thanks Alan for the tips!!! I greatly appreciate. :-D Duane -- Bw_dw at fastmail.net From bw_dw at fastmail.fm Tue Feb 3 23:48:51 2015 From: bw_dw at fastmail.fm (dw) Date: Tue, 03 Feb 2015 14:48:51 -0800 Subject: [Tutor] Wondering about a project Message-ID: <1423003731.3446831.222734369.58547CF4@webmail.messagingengine.com> Thanks Dave A for your Tips!! I greatly appreciate. :-D Duane -- Bw_dw at fastmail.net From suresh852456 at gmail.com Tue Feb 3 23:51:31 2015 From: suresh852456 at gmail.com (Suresh Nagulavancha) Date: Wed, 4 Feb 2015 04:21:31 +0530 Subject: [Tutor] How can I replicate a list in a for loop Message-ID: <54d150f9.4841440a.5d7f.ffff8eb1@mx.google.com> This is my sample piece of code (not full code of my original code just sample of it) I am using python 2.7 Import itertools var=[1,2,3,4,5] Length=int(raw_input("length of possible numbers required")) #This is for length of 3 chars for i in itertools.product(var,var,var): print i[0]+i[1]+i[2] Here what is my problem is i am unable to replicate the list based on the user input i tried var*length but it is creating a new single list with repeated values , how can i solve this problem?? I want the same original list to be used Thanks in advance From jugurtha.hadjar at gmail.com Wed Feb 4 00:42:11 2015 From: jugurtha.hadjar at gmail.com (Jugurtha Hadjar) Date: Wed, 04 Feb 2015 00:42:11 +0100 Subject: [Tutor] Why is an instance smaller than the sum of its components? In-Reply-To: References: <54D139A9.70308@gmail.com> Message-ID: <54D15CD3.30506@gmail.com> On 02/03/2015 11:40 PM, Peter Otten wrote: > CPython already does this for many common values, e. g. small integers and > variable names > > >>>> a = 42 >>>> b = 42 >>>> a is b > True >>>> a = 300 >>>> b = 300 >>>> a is b > False > The threshold seems to be 256 (last value where it evaluates to True): >>> a = 1 >>> b = 1 >>> same = True >>> while same: ... a += 1 ... b += 1 ... same = a is b ... >>> a 257 >>> b 257 Interesting that it does that, and interesting that it doesn't work for floats. > To know its class the foo instance only needs a reference to the class > object, not a complete copy of the class. This is typically provided by > putting a pointer into the instance, and this consumes only 8 bytes on 64- > bit systems. Okay, I thought the way it was done was that each instance was a full, independent, citizen/entity; with everything copied as many times as there are instances, which somehow bothered me memory wise, but had an appeal of having them completely separated. >... Rest of the post is partially grasped and requires further reading to fully appreciate. Thank you very much for taking the time and for the example code. -- ~Jugurtha Hadjar, From breamoreboy at yahoo.co.uk Wed Feb 4 00:53:17 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 03 Feb 2015 23:53:17 +0000 Subject: [Tutor] How can I replicate a list in a for loop In-Reply-To: <54d150f9.4841440a.5d7f.ffff8eb1@mx.google.com> References: <54d150f9.4841440a.5d7f.ffff8eb1@mx.google.com> Message-ID: On 03/02/2015 22:51, Suresh Nagulavancha wrote: > This is my sample piece of code (not full code of my original code just sample of it) > I am using python 2.7 > Import itertools > var=[1,2,3,4,5] > Length=int(raw_input("length of possible numbers required")) > #This is for length of 3 chars > for i in itertools.product(var,var,var): > print i[0]+i[1]+i[2] > > Here what is my problem is i am unable to replicate the list based on the user input i tried var*length but it is creating a new single list with repeated values , how can i solve this problem?? I want the same original list to be used > > Thanks in advance If you are trying to get the first n items from the list all you need is the slice notation:- chunk = var[:Length] If not can you please rephrase your question as it makes no sense to me. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From jugurtha.hadjar at gmail.com Wed Feb 4 02:51:18 2015 From: jugurtha.hadjar at gmail.com (Jugurtha Hadjar) Date: Wed, 04 Feb 2015 02:51:18 +0100 Subject: [Tutor] Why is an instance smaller than the sum of its components? In-Reply-To: <20150203231816.GV2498@ando.pearwood.info> References: <54D139A9.70308@gmail.com> <20150203231816.GV2498@ando.pearwood.info> Message-ID: <54D17B16.6090004@gmail.com> On 02/04/2015 12:18 AM, Steven D'Aprano wrote: > > Not necessarily. Consider: > > class A(object): > spam = 23 > def __init__(self): > self.eggs = 42 > > In this case, the "spam" attribute is on the class, not the instance, > and so it doesn't matter how many A instances you have, there is only > one reference to 23 and a single copy of 23. > > The "eggs" attribute is on the instance. That means that each instance > has its own separate reference to 42. > Hmm.. Here are the first few lines of my class: class Sender(object): """ Redacted """ SENDER_DB = 'sender.db' def __init__(self, phone, balance=0.0): self.phone = phone self.balance = balance I gave the (bad) examples that way because I thought what mattered is how much data was inside. I put SENDER_DB there because it made sense to put constants way on top, not because I had any idea it'd make the difference you mentioned (class attributes vs instance attributes). And also because it's a common piece of data to all the methods...(because after I started with each method opening and closing the database, I eliminated the code and made a method that returns a connection and a cursor, and the others just call it when they need to do stuff on the database. I'll ask another question later on how to refine it) But now that you, Dave, and Peter pointed this out, I'm thinking of putting the methods' constants up there (mainly patterns for regular expressions, and queries (SQL)). > Does that mean a separate copy of 42? Maybe, maybe not. In general, yes: > if eggs was a mutable object like a list, or a dict, say: > > self.eggs = [] > > then naturally it would need to be a separate list for each instance. > (If you wanted a single list shared between all instances, put it on the > class.) But with immutable objects like ints, strings and floats, there > is an optimization available to the Python compiler: it could reuse the > same object. There would be a separate reference to that object per > instance, but only one copy of the object itself. Okay.. I think that even if Python does optimize that, this belongs to the "good practice" category, so it's better that I'm the one who does it instead of relying on what the compiler might do. I'm a beginner(that's the first thing I write that does something useful) and would like to reinforce good habits. > Think of references as being rather like C pointers. References are > cheap, while objects themselves could be arbitrarily large. > That's the analogy I made, but I'm careful with those. I don't want to end up like the "English As She Is Spoke" book.. > With current versions of Python, the compiler will intern and re-use > small integers and strings which look like identifiers ("alpha" is an > identifier, "hello world!" is not). > ... > In general, Python will share stuff if it can, although maybe not > *everything* it can. That's interesting. I'll try to read up on this without being sidetracked. > In this case, the Foo and Bar instances both have the same size. They > both have a __dict__, and the Foo instance's __dict__ is empty, while > the Bar instance's __dict__ has 4 items. Print: > > print(foo().__dict__) > print(bar().__dict__) > > to see the difference. But with only 4 items, Bar's items will fit in > the default sized hash table. No resize will be triggered and the sizes > are the same. I thought that there was a default size allocated even for an "empty" class (which is correct), and then if I added w, x, y, z, their size would be *added* to the default size (which is incorrect).. Somehow, I didn't think of the analogy of 8dec being (1000b) (4 bits) and incrementing, it's still 4 bits through 15dec (1111b). So that's: default class size + data = default class size until it "overflows". (or until 50% of default class size is reached as you mentioned later). > Run this little snippet of code to see what happens: > d = {} > for c in "abcdefghijklm": > print(len(d), sys.getsizeof(d)) > d[c] = None For memo: (0, 136) (1, 136) (2, 136) (3, 136) (4, 136) (5, 136) (6, 520) (7, 520) (8, 520) (9, 520) (10, 520) (11, 520) (12, 520) >> Summary questions: >> >> 1 - Why are foo's and bar's class sizes the same? (foo's just a nop) > > Foo is a class, it certainly isn't a NOP. Just because you haven't given > it state or behaviour doesn't mean it doesn't have any. It has the > default state and behaviour that all classes start off with. > >> 2 - Why are foo() and bar() the same size, even with bar()'s 4 integers? > > Because hash tables (dicts) contain empty slots. Once the hash table > reaches 50% full, a resize is triggered. > >> 3 - Why's bar()'s size smaller than the sum of the sizes of 4 integers? > > Because sys.getsizeof tells you the size of the object, not the objects > referred to by the object. Here is a recipe for a recursive getsizeof: > > http://code.activestate.com/recipes/577504 > > This is cool. Thanks a lot (and Dave, too) for the great explanations.. I'll post some code about the database stuff in a new thread. -- ~Jugurtha Hadjar, From jugurtha.hadjar at gmail.com Wed Feb 4 03:01:46 2015 From: jugurtha.hadjar at gmail.com (Jugurtha Hadjar) Date: Wed, 04 Feb 2015 03:01:46 +0100 Subject: [Tutor] Why is an instance smaller than the sum of its components? In-Reply-To: <20150203231816.GV2498@ando.pearwood.info> References: <54D139A9.70308@gmail.com> <20150203231816.GV2498@ando.pearwood.info> Message-ID: <54D17D8A.5050500@gmail.com> Sorry for the full lines. They were wrapped here but were sent unfolded. It seems I need to "rewrap" on Thunderbird. -- ~Jugurtha Hadjar, From alan.gauld at btinternet.com Wed Feb 4 09:03:52 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 04 Feb 2015 08:03:52 +0000 Subject: [Tutor] How can I replicate a list in a for loop In-Reply-To: <54d150f9.4841440a.5d7f.ffff8eb1@mx.google.com> References: <54d150f9.4841440a.5d7f.ffff8eb1@mx.google.com> Message-ID: On 03/02/15 22:51, Suresh Nagulavancha wrote: > This is my sample piece of code (not full code of my original code just sample of it) > I am using python 2.7 > Import itertools > var=[1,2,3,4,5] > Length=int(raw_input("length of possible numbers required")) > #This is for length of 3 chars > for i in itertools.product(var,var,var): > print i[0]+i[1]+i[2] > > > Here what is my problem is i am unable to replicate the list based > on the user input i tried var*length but it is creating a new > single list with repeated values , how can i solve this problem?? > I want the same original list to be used Sorry, I couldn't follow that. Can you provide some sample data, some inputs and some outputs to show what you expected and what you got? tia -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From pugachov.andrey at gmail.com Wed Feb 4 10:01:54 2015 From: pugachov.andrey at gmail.com (=?UTF-8?B?0JDQvdC00YDQtdC5INCf0YPQs9Cw0YfQtdCy?=) Date: Wed, 4 Feb 2015 11:01:54 +0200 Subject: [Tutor] Need help with find error Message-ID: Hi I'm learning python a few weeks and have problems with code that read text from txt-file Code doing all right, but in the end I have error Traceback (most recent call last): File "trivia_challenge.py", line 81, in main() File "trivia_challenge.py", line 74, in main category, question, answers, correct, explanation, points = next_block(trivia_file) File "trivia_challenge.py", line 37, in next_block points = int(next_line(the_file)) ValueError: invalid literal for int() with base 10: '' I see it don't like empty line, but line is not emty... py-file http://pastebin.com/9C4guZq5 txt-file http://pastebin.com/dZVs8V9P From siya360 at gmail.com Wed Feb 4 09:40:49 2015 From: siya360 at gmail.com (Siya 360) Date: Wed, 4 Feb 2015 10:40:49 +0200 Subject: [Tutor] Unable to install django in visual studio References: Message-ID: <2CB32873-B736-4A37-B119-00E21BBB206A@gmail.com> Hi, Please assist with resolving this problem as am sitting behind a proxy, and I understand I have to use python get -pip.py --proxy="[user:passwd@]proxy.server:port" To install behind a proxy > > > > > This electronic communication and the attached file(s) are subject to a disclaimer which can be viewed at http://www.multichoice.co.za/multichoice/content/en/email-disclaimer. If you are unable to view the disclaimer, please email disclaimer at multichoice.co.za for a copy. > > From suresh852456 at gmail.com Wed Feb 4 10:46:51 2015 From: suresh852456 at gmail.com (Suresh Kumar) Date: Wed, 4 Feb 2015 15:16:51 +0530 Subject: [Tutor] How can I replicate a list in a for loop In-Reply-To: References: <54d150f9.4841440a.5d7f.ffff8eb1@mx.google.com> Message-ID: here is the sample code >>> import itertools >>> import string >>> var=[] >>> for i in string.ascii_lowercase[0:5]: var.append(i) >>>print var ['a', 'b', 'c', 'd', 'e'] >>> length=int(raw_input("enter the length of random letters you need ")) enter the length of random letters you need 2 the user gave two so code should be like this >>>for i in itertools.product(var,var): print i[0]+i[1] output of code should be like this aa ab ac ad ae ba bb bc bd be ca cb cc cd ce da db dc dd de ea eb ec ed ee based on the user given input of length i need to add var in for loop if 3 given >>>for i in itertools.product(var,var,var): print i[0]+i[1]+i[2] if 4 given >>>for i in itertools.product(var,var,var,var): print i[0]+i[1]+i[2]+i[3] like this i need to get i tried var*length >>>print var ['a', 'b', 'c', 'd', 'e'] >>> var*length ['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e'] if i use the same in for loop >>>for i in itertools.product(var*2): print i[0]+i[1] Traceback (most recent call last): File "", line 2, in print i[0]+i[1] IndexError: tuple index out of range so i need to use many if blocks based on user input which makes my code very lengthy thanks in advance On Wed, Feb 4, 2015 at 1:33 PM, Alan Gauld wrote: > On 03/02/15 22:51, Suresh Nagulavancha wrote: > >> This is my sample piece of code (not full code of my original code just >> sample of it) >> I am using python 2.7 >> Import itertools >> var=[1,2,3,4,5] >> Length=int(raw_input("length of possible numbers required")) >> #This is for length of 3 chars >> for i in itertools.product(var,var,var): >> print i[0]+i[1]+i[2] >> >> >> Here what is my problem is i am unable to replicate the list based >> > > on the user input i tried var*length but it is creating a new > > single list with repeated values , how can i solve this problem?? > > I want the same original list to be used > > Sorry, I couldn't follow that. Can you provide some sample data, > some inputs and some outputs to show what you expected and what > you got? > > tia > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Wed Feb 4 13:23:45 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 04 Feb 2015 12:23:45 +0000 Subject: [Tutor] Need help with find error In-Reply-To: References: Message-ID: On 04/02/15 09:01, ?????? ??????? wrote: > Code doing all right, but in the end I have error > > Traceback (most recent call last): > File "trivia_challenge.py", line 81, in > main() > File "trivia_challenge.py", line 74, in main > category, question, answers, correct, explanation, points = > next_block(trivia_file) > File "trivia_challenge.py", line 37, in next_block > points = int(next_line(the_file)) > ValueError: invalid literal for int() with base 10: '' > > I see it don't like empty line, but line is not emty... > OK, But what is it? Does it contain any spaces or letters or punctuation characters? Try separating out the line and then adding a try/except like so: try: line = next_line(the_file) points = int(line) except ValueError: print "Line causing error is: \n;", repr(line) raise That way you will see exactly what causes the exception. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Feb 4 13:25:29 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 04 Feb 2015 12:25:29 +0000 Subject: [Tutor] Unable to install django in visual studio In-Reply-To: <2CB32873-B736-4A37-B119-00E21BBB206A@gmail.com> References: <2CB32873-B736-4A37-B119-00E21BBB206A@gmail.com> Message-ID: On 04/02/15 08:40, Siya 360 wrote: > Please assist with resolving this problem as am sitting behind a proxy, and I understand I have to use > > python get -pip.py --proxy="[user:passwd@]proxy.server:port" > > To install behind a proxy This group is for folks learning Python and its standard library. For non standard libraries like Django you are better asking on their support forum. Especially in this case, since it's an install question related to a very specific platform. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Wed Feb 4 13:32:06 2015 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 Feb 2015 13:32:06 +0100 Subject: [Tutor] Need help with find error References: Message-ID: ?????? ??????? wrote: > Hi > I'm learning python a few weeks and have problems with code that read text > from txt-file > Code doing all right, but in the end I have error > > Traceback (most recent call last): > File "trivia_challenge.py", line 81, in > main() > File "trivia_challenge.py", line 74, in main > category, question, answers, correct, explanation, points = > next_block(trivia_file) > File "trivia_challenge.py", line 37, in next_block > points = int(next_line(the_file)) > ValueError: invalid literal for int() with base 10: '' > > I see it don't like empty line, but line is not emty... > > py-file http://pastebin.com/9C4guZq5 > > txt-file http://pastebin.com/dZVs8V9P Put some debugging code into your script that keeps track of the line you are reading. For that you can modify the next_line() routine: current_line = 0 def next_line(the_file): """Return next line from the trivia file, formatted.""" global current_line line = the_file.readline() print("XXX CURRENT LINE", current_line, repr(line)) current_line += 1 line = line.replace("/", "\n") return line Then, when you run the script again, there will be a line XXX CURRENT LINE 451 'yabba dabba doo\n' printed right before the exception is triggered. Once you know the line (hint: it's not actually a line in the file) the problem should be easy to fix. (Come back here to ask for more hints if you cannot fix it.) From alan.gauld at btinternet.com Wed Feb 4 13:38:18 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 04 Feb 2015 12:38:18 +0000 Subject: [Tutor] How can I replicate a list in a for loop In-Reply-To: References: <54d150f9.4841440a.5d7f.ffff8eb1@mx.google.com> Message-ID: On 04/02/15 09:46, Suresh Kumar wrote: >>>> print var > ['a', 'b', 'c', 'd', 'e'] > the user gave two so code should be like this >>>> for i in itertools.product(var,var): > print i[0]+i[1] > output of code should be like this > aa > ab ... > ee > based on the user given input of length i need to add var in for loop > if 3 given >>>> for i in itertools.product(var,var,var): > print i[0]+i[1]+i[2] OK, So the question is how to pass n copies of var to product()? You could do it by enclosing var in an outer list or tuple, then unpacking the result in the call to product(): Untested... for i in itertools.product(*((var,) * n)): print ''.join(i) Does that work? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From raulcumplido at gmail.com Wed Feb 4 13:54:37 2015 From: raulcumplido at gmail.com (=?UTF-8?Q?Ra=C3=BAl_Cumplido?=) Date: Wed, 4 Feb 2015 12:54:37 +0000 Subject: [Tutor] How can I replicate a list in a for loop In-Reply-To: References: <54d150f9.4841440a.5d7f.ffff8eb1@mx.google.com> Message-ID: I think you want to use combinations_with_replacement: >>> var = ['a', 'b', 'c', 'd', 'e'] >>> length=int(raw_input("enter the length of random letters you need ")) enter the length of random letters you need 2 >>> length 2 >>> from itertools import combinations_with_replacement >>> [''.join(s) for s in combinations_with_replacement(var, 2)] ['aa', 'ab', 'ac', 'ad', 'ae', 'bb', 'bc', 'bd', 'be', 'cc', 'cd', 'ce', 'dd', 'de', 'ee'] On Wed, Feb 4, 2015 at 12:38 PM, Alan Gauld wrote: > On 04/02/15 09:46, Suresh Kumar wrote: > > print var >>>>> >>>> ['a', 'b', 'c', 'd', 'e'] >> > > the user gave two so code should be like this >> >>> for i in itertools.product(var,var): >>>>> >>>> print i[0]+i[1] >> > > output of code should be like this >> aa >> ab >> > ... > >> ee >> > > based on the user given input of length i need to add var in for loop >> if 3 given >> >>> for i in itertools.product(var,var,var): >>>>> >>>> print i[0]+i[1]+i[2] >> > > OK, So the question is how to pass n copies of var to product()? > > You could do it by enclosing var in an outer list or tuple, then unpacking > the result in the call to product(): > > Untested... > > for i in itertools.product(*((var,) * n)): > print ''.join(i) > > Does that work? > > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From raulcumplido at gmail.com Wed Feb 4 14:01:11 2015 From: raulcumplido at gmail.com (=?UTF-8?Q?Ra=C3=BAl_Cumplido?=) Date: Wed, 4 Feb 2015 13:01:11 +0000 Subject: [Tutor] How can I replicate a list in a for loop In-Reply-To: References: <54d150f9.4841440a.5d7f.ffff8eb1@mx.google.com> Message-ID: sorry, just me being stupid :P should have read closely what the problem was On Wed, Feb 4, 2015 at 12:54 PM, Ra?l Cumplido wrote: > I think you want to use combinations_with_replacement: > > >>> var = ['a', 'b', 'c', 'd', 'e'] > > >>> length=int(raw_input("enter the length of random letters you need ")) > enter the length of random letters you need 2 > > >>> length > 2 > > >>> from itertools import combinations_with_replacement > > >>> [''.join(s) for s in combinations_with_replacement(var, 2)] > ['aa', > 'ab', > 'ac', > 'ad', > 'ae', > 'bb', > 'bc', > 'bd', > 'be', > 'cc', > 'cd', > 'ce', > 'dd', > 'de', > 'ee'] > > On Wed, Feb 4, 2015 at 12:38 PM, Alan Gauld > wrote: > >> On 04/02/15 09:46, Suresh Kumar wrote: >> >> print var >>>>>> >>>>> ['a', 'b', 'c', 'd', 'e'] >>> >> >> the user gave two so code should be like this >>> >>>> for i in itertools.product(var,var): >>>>>> >>>>> print i[0]+i[1] >>> >> >> output of code should be like this >>> aa >>> ab >>> >> ... >> >>> ee >>> >> >> based on the user given input of length i need to add var in for loop >>> if 3 given >>> >>>> for i in itertools.product(var,var,var): >>>>>> >>>>> print i[0]+i[1]+i[2] >>> >> >> OK, So the question is how to pass n copies of var to product()? >> >> You could do it by enclosing var in an outer list or tuple, then >> unpacking the result in the call to product(): >> >> Untested... >> >> for i in itertools.product(*((var,) * n)): >> print ''.join(i) >> >> Does that work? >> >> >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> http://www.amazon.com/author/alan_gauld >> Follow my photo-blog on Flickr at: >> http://www.flickr.com/photos/alangauldphotos >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > From raulcumplido at gmail.com Wed Feb 4 14:06:11 2015 From: raulcumplido at gmail.com (=?UTF-8?Q?Ra=C3=BAl_Cumplido?=) Date: Wed, 4 Feb 2015 13:06:11 +0000 Subject: [Tutor] How can I replicate a list in a for loop In-Reply-To: References: <54d150f9.4841440a.5d7f.ffff8eb1@mx.google.com> Message-ID: There is a repeat argument on the product function that is used exactly for what you want to do: >>> for s in product(var, repeat=2) print ''.join(s) On Wed, Feb 4, 2015 at 1:01 PM, Ra?l Cumplido wrote: > sorry, just me being stupid :P should have read closely what the problem > was > > On Wed, Feb 4, 2015 at 12:54 PM, Ra?l Cumplido > wrote: > >> I think you want to use combinations_with_replacement: >> >> >>> var = ['a', 'b', 'c', 'd', 'e'] >> >> >>> length=int(raw_input("enter the length of random letters you need ")) >> enter the length of random letters you need 2 >> >> >>> length >> 2 >> >> >>> from itertools import combinations_with_replacement >> >> >>> [''.join(s) for s in combinations_with_replacement(var, 2)] >> ['aa', >> 'ab', >> 'ac', >> 'ad', >> 'ae', >> 'bb', >> 'bc', >> 'bd', >> 'be', >> 'cc', >> 'cd', >> 'ce', >> 'dd', >> 'de', >> 'ee'] >> >> On Wed, Feb 4, 2015 at 12:38 PM, Alan Gauld >> wrote: >> >>> On 04/02/15 09:46, Suresh Kumar wrote: >>> >>> print var >>>>>>> >>>>>> ['a', 'b', 'c', 'd', 'e'] >>>> >>> >>> the user gave two so code should be like this >>>> >>>>> for i in itertools.product(var,var): >>>>>>> >>>>>> print i[0]+i[1] >>>> >>> >>> output of code should be like this >>>> aa >>>> ab >>>> >>> ... >>> >>>> ee >>>> >>> >>> based on the user given input of length i need to add var in for loop >>>> if 3 given >>>> >>>>> for i in itertools.product(var,var,var): >>>>>>> >>>>>> print i[0]+i[1]+i[2] >>>> >>> >>> OK, So the question is how to pass n copies of var to product()? >>> >>> You could do it by enclosing var in an outer list or tuple, then >>> unpacking the result in the call to product(): >>> >>> Untested... >>> >>> for i in itertools.product(*((var,) * n)): >>> print ''.join(i) >>> >>> Does that work? >>> >>> >>> >>> -- >>> Alan G >>> Author of the Learn to Program web site >>> http://www.alan-g.me.uk/ >>> http://www.amazon.com/author/alan_gauld >>> Follow my photo-blog on Flickr at: >>> http://www.flickr.com/photos/alangauldphotos >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> https://mail.python.org/mailman/listinfo/tutor >>> >> >> > From alan.gauld at btinternet.com Wed Feb 4 14:45:52 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 04 Feb 2015 13:45:52 +0000 Subject: [Tutor] How can I replicate a list in a for loop In-Reply-To: References: <54d150f9.4841440a.5d7f.ffff8eb1@mx.google.com> Message-ID: <54D22290.9080908@btinternet.com> On 04/02/15 13:06, Ra?l Cumplido wrote: > There is a repeat argument on the product function that is used > exactly for what you want to do: > >>> for s in product(var, repeat=2) > print ''.join(s) Good catch, I should have remembered that. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From james at uplinkzero.com Wed Feb 4 18:01:40 2015 From: james at uplinkzero.com (James Chapman) Date: Wed, 4 Feb 2015 17:01:40 +0000 Subject: [Tutor] Assistance with UnicodeDecodeError In-Reply-To: References: Message-ID: > > I am trying to scrap text from a website using Python 2.7 in windows 8 and > i am getting this error *"**UnicodeDecodeError: 'charmap codec can't encode > character u'\u2014 in position 11231 character maps to "* > > For starters, move away from Python 2 unless you have a good reason to use it. Unicode is built into Python 3 whereas it's an after thought in Python 2. What's happening is that python doesn't understand the character set in use and it's throwing the exception. You need to tell python what encoding to use: (not all website are "utf-8") Code example (using python 2.7): >>> u = u'\u2014' >>> print(u) Traceback (most recent call last): File "", line 1, in File "c:\Python27\lib\encodings\cp850.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u2014' in position 0: character maps to >>> s = u.encode("utf-8") >>> print(s) ??? I also strongly suggest you read: https://docs.python.org/2/howto/unicode.html There is much cursing to come. Unicode and especially multi-byte character string processing is a nightmare! Good luck ;-) James From james at uplinkzero.com Wed Feb 4 18:14:00 2015 From: james at uplinkzero.com (James Chapman) Date: Wed, 4 Feb 2015 17:14:00 +0000 Subject: [Tutor] Assistance with UnicodeDecodeError In-Reply-To: References: Message-ID: Actually, it's more likely that the char you are grabbing is UTF-16 not UTF-8 which is moving into the double byte... * An assumption based on the following output: >>> u = u'\u2014' >>> s = u.encode("utf-16") >>> print(s) ?? >>> s = u.encode("utf-32") >>> print(s) ? ? >>> s = u.encode("utf-16LE") >>> print(s) ? >>> s = u.encode("utf-16BE") >>> print(s) ? See https://en.wikipedia.org/wiki/Character_encoding to help with the understanding of character encoding, code pages and why they are important. James From dyoo at hashcollision.org Wed Feb 4 19:12:58 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 4 Feb 2015 10:12:58 -0800 Subject: [Tutor] Need help with find error In-Reply-To: References: Message-ID: On Wed, Feb 4, 2015 at 1:01 AM, ?????? ??????? wrote: > Hi > I'm learning python a few weeks and have problems with code that read text > from txt-file > Code doing all right, but in the end I have error > > Traceback (most recent call last): > File "trivia_challenge.py", line 81, in > main() > File "trivia_challenge.py", line 74, in main > category, question, answers, correct, explanation, points = > next_block(trivia_file) > File "trivia_challenge.py", line 37, in next_block > points = int(next_line(the_file)) > ValueError: invalid literal for int() with base 10: '' Your next_line() function looks a little off. Let's take a look at it: ############################################ def next_line(the_file): """Return next line from the trivia file, formatted.""" line = the_file.readline() line = line.replace("/", "\n") return line ############################################ What do you want to happen here, when there are no more lines in the file to read? From dyoo at hashcollision.org Wed Feb 4 19:24:12 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 4 Feb 2015 10:24:12 -0800 Subject: [Tutor] Need help with find error In-Reply-To: References: Message-ID: As a revision of my initial question, when we look at next_block(), it's documented as follows: ############################################ def next_block(the_file): """Return the next block of data from the trivia file.""" .... ############################################ What if there are no more blocks in the file? What should happen then? Let's say that we do a test, where we pass in the empty file to next_block(). ###################### from io import StringIO x = next_block(StringIO('')) ###################### What do you want to happen in this situation? --- As a side note: if you have control over the data format, you might want to consider using JSON rather than a line-based format. If you use JSON, this takes care of a few issues that you are working around now. For example, you can reuse the newline escapes rather than define your own convention. Also, rather than read a stream of records, where you have to deal with the end of the file, you might just read one JSON object that represents your whole trivia file, which will simplify your program's logic. See: https://docs.python.org/2/library/json.html and use your favorite web search engine for 'json python tutorial', and you should be able to find some useful information. If you have questions, please feel free to ask. From zagheni at yahoo.com Thu Feb 5 01:12:35 2015 From: zagheni at yahoo.com (Antonio Zagheni) Date: Wed, 4 Feb 2015 16:12:35 -0800 Subject: [Tutor] Why is it not working? Message-ID: <1423095155.26663.YahooMailBasic@web164004.mail.gq1.yahoo.com> Hi there, I am a begginer in python and I'm trying to learn something about Tkinter. I did a game (the code is below) using Tkinter were two players have to fill a row, a column or a diagonal with either 'X' or 'O'. When it happens, the code was supposed to recognize the winner ('Jogador 1 or 2 vence!' --> translating from portuguese means 'player 1 or 2 wins!'). The problem is that sometimes the code doesn't recognize the winner and I can't find the problem. I don't have any error message. I belive that the problem is related with the fact that after clicking a button it calls a function an inside that function another function is called (analise()), but I am not sure... If somebody could take a look and give me some tips to solve the problem I will apreciate a lot. The problem occurs either using Windows 7 or Ubuntu 14.04 in a 64 bit computer, both running idle with python's version 2.7.7. Regards, Antonio Zagheni. #------------------------------------------------------------------------------- from Tkinter import * janela = Tk() flag_botaoA1 = "1" flag_botaoA2 = "2" flag_botaoA3 = "3" flag_botaoB1 = "4" flag_botaoB2 = "5" flag_botaoB3 = "6" flag_botaoC1 = "7" flag_botaoC2 = "8" flag_botaoC3 = "9" jogador = 1 rodada = 1 fim = False rotulo_botaoA1 = StringVar() rotulo_botaoA2 = StringVar() rotulo_botaoA3 = StringVar() rotulo_botaoB1 = StringVar() rotulo_botaoB2 = StringVar() rotulo_botaoB3 = StringVar() rotulo_botaoC1 = StringVar() rotulo_botaoC2 = StringVar() rotulo_botaoC3 = StringVar() active_player = StringVar() active_player.set(str(jogador)) def analise(): global jogador, rodada print flag_botaoA1, flag_botaoA2, flag_botaoA3 print flag_botaoB1, flag_botaoB2, flag_botaoB3 print flag_botaoC1, flag_botaoC2, flag_botaoC3 print jogador, rodada if rodada == 9: active_player.set('Game Over!') fim = True if flag_botaoA1 == flag_botaoB1 == flag_botaoC1 or flag_botaoA2 == flag_botaoB2 == flag_botaoC2 or flag_botaoA3 == flag_botaoB3 == flag_botaoC3: active_player.set(str(jogador) + ' vence!') fim = True elif flag_botaoA1 == flag_botaoA2 == flag_botaoA3 or flag_botaoB1 == flag_botaoB2 == flag_botaoB3 or flag_botaoC1 == flag_botaoC2 == flag_botaoC3: active_player.set(str(jogador) + ' vence!') fim = True elif flag_botaoA1 == flag_botaoB2 == flag_botaoC3 or flag_botaoC1 == flag_botaoB2 == flag_botaoA3: active_player.set(str(jogador) + ' vence!') fim = True rodada += 1 def clickA1(): global jogador, flag_botaoA1 if jogador == 1 and flag_botaoA1 == "1" and fim == False: rotulo_botaoA1.set("X") flag_botaoA1 = 'X' analise() jogador = 2 if jogador == 2 and flag_botaoA1 == "1" and fim == False: rotulo_botaoA1.set("O") flag_botaoA1 = 'O' analise() jogador = 1 active_player.set(str(jogador)) def clickA2(): global jogador, flag_botaoA2 if jogador == 1 and flag_botaoA2 == "2" and fim == False: rotulo_botaoA2.set("X") flag_botaoA2 = 'X' analise() jogador = 2 if jogador == 2 and flag_botaoA2 == "2" and fim == False: rotulo_botaoA2.set("O") flag_botaoA2 = 'O' analise() jogador = 1 active_player.set(str(jogador)) def clickA3(): global jogador, flag_botaoA3 if jogador == 1 and flag_botaoA3 == "3" and fim == False: rotulo_botaoA3.set("X") flag_botaoA3 = 'X' analise() jogador = 2 if jogador == 2 and flag_botaoA3 == "3" and fim == False: rotulo_botaoA3.set("O") flag_botaoA3 = 'O' analise() jogador = 1 active_player.set(str(jogador)) def clickB1(): global jogador, flag_botaoB1 if jogador == 1 and flag_botaoB1 == "4" and fim == False: rotulo_botaoB1.set("X") flag_botaoB1 = 'X' analise() jogador = 2 if jogador == 2 and flag_botaoB1 == "4" and fim == False: rotulo_botaoB1.set("O") flag_botaoB1 = 'O' analise() jogador = 1 active_player.set(str(jogador)) def clickB2(): global jogador, flag_botaoB2 if jogador == 1 and flag_botaoB2 == "5" and fim == False: rotulo_botaoB2.set("X") flag_botaoB2 = 'X' analise() jogador = 2 if jogador == 2 and flag_botaoB2 == "5" and fim == False: rotulo_botaoB2.set("O") flag_botaoB2 = 'O' analise() jogador = 1 active_player.set(str(jogador)) def clickB3(): global jogador, flag_botaoB3 if jogador == 1 and flag_botaoB3 == "6" and fim == False: rotulo_botaoB3.set("X") flag_botaoB3 = 'X' analise() jogador = 2 if jogador == 2 and flag_botaoB3 == "6" and fim == False: rotulo_botaoB3.set("O") flag_botaoB3 = 'O' analise() jogador = 1 active_player.set(str(jogador)) def clickC1(): global jogador, flag_botaoC1 if jogador == 1 and flag_botaoC1 == "7" and fim == False: rotulo_botaoC1.set("X") flag_botaoC1 = 'X' analise() jogador = 2 if jogador == 2 and flag_botaoC1 == "7" and fim == False: rotulo_botaoC1.set("O") flag_botaoC1 = 'O' analise() jogador = 1 active_player.set(str(jogador)) def clickC2(): global jogador, flag_botaoC2 if jogador == 1 and flag_botaoC2 == "8" and fim == False: rotulo_botaoC2.set("X") flag_botaoC2 = 'X' analise() jogador = 2 if jogador == 2 and flag_botaoC2 == "8" and fim == False: rotulo_botaoC2.set("O") flag_botaoC2 = 'O' analise() jogador = 1 active_player.set(str(jogador)) def clickC3(): global jogador, flag_botaoC3 if jogador == 1 and flag_botaoC3 == "9" and fim == False: rotulo_botaoC3.set("X") flag_botaoC3 = 'X' analise() jogador = 2 if jogador == 2 and flag_botaoC3 == "9" and fim == False: rotulo_botaoC3.set("O") flag_botaoC3 = 'O' analise() jogador = 1 tabuleiro = Frame(janela) tabuleiro.pack() janela.title('Jogo da Velha') linha1 = Frame(janela) linha1.pack() linha2 = Frame(janela) linha2.pack() linha3 = Frame(janela) linha3.pack() linha4 = Frame(janela) linha4.pack() titulo = Label (tabuleiro, text = 'Jogo da Velha') titulo.pack() autor = Label (tabuleiro, text = 'by Antonio Zagheni') autor.pack() player = Label (linha4, text = 'Jogador') player.pack(side = LEFT) actual_player = Label (linha4, textvariable = active_player) actual_player.pack(side = LEFT) botaoA1 = Button (linha1, textvariable = rotulo_botaoA1, command = clickA1, width = 1) botaoA1.pack(side = LEFT) botaoB1 = Button (linha2, textvariable = rotulo_botaoB1, command = clickB1, width = 1) botaoB1.pack(side = LEFT) botaoC1 = Button (linha3, textvariable = rotulo_botaoC1, command = clickC1, width = 1) botaoC1.pack(side = LEFT) botaoA2 = Button (linha1, textvariable = rotulo_botaoA2, command = clickA2, width = 1) botaoA2.pack(side = LEFT) botaoB2 = Button (linha2, textvariable = rotulo_botaoB2, command = clickB2, width = 1) botaoB2.pack(side = LEFT) botaoC2 = Button (linha3, textvariable = rotulo_botaoC2, command = clickC2, width = 1) botaoC2.pack(side = LEFT) botaoA3 = Button (linha1, textvariable = rotulo_botaoA3, command = clickA3, width = 1) botaoA3.pack(side = LEFT) botaoB3 = Button (linha2, textvariable = rotulo_botaoB3, command = clickB3, width = 1) botaoB3.pack(side = LEFT) botaoC3 = Button (linha3, textvariable = rotulo_botaoC3, command = clickC3, width = 1) botaoC3.pack(side = LEFT) janela.mainloop() From alan.gauld at btinternet.com Thu Feb 5 02:03:34 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 05 Feb 2015 01:03:34 +0000 Subject: [Tutor] Why is it not working? In-Reply-To: <1423095155.26663.YahooMailBasic@web164004.mail.gq1.yahoo.com> References: <1423095155.26663.YahooMailBasic@web164004.mail.gq1.yahoo.com> Message-ID: On 05/02/15 00:12, Antonio Zagheni wrote: > from Tkinter import * ... > jogador = 1 > rodada = 1 > fim = False Notice that fim is declared here as a global variable > def analise(): > global jogador, rodada But you do not include fim here > print flag_botaoA1, flag_botaoA2, flag_botaoA3 > print flag_botaoB1, flag_botaoB2, flag_botaoB3 > print flag_botaoC1, flag_botaoC2, flag_botaoC3 > print jogador, rodada > if rodada == 9: > active_player.set('Game Over!') > fim = True So when you set fim here you are setting a local variable only visible inside the analise() function. You need to make fim global. That's the only thing I can see although not speaking Portuguese makes it harder to check the logic. You have a lot of repetitive code there that could be made much simpler. But that's a mail for another time. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Thu Feb 5 04:51:15 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Wed, 4 Feb 2015 21:51:15 -0600 Subject: [Tutor] Why is it not working? In-Reply-To: <1423095155.26663.YahooMailBasic@web164004.mail.gq1.yahoo.com> References: <1423095155.26663.YahooMailBasic@web164004.mail.gq1.yahoo.com> Message-ID: On Wed, Feb 4, 2015 at 6:12 PM, Antonio Zagheni wrote: > Hi there, > > I am a begginer in python and I'm trying to learn something about Tkinter. > > I did a game (the code is below) using Tkinter were two players have to fill a row, a column or a diagonal with either 'X' or 'O'. > When it happens, the code was supposed to recognize the winner ('Jogador 1 or 2 vence!' --> translating from portuguese means 'player 1 or 2 wins!'). > > The problem is that sometimes the code doesn't recognize the winner and I can't find the problem. > > I don't have any error message. > > I belive that the problem is related with the fact that after clicking a button it calls a function an inside that function another function is called (analise()), but I am not sure... > > If somebody could take a look and give me some tips to solve the problem I will apreciate a lot. > > The problem occurs either using Windows 7 or Ubuntu 14.04 in a 64 bit computer, both running idle with python's version 2.7.7. It has been mentioned here in the past that one should not run a program using Tkinter from within IDLE as IDLE itself is implemented using Tkinter. Just to eliminate one other variable from your troubleshooting you might ensure you start your program from the command line and not from within IDLE. boB From linux at barrowhillfarm.org.uk Thu Feb 5 14:27:29 2015 From: linux at barrowhillfarm.org.uk (Bob Williams) Date: Thu, 05 Feb 2015 13:27:29 +0000 Subject: [Tutor] Nested for loops, possibly? Message-ID: <54D36FC1.5070800@barrowhillfarm.org.uk> Hi, My script is running under Python 3.4.1 on a 64bit openSUSE linux system. It is a backup script making calls to rsync and btrfs-tools, and backing up several different paths. Here is the script, my question follows below: **Code** import datetime import glob import os, os.path import subprocess import sys if not os.getuid() == 0: print("\n*** This script must be run as root. ***\n") sys.exit() mnt_path = "/home/bob/A3" subprocess.call(["mount", "LABEL=backup", mnt_path]) if not os.path.ismount(mnt_path): print("\nBackup drive is not mounted\nCheck if it is attached.\n") sys.exit() else: print("\nBackup drive mounted at", mnt_path, "\n") src_path = "/home/bob" today = datetime.datetime.now() fname = today.strftime("%y-%m-%d_%H-%M") doc_retain = datetime.timedelta(days=90) pic_retain = datetime.timedelta(days=90) misc_retain = datetime.timedelta(days=90) etc_retain = datetime.timedelta(days=30) mus_retain = datetime.timedelta(days=30) web_retain = datetime.timedelta(days=30) rep_retain = datetime.timedelta(days=30) doc_srcpath = os.path.join(src_path, "Documents") pic_srcpath = os.path.join(src_path, "Pictures") misc_srcpath = src_path etc_srcpath = "/etc" music_srcpath = os.path.join(src_path, "music") www_srcpath = "/srv/www" repo_srcpath = os.path.join(src_path, "download") doc_syncpath = os.path.join(mnt_path, "documents") pic_syncpath = os.path.join(mnt_path, "pictures") misc_syncpath = os.path.join(mnt_path, "miscellaneous") etc_syncpath = os.path.join(mnt_path, "etc") music_syncpath = os.path.join(mnt_path, "music") www_syncpath = os.path.join(mnt_path, "www") repo_syncpath = os.path.join(mnt_path, "repo") doc_snappath = os.path.join(mnt_path, "docsnaps", fname) pic_snappath = os.path.join(mnt_path, "picsnaps", fname) misc_snappath = os.path.join(mnt_path, "miscsnaps", fname) etc_snappath = os.path.join(mnt_path, "etcsnaps", fname) music_snappath = os.path.join(mnt_path, "musicsnaps", fname) www_snappath = os.path.join(mnt_path, "wwwsnaps", fname) repo_snappath = os.path.join(mnt_path, "reposnaps", fname) doc_snaplist = glob.glob(mnt_path + "/docsnaps/*") pic_snaplist = glob.glob(mnt_path + "/picsnaps/*") misc_snaplist = glob.glob(mnt_path + "/miscsnaps/*") etc_snaplist = glob.glob(mnt_path + "/etcsnaps/*") music_snaplist = glob.glob(mnt_path + "/musicsnaps/*") www_snaplist = glob.glob(mnt_path + "/wwwsnaps/*") repo_snaplist = glob.glob(mnt_path + "/reposnaps/*") def do_sync(source, dest): subprocess.call(['rsync', '-av', '--safe-links', '--delete-excluded', '-F', source, dest]) print("\n") def create_snaps(newsnap, snapdest): subprocess.call(['btrfs', 'subvolume', 'snapshot', newsnap, snapdest]) print("\n") def expire_snaps(snaplist, today, expiry_interval): x = 0 print("\nDeleting snapshots older than", str(expiry_interval)[:7], "...") for i in range(0, len(snaplist)): snap_date = datetime.datetime.strptime(snaplist[i][-14:], "%y-%m-%d_%H-%M") if today - snap_date >= expiry_interval: subprocess.call(['btrfs', 'subvolume', 'delete', snaplist[i]]) x += 1 if x == 0: print("... No snapshots older than", str(expiry_interval)[:7], "found - nothing to do.") else: print("...", x, "snapshot(s) deleted.") print("\n") def main(): print("Backing up ", src_path, "/Documents\n", sep='') do_sync(doc_srcpath, doc_syncpath) create_snaps(doc_syncpath, doc_snappath) print("Documents backup completed.") expire_snaps(doc_snaplist, today, doc_retain) print("Backing up ", src_path, "/Pictures\n", sep='') do_sync(pic_srcpath, pic_syncpath) create_snaps(pic_syncpath, pic_snappath) print("Pictures backup completed.") expire_snaps(pic_snaplist, today, pic_retain) print("Backing up Miscellaneous files\n") do_sync(misc_srcpath, misc_syncpath) create_snaps(misc_syncpath, misc_snappath) print("Miscellaneous backup completed.") expire_snaps(misc_snaplist, today, misc_retain) print("Backing up /etc\n") do_sync(etc_srcpath, etc_syncpath) create_snaps(etc_syncpath, etc_snappath) print("Backup of /etc completed.") expire_snaps(etc_snaplist, today, etc_retain) print("Backing up ", src_path, "/music\n", sep='') do_sync(music_srcpath, music_syncpath) create_snaps(music_syncpath, music_snappath) print("Music backup completed.") expire_snaps(music_snaplist, today, mus_retain) print("Backing up Web server\n") do_sync(www_srcpath, www_syncpath) create_snaps(www_syncpath, www_snappath) print("Web server backup completed.") expire_snaps(www_snaplist, today, web_retain) print("Backing up Download repository\n") do_sync(repo_srcpath, repo_syncpath) create_snaps(repo_syncpath, repo_snappath) print("Download repository backup completed.") expire_snaps(repo_snaplist, today, rep_retain) print("\nAll backups completed.") print("\nUnmounting backup drive.\n") subprocess.call(['umount', mnt_path]) print("\n>>> Please power down the Quad external drive enclosure <<<\n") if __name__ == "__main__": main() **/Code** I would like to reduce all those repeated calls to do_sync() in main(), for example, to one by putting the *_srcpath and *_*syncpath variables into lists (eg. source_list and sync_list) and using a for loop to get the first item out of each list, then the second item, etc. Something like: for i in range(0, len(source_list)): for j in range(0, len(sync_list)): do_sync(source_list[i], sync_list[j]) but this will get all the values of sync_list[j] for each value of source_list[i], which is not what I want. I hope this is clear enough to see my problem? I realise that the print statements will need some work, I'm just trying to get the functionality working. TIA Bob -- Bob Williams System: Linux 3.16.7-7-desktop Distro: openSUSE 13.2 (x86_64) with KDE Development Platform: 4.14.3 Uptime: 06:00am up 7:55, 3 users, load average: 0.16, 0.05, 0.06 From breamoreboy at yahoo.co.uk Thu Feb 5 14:57:56 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 05 Feb 2015 13:57:56 +0000 Subject: [Tutor] Nested for loops, possibly? In-Reply-To: <54D36FC1.5070800@barrowhillfarm.org.uk> References: <54D36FC1.5070800@barrowhillfarm.org.uk> Message-ID: On 05/02/2015 13:27, Bob Williams wrote: > > I would like to reduce all those repeated calls to do_sync() in main(), for example, to one by putting the *_srcpath and *_*syncpath variables into lists (eg. source_list and sync_list) and using a for loop to get the first item out of each list, then the second item, etc. Something like: > > for i in range(0, len(source_list)): > for j in range(0, len(sync_list)): > do_sync(source_list[i], sync_list[j]) > > but this will get all the values of sync_list[j] for each value of source_list[i], which is not what I want. > > I hope this is clear enough to see my problem? I realise that the print statements will need some work, I'm just trying to get the functionality working. > > TIA > > Bob > Apologies for shouting but this has been said several times in the past so I'm deliberately emphasising the point. YOU *DON'T* NEED TO LOOP THROUGH ITEMS IN A LIST USING range AND len. Hence:- for source in source_list: for sync in sync_list: do_sync(source, sync) Having said that I haven't looked at your code in depth, but I think you're looking for something like:- for source, sync in zip(source_list, sync_list): do_sync(source, sync) Let's try it. >>> def do_sync(source, sync): ... print('Source is', source, 'Sync is', sync) ... >>> source_list = ['a', 'b', 'c'] >>> sync_list = ['w', 'x', 'y'] >>> for source, sync in zip(source_list, sync_list): ... do_sync(source, sync) ... Source is a Sync is w Source is b Sync is x Source is c Sync is y Am I close? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From davea at davea.name Thu Feb 5 15:59:34 2015 From: davea at davea.name (DaveA) Date: Thu, 05 Feb 2015 14:59:34 +0000 Subject: [Tutor] Nested for loops, possibly? In-Reply-To: <54D36FC1.5070800@barrowhillfarm.org.uk> References: <54D36FC1.5070800@barrowhillfarm.org.uk> Message-ID: <5C17E4E2-69AC-40F4-9B5B-F7DD55B10D23@davea.name> On February 5, 2015 8:27:29 AM EST, Bob Williams wrote: >Hi, > >My script is running under Python 3.4.1 on a 64bit openSUSE linux >system. It is a backup script making calls to rsync and btrfs-tools, >and backing up several different paths. Here is the script, my question >follows below: > >**Code** >import datetime >import glob >import os, os.path >import subprocess >import sys > >if not os.getuid() == 0: > print("\n*** This script must be run as root. ***\n") > sys.exit() > >mnt_path = "/home/bob/A3" > >subprocess.call(["mount", "LABEL=backup", mnt_path]) >if not os.path.ismount(mnt_path): > print("\nBackup drive is not mounted\nCheck if it is attached.\n") > sys.exit() >else: > print("\nBackup drive mounted at", mnt_path, "\n") > >src_path = "/home/bob" > >today = datetime.datetime.now() >fname = today.strftime("%y-%m-%d_%H-%M") > >doc_retain = datetime.timedelta(days=90) >pic_retain = datetime.timedelta(days=90) >misc_retain = datetime.timedelta(days=90) >etc_retain = datetime.timedelta(days=30) >mus_retain = datetime.timedelta(days=30) >web_retain = datetime.timedelta(days=30) >rep_retain = datetime.timedelta(days=30) > >doc_srcpath = os.path.join(src_path, "Documents") >pic_srcpath = os.path.join(src_path, "Pictures") >misc_srcpath = src_path >etc_srcpath = "/etc" >music_srcpath = os.path.join(src_path, "music") >www_srcpath = "/srv/www" >repo_srcpath = os.path.join(src_path, "download") > Three things bother me about this portion of code, Too much code at top-level, too many separate variables, too many global.The last point doesn't matter much, since they're constant. I'd put these Values into a class, and make a list of instances. If you're not yet comfortable with that, it would also be possible to make a list per "paragraph", and use zip to combine them, as already suggested. The class would hold retain, srcpath, syncpath, snappath, etc. And your list would have 7 instances of that class currently, corresponding to your doc, pic, misc, ... That list would be THE global, replacing these 35 or so. It would be populated something like: def initialize (worklist=[]): worklist . append (Job (90, src_path, "Documents", "documents", "docsnaps") worklist .append (Job (90, src_path, "Pictures", ... .... return worklist Now all the joins and globs are done in the Job initializer, just once. .....th.join(mnt_path, "documents") >pic_syncpath = os.path.join(mnt_path, "pictures") >misc_syncpath = os.path.join(mnt_path, "miscellaneous") >etc_syncpath = os.path.join(mnt_path, "etc") >music_syncpath = os.path.join(mnt_path, "music") >www_syncpath = os.path.join(mnt_path, "www") >repo_syncpath = os.path.join(mnt_path, "repo") > >doc_snappath = os.path.join(mnt_path, "docsnaps", fname) >pic_snappath = os.path.join(mnt_path, "picsnaps", fname) >misc_snappath = os.path.join(mnt_path, "miscsnaps", fname) >etc_snappath = os.path.join(mnt_path, "etcsnaps", fname) >music_snappath = os.path.join(mnt_path, "musicsnaps", fname) >www_snappath = os.path.join(mnt_path, "wwwsnaps", fname) >repo_snappath = os.path.join(mnt_path, "reposnaps", fname) > >doc_snaplist = glob.glob(mnt_path + "/docsnaps/*") >pic_snaplist = glob.glob(mnt_path + "/picsnaps/*") >misc_snaplist = glob.glob(mnt_path + "/miscsnaps/*") >etc_snaplist = glob.glob(mnt_path + "/etcsnaps/*") >music_snaplist = glob.glob(mnt_path + "/musicsnaps/*") >www_snaplist = glob.glob(mnt_path + "/wwwsnaps/*") >repo_snaplist = glob.glob(mnt_path + "/reposnaps/*") > >def do_sync(source, dest): >subprocess.call(['rsync', '-av', '--safe-links', '--delete-excluded', >'-F', source, dest]) > print("\n") > >def create_snaps(newsnap, snapdest): > subprocess.call(['btrfs', 'subvolume', 'snapshot', newsnap, snapdest]) > print("\n") > >def expire_snaps(snaplist, today, expiry_interval): > x = 0 >print("\nDeleting snapshots older than", str(expiry_interval)[:7], >"...") > for i in range(0, len(snaplist)): >snap_date = datetime.datetime.strptime(snaplist[i][-14:], >"%y-%m-%d_%H-%M") > if today - snap_date >= expiry_interval: > subprocess.call(['btrfs', 'subvolume', 'delete', snaplist[i]]) > x += 1 > if x == 0: >print("... No snapshots older than", str(expiry_interval)[:7], "found - >nothing to do.") > else: > print("...", x, "snapshot(s) deleted.") > print("\n") > >def main(): > print("Backing up ", src_path, "/Documents\n", sep='') > do_sync(doc_srcpath, doc_syncpath) > create_snaps(doc_syncpath, doc_snappath) > print("Documents backup completed.") > expire_snaps(doc_snaplist, today, doc_retain) At this point main becomes something like jobs = initialize () for job in jobs: do_sync (job.srcpath, job.syncpath) create_snaps (job.syncpath, job.snappath) expire_snaps (job.snaplist, ... > > print("Backing up ", src_path, "/Pictures\n", sep='') > do_sync(pic_srcpath, pic_syncpath) > create_snaps(pic_syncpath, pic_snappath) > print("Pictures backup completed.") > expire_snaps(pic_snaplist, today, pic_retain) > > print("Backing up Miscellaneous files\n") > do_sync(misc_srcpath, misc_syncpath) > create_snaps(misc_syncpath, misc_snappath) > print("Miscellaneous backup completed.") > expire_snaps(misc_snaplist, today, misc_retain) > > print("Backing up /etc\n") > do_sync(etc_srcpath, etc_syncpath) > create_snaps(etc_syncpath, etc_snappath) > print("Backup of /etc completed.") > expire_snaps(etc_snaplist, today, etc_retain) > > print("Backing up ", src_path, "/music\n", sep='') > do_sync(music_srcpath, music_syncpath) > create_snaps(music_syncpath, music_snappath) > print("Music backup completed.") > expire_snaps(music_snaplist, today, mus_retain) > > print("Backing up Web server\n") > do_sync(www_srcpath, www_syncpath) > create_snaps(www_syncpath, www_snappath) > print("Web server backup completed.") > expire_snaps(www_snaplist, today, web_retain) > > print("Backing up Download repository\n") > do_sync(repo_srcpath, repo_syncpath) > create_snaps(repo_syncpath, repo_snappath) > print("Download repository backup completed.") > expire_snaps(repo_snaplist, today, rep_retain) > > print("\nAll backups completed.") > print("\nUnmounting backup drive.\n") > subprocess.call(['umount', mnt_path]) >print("\n>>> Please power down the Quad external drive enclosure ><<<\n") > >if __name__ == "__main__": > main() >**/Code** > >I would like to reduce all those repeated calls to do_sync() in main(), >for example, to one by putting the *_srcpath and *_*syncpath variables >into lists (eg. source_list and sync_list) and using a for loop to get >the first item out of each list, then the second item, etc. Something >like: > >for i in range(0, len(source_list)): > for j in range(0, len(sync_list)): > do_sync(source_list[i], sync_list[j]) > >but this will get all the values of sync_list[j] for each value of >source_list[i], which is not what I want. If you're sure all the lists are the same length, you can use zip. But I'd recommend a list of objects. > >I hope this is clear enough to see my problem? I realise that the print >statements will need some work, I'm just trying to get the >functionality working. > >TIA > >Bob -- Sent from my Android device with K-9 Mail. Please excuse my brevity. From linux at barrowhillfarm.org.uk Thu Feb 5 16:34:33 2015 From: linux at barrowhillfarm.org.uk (Bob Williams) Date: Thu, 05 Feb 2015 15:34:33 +0000 Subject: [Tutor] Nested for loops, possibly? In-Reply-To: References: <54D36FC1.5070800@barrowhillfarm.org.uk> Message-ID: <54D38D89.5020300@barrowhillfarm.org.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 05/02/15 13:57, Mark Lawrence wrote: > On 05/02/2015 13:27, Bob Williams wrote: > >> >> I would like to reduce all those repeated calls to do_sync() in >> main(), for example, to one by putting the *_srcpath and >> *_*syncpath variables into lists (eg. source_list and sync_list) >> and using a for loop to get the first item out of each list, then >> the second item, etc. Something like: >> >> for i in range(0, len(source_list)): for j in range(0, >> len(sync_list)): do_sync(source_list[i], sync_list[j]) >> >> but this will get all the values of sync_list[j] for each value >> of source_list[i], which is not what I want. >> >> I hope this is clear enough to see my problem? I realise that >> the print statements will need some work, I'm just trying to get >> the functionality working. >> >> TIA >> >> Bob >> > > Apologies for shouting but this has been said several times in the > past so I'm deliberately emphasising the point. YOU *DON'T* NEED > TO LOOP THROUGH ITEMS IN A LIST USING range AND len. Hence:- > Sometimes you have to shout, if the class won't listen ;-) > for source in source_list: for sync in sync_list: do_sync(source, > sync) > Point taken, and understood. > Having said that I haven't looked at your code in depth, but I > think you're looking for something like:- > > for source, sync in zip(source_list, sync_list): do_sync(source, > sync) > > Let's try it. > >>>> def do_sync(source, sync): > ... print('Source is', source, 'Sync is', sync) ... >>>> source_list = ['a', 'b', 'c'] sync_list = ['w', 'x', 'y'] for >>>> source, sync in zip(source_list, sync_list): > ... do_sync(source, sync) ... Source is a Sync is w Source is b > Sync is x Source is c Sync is y > > Am I close? > Spot on! This is my first encounter with zip, but it does exactly what I want here. Many thanks Bob - -- Bob Williams System: Linux 3.16.7-7-desktop Distro: openSUSE 13.2 (x86_64) with KDE Development Platform: 4.14.3 Uptime: 06:00am up 7:55, 3 users, load average: 0.16, 0.05, 0.06 -----BEGIN PGP SIGNATURE----- Version: GnuPG v2 iEYEARECAAYFAlTTjYYACgkQ0Sr7eZJrmU4HlQCeKPfXiSJEiR5D1JqeZkPLAfRn AFMAoJhyCw75mC8b0+n8T6zIU0AnT0vM =8NMM -----END PGP SIGNATURE----- From robertvstepp at gmail.com Thu Feb 5 18:30:38 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 5 Feb 2015 11:30:38 -0600 Subject: [Tutor] How to easily recover the current index when using Python-style for loops? Message-ID: Python 2.4.4, Solaris 10. a_list = [item1, item2, item3] for item in a_list: print 'Item number', ???, 'is:', item Is there an easy, clever, Pythonic way (other than setting up a counter) to replace ??? with the current index of item in a_list? -- boB From linux at barrowhillfarm.org.uk Thu Feb 5 18:33:56 2015 From: linux at barrowhillfarm.org.uk (Bob Williams) Date: Thu, 05 Feb 2015 17:33:56 +0000 Subject: [Tutor] Nested for loops, possibly? In-Reply-To: <5C17E4E2-69AC-40F4-9B5B-F7DD55B10D23@davea.name> References: <54D36FC1.5070800@barrowhillfarm.org.uk> <5C17E4E2-69AC-40F4-9B5B-F7DD55B10D23@davea.name> Message-ID: <54D3A984.8050704@barrowhillfarm.org.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 05/02/15 14:59, DaveA wrote: > > > On February 5, 2015 8:27:29 AM EST, Bob Williams > wrote: >> Hi, >> >> My script is running under Python 3.4.1 on a 64bit openSUSE >> linux system. It is a backup script making calls to rsync and >> btrfs-tools, and backing up several different paths. Here is the >> script, my question follows below: >> >> **Code** import datetime import glob import os, os.path import >> subprocess import sys >> >> if not os.getuid() == 0: print("\n*** This script must be run as >> root. ***\n") sys.exit() >> >> mnt_path = "/home/bob/A3" >> >> subprocess.call(["mount", "LABEL=backup", mnt_path]) if not >> os.path.ismount(mnt_path): print("\nBackup drive is not >> mounted\nCheck if it is attached.\n") sys.exit() else: >> print("\nBackup drive mounted at", mnt_path, "\n") >> >> src_path = "/home/bob" >> >> today = datetime.datetime.now() fname = >> today.strftime("%y-%m-%d_%H-%M") >> >> doc_retain = datetime.timedelta(days=90) pic_retain = >> datetime.timedelta(days=90) misc_retain = >> datetime.timedelta(days=90) etc_retain = >> datetime.timedelta(days=30) mus_retain = >> datetime.timedelta(days=30) web_retain = >> datetime.timedelta(days=30) rep_retain = >> datetime.timedelta(days=30) >> >> doc_srcpath = os.path.join(src_path, "Documents") pic_srcpath = >> os.path.join(src_path, "Pictures") misc_srcpath = src_path >> etc_srcpath = "/etc" music_srcpath = os.path.join(src_path, >> "music") www_srcpath = "/srv/www" repo_srcpath = >> os.path.join(src_path, "download") >> > Three things bother me about this portion of code, Too much code at > top-level, too many separate variables, too many global.The last > point doesn't matter much, since they're constant. > > I'd put these Values into a class, and make a list of instances. If > you're not yet comfortable with that, it would also be possible to > make a list per "paragraph", and use zip to combine them, as > already suggested. > I also felt that there was something wrong with that long list of variables. However, I'm new to classes, so I'll need to do some background reading. Thank you for the pointer. > The class would hold retain, srcpath, syncpath, snappath, etc. And > your list would have 7 instances of that class currently, > corresponding to your doc, pic, misc, ... > > That list would be THE global, replacing these 35 or so. It would > be populated something like: > > def initialize (worklist=[]): worklist . append (Job (90, > src_path, "Documents", "documents", "docsnaps") worklist .append > (Job (90, src_path, "Pictures", ... .... return worklist > > Now all the joins and globs are done in the Job initializer, just > once. > > .....th.join(mnt_path, "documents") >> pic_syncpath = os.path.join(mnt_path, "pictures") misc_syncpath = >> os.path.join(mnt_path, "miscellaneous") etc_syncpath = >> os.path.join(mnt_path, "etc") music_syncpath = >> os.path.join(mnt_path, "music") www_syncpath = >> os.path.join(mnt_path, "www") repo_syncpath = >> os.path.join(mnt_path, "repo") >> >> doc_snappath = os.path.join(mnt_path, "docsnaps", fname) >> pic_snappath = os.path.join(mnt_path, "picsnaps", fname) >> misc_snappath = os.path.join(mnt_path, "miscsnaps", fname) >> etc_snappath = os.path.join(mnt_path, "etcsnaps", fname) >> music_snappath = os.path.join(mnt_path, "musicsnaps", fname) >> www_snappath = os.path.join(mnt_path, "wwwsnaps", fname) >> repo_snappath = os.path.join(mnt_path, "reposnaps", fname) >> >> doc_snaplist = glob.glob(mnt_path + "/docsnaps/*") pic_snaplist = >> glob.glob(mnt_path + "/picsnaps/*") misc_snaplist = >> glob.glob(mnt_path + "/miscsnaps/*") etc_snaplist = >> glob.glob(mnt_path + "/etcsnaps/*") music_snaplist = >> glob.glob(mnt_path + "/musicsnaps/*") www_snaplist = >> glob.glob(mnt_path + "/wwwsnaps/*") repo_snaplist = >> glob.glob(mnt_path + "/reposnaps/*") >> >> def do_sync(source, dest): subprocess.call(['rsync', '-av', >> '--safe-links', '--delete-excluded', '-F', source, dest]) >> print("\n") >> >> def create_snaps(newsnap, snapdest): subprocess.call(['btrfs', >> 'subvolume', 'snapshot', newsnap, snapdest]) print("\n") >> >> def expire_snaps(snaplist, today, expiry_interval): x = 0 >> print("\nDeleting snapshots older than", >> str(expiry_interval)[:7], "...") for i in range(0, >> len(snaplist)): snap_date = >> datetime.datetime.strptime(snaplist[i][-14:], "%y-%m-%d_%H-%M") >> if today - snap_date >= expiry_interval: >> subprocess.call(['btrfs', 'subvolume', 'delete', snaplist[i]]) x >> += 1 if x == 0: print("... No snapshots older than", >> str(expiry_interval)[:7], "found - nothing to do.") else: >> print("...", x, "snapshot(s) deleted.") print("\n") >> >> def main(): print("Backing up ", src_path, "/Documents\n", >> sep='') do_sync(doc_srcpath, doc_syncpath) >> create_snaps(doc_syncpath, doc_snappath) print("Documents backup >> completed.") expire_snaps(doc_snaplist, today, doc_retain) > > At this point main becomes something like > > jobs = initialize () for job in jobs: do_sync (job.srcpath, > job.syncpath) create_snaps (job.syncpath, job.snappath) > expire_snaps (job.snaplist, ... >> >> print("Backing up ", src_path, "/Pictures\n", sep='') >> do_sync(pic_srcpath, pic_syncpath) create_snaps(pic_syncpath, >> pic_snappath) print("Pictures backup completed.") >> expire_snaps(pic_snaplist, today, pic_retain) >> >> print("Backing up Miscellaneous files\n") do_sync(misc_srcpath, >> misc_syncpath) create_snaps(misc_syncpath, misc_snappath) >> print("Miscellaneous backup completed.") >> expire_snaps(misc_snaplist, today, misc_retain) >> >> print("Backing up /etc\n") do_sync(etc_srcpath, etc_syncpath) >> create_snaps(etc_syncpath, etc_snappath) print("Backup of /etc >> completed.") expire_snaps(etc_snaplist, today, etc_retain) >> >> print("Backing up ", src_path, "/music\n", sep='') >> do_sync(music_srcpath, music_syncpath) >> create_snaps(music_syncpath, music_snappath) print("Music backup >> completed.") expire_snaps(music_snaplist, today, mus_retain) >> >> print("Backing up Web server\n") do_sync(www_srcpath, >> www_syncpath) create_snaps(www_syncpath, www_snappath) print("Web >> server backup completed.") expire_snaps(www_snaplist, today, >> web_retain) >> >> print("Backing up Download repository\n") do_sync(repo_srcpath, >> repo_syncpath) create_snaps(repo_syncpath, repo_snappath) >> print("Download repository backup completed.") >> expire_snaps(repo_snaplist, today, rep_retain) >> >> print("\nAll backups completed.") print("\nUnmounting backup >> drive.\n") subprocess.call(['umount', mnt_path]) print("\n>>> >> Please power down the Quad external drive enclosure <<<\n") >> >> if __name__ == "__main__": main() **/Code** >> >> I would like to reduce all those repeated calls to do_sync() in >> main(), for example, to one by putting the *_srcpath and >> *_*syncpath variables into lists (eg. source_list and sync_list) >> and using a for loop to get the first item out of each list, then >> the second item, etc. Something like: >> >> for i in range(0, len(source_list)): for j in range(0, >> len(sync_list)): do_sync(source_list[i], sync_list[j]) >> >> but this will get all the values of sync_list[j] for each value >> of source_list[i], which is not what I want. > > If you're sure all the lists are the same length, you can use zip. > But I'd recommend a list of objects. > >> >> I hope this is clear enough to see my problem? I realise that the >> print statements will need some work, I'm just trying to get the >> functionality working. >> >> TIA >> >> Bob > - -- Bob Williams System: Linux 3.16.7-7-desktop Distro: openSUSE 13.2 (x86_64) with KDE Development Platform: 4.14.3 Uptime: 06:00am up 7:55, 3 users, load average: 0.16, 0.05, 0.06 -----BEGIN PGP SIGNATURE----- Version: GnuPG v2 iEYEARECAAYFAlTTqYIACgkQ0Sr7eZJrmU7s0gCeNfl1WCW2kvahVlfmBfoZdEZ4 FU8AnitA7R8ewK8Uc5/24HB6aGlq8GHQ =hQva -----END PGP SIGNATURE----- From zachary.ware+pytut at gmail.com Thu Feb 5 18:45:20 2015 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Thu, 5 Feb 2015 11:45:20 -0600 Subject: [Tutor] How to easily recover the current index when using Python-style for loops? In-Reply-To: References: Message-ID: On Thu, Feb 5, 2015 at 11:30 AM, boB Stepp wrote: > Python 2.4.4, Solaris 10. > > a_list = [item1, item2, item3] > for item in a_list: > print 'Item number', ???, 'is:', item > > Is there an easy, clever, Pythonic way (other than setting up a > counter) to replace ??? with the current index of item in a_list? Added in Python 2.3: https://docs.python.org/2/library/functions.html#enumerate a_list = [item1, item2, item3] for i, item in enumerate(a_list): print 'Item number', i, 'is:', item -- Zach From alan.gauld at btinternet.com Thu Feb 5 18:48:40 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 05 Feb 2015 17:48:40 +0000 Subject: [Tutor] How to easily recover the current index when using Python-style for loops? In-Reply-To: References: Message-ID: On 05/02/15 17:30, boB Stepp wrote: > Python 2.4.4, Solaris 10. > > a_list = [item1, item2, item3] > for item in a_list: > print 'Item number', ???, 'is:', item > > Is there an easy, clever, Pythonic way (other than setting up a > counter) to replace ??? with the current index of item in a_list? > try: >>> help( enumerate() ) It returns the index and item and you can specify the starting index if you don't like zero. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From robertvstepp at gmail.com Thu Feb 5 19:00:52 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 5 Feb 2015 12:00:52 -0600 Subject: [Tutor] How to easily recover the current index when using Python-style for loops? In-Reply-To: References: Message-ID: On Thu, Feb 5, 2015 at 11:45 AM, Zachary Ware wrote: > On Thu, Feb 5, 2015 at 11:30 AM, boB Stepp wrote: >> Python 2.4.4, Solaris 10. >> >> a_list = [item1, item2, item3] >> for item in a_list: >> print 'Item number', ???, 'is:', item >> >> Is there an easy, clever, Pythonic way (other than setting up a >> counter) to replace ??? with the current index of item in a_list? > > Added in Python 2.3: > https://docs.python.org/2/library/functions.html#enumerate > > a_list = [item1, item2, item3] > for i, item in enumerate(a_list): > print 'Item number', i, 'is:', item Thanks, Zach! I knew I had seen this feature before, but I kept searching for the wrong terms. -- boB From robertvstepp at gmail.com Thu Feb 5 19:03:14 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 5 Feb 2015 12:03:14 -0600 Subject: [Tutor] How to easily recover the current index when using Python-style for loops? In-Reply-To: References: Message-ID: On Thu, Feb 5, 2015 at 11:48 AM, Alan Gauld wrote: > On 05/02/15 17:30, boB Stepp wrote: >> >> Python 2.4.4, Solaris 10. >> >> a_list = [item1, item2, item3] >> for item in a_list: >> print 'Item number', ???, 'is:', item >> >> Is there an easy, clever, Pythonic way (other than setting up a >> counter) to replace ??? with the current index of item in a_list? >> > > try: > >>>> help( enumerate() ) > > It returns the index and item and you can specify the > starting index if you don't like zero. Thanks, Alan! In this instance I am happy with zero, but the link Zach provided says that changing the starting index wasn't implemented until Python 2.6. -- boB From breamoreboy at yahoo.co.uk Thu Feb 5 19:25:15 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 05 Feb 2015 18:25:15 +0000 Subject: [Tutor] How to easily recover the current index when using Python-style for loops? In-Reply-To: References: Message-ID: On 05/02/2015 18:03, boB Stepp wrote: > On Thu, Feb 5, 2015 at 11:48 AM, Alan Gauld wrote: >> On 05/02/15 17:30, boB Stepp wrote: >>> >>> Python 2.4.4, Solaris 10. >>> >>> a_list = [item1, item2, item3] >>> for item in a_list: >>> print 'Item number', ???, 'is:', item >>> >>> Is there an easy, clever, Pythonic way (other than setting up a >>> counter) to replace ??? with the current index of item in a_list? >>> >> >> try: >> >>>>> help( enumerate() ) >> >> It returns the index and item and you can specify the >> starting index if you don't like zero. > > Thanks, Alan! In this instance I am happy with zero, but the link Zach > provided says that changing the starting index wasn't implemented > until Python 2.6. > We're now at 3.4 with 3.5 close to its first alpha release, so any particular reason that even 2.6 doesn't seem relevant to you? No axe to grind, just plain old fashioned curiosity :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From timomlists at gmail.com Thu Feb 5 19:37:09 2015 From: timomlists at gmail.com (Timo) Date: Thu, 05 Feb 2015 19:37:09 +0100 Subject: [Tutor] How to easily recover the current index when using Python-style for loops? In-Reply-To: References: Message-ID: <54D3B855.7080404@gmail.com> Op 05-02-15 om 18:48 schreef Alan Gauld: > > try: > > >>> help( enumerate() ) > > Should be >>> help(enumerate) Timo From davea at davea.name Thu Feb 5 19:46:08 2015 From: davea at davea.name (DaveA) Date: Thu, 05 Feb 2015 18:46:08 +0000 Subject: [Tutor] Nested for loops, possibly? In-Reply-To: <54D3A984.8050704@barrowhillfarm.org.uk> References: <54D36FC1.5070800@barrowhillfarm.org.uk> <5C17E4E2-69AC-40F4-9B5B-F7DD55B10D23@davea.name> <54D3A984.8050704@barrowhillfarm.org.uk> Message-ID: On February 5, 2015 12:33:56 PM EST, Bob Williams wrote: >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > >On 05/02/15 14:59, DaveA wrote: >> >> Sorry my last message was in html, and indentation trashed . I just installed k9 on my tablet and hadn't yet found the setting for text-only. Let m know if this one is also messed up. >> >> I'd put these Values into a class, and make a list of instances. If >> you're not yet comfortable with that, it would also be possible to >> make a list per "paragraph", and use zip to combine them, as >> already suggested. >> >I also felt that there was something wrong with that long list of >variables. However, I'm new to classes, so I'll need to do some >background reading. Thank you for the pointer. You don't need much class understanding at all for this. Something like: class Job: def __init__(self, retain, srcpath, suffix, syncpath, snappath, ...): self.retain = retain = datetime.timedelta (days = retain) self.srcpath = os.path.join (srcpath, suffix) self.syncpath = os.path.join (.... Notice that in the above method, the object is called self, while in the loop in main it'll be called job, or whatever you use as a loop variable. > >> The class would hold retain, srcpath, syncpath, snappath, etc. And >> your list would have 7 instances of that class currently, >> corresponding to your doc, pic, misc, ... >> >> That list would be THE global, replacing these 35 or so. It would >> be populated something like: >> >> def initialize (worklist=[]): worklist . append (Job (90, >> src_path, "Documents", "documents", "docsnaps") worklist .append >> (Job (90, src_path, "Pictures", ... .... return worklist (Reformatting ) def initialize (worklist=[]): worklist . append (Job (90, src_path, "Documents", "documents", "docsnaps") worklist .append(Job (90, src_path, "Pictures", ... .... return worklist >> >> Now all the joins and globs are done in the Job initializer, just >> once. >> >>> >>> def main(): print("Backing up ", src_path, "/Documents\n", >>> sep='') do_sync(doc_srcpath, doc_syncpath) >>> create_snaps(doc_syncpath, doc_snappath) print("Documents backup >>> completed.") expire_snaps(doc_snaplist, today, doc_retain) >> >> At this point main becomes something like >> def main (): jobs = initialize () for job in jobs: do_sync (job.srcpath, job.syncpath) create_snaps (job.syncpath, job.snappath) expire_snaps (job.snaplist, ... -- Sent from my Android device with K-9 Mail. Please excuse my brevity. From robertvstepp at gmail.com Thu Feb 5 20:22:29 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 5 Feb 2015 13:22:29 -0600 Subject: [Tutor] How to easily recover the current index when using Python-style for loops? In-Reply-To: References: Message-ID: On Thu, Feb 5, 2015 at 12:25 PM, Mark Lawrence wrote: > > We're now at 3.4 with 3.5 close to its first alpha release, so any > particular reason that even 2.6 doesn't seem relevant to you? No axe to > grind, just plain old fashioned curiosity :) > We are not allowed to install or upgrade software on these particular systems. So whatever version of Python came pre-installed is what I have to forever use until they (The people that supply us with these systems.) upgrade the hardware and/or OS. Periodically the treatment planning software gets upgraded, but never any of the other software on the systems unless the planning software upgrade makes use of external software that must be upgraded, too. Unfortunately Python is not one of these! -- boB From alan.gauld at btinternet.com Thu Feb 5 22:54:42 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 05 Feb 2015 21:54:42 +0000 Subject: [Tutor] How to easily recover the current index when using Python-style for loops? In-Reply-To: <54D3B855.7080404@gmail.com> References: <54D3B855.7080404@gmail.com> Message-ID: On 05/02/15 18:37, Timo wrote: > Op 05-02-15 om 18:48 schreef Alan Gauld: >> >> try: >> >> >>> help( enumerate() ) > Should be > > >>> help(enumerate) True, good catch! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Fri Feb 6 01:16:40 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 6 Feb 2015 11:16:40 +1100 Subject: [Tutor] How to easily recover the current index when using Python-style for loops? In-Reply-To: References: Message-ID: <20150206001639.GA2498@ando.pearwood.info> On Thu, Feb 05, 2015 at 11:30:38AM -0600, boB Stepp wrote: > Python 2.4.4, Solaris 10. > > a_list = [item1, item2, item3] > for item in a_list: > print 'Item number', ???, 'is:', item > > Is there an easy, clever, Pythonic way (other than setting up a > counter) to replace ??? with the current index of item in a_list? The easy, clever, Pythonic way *is* to set up a counter. for i, item in enumerate(a_list): ... If you know that the list contains no duplicates, you can (but shouldn't!) do this: for item in a_list: i = a_list.index(item) but really, don't do that. Three problems: it only works with lists and tuples, it fails when there are duplicate items, and it is slow and inefficient. If you test with a small list, say a hundred items, you might not notice how slow and inefficient, but then some day you'll try it on a list with ten million items, and then you will *really* feel the pain. -- Steve From figgypops at hotmail.com Fri Feb 6 00:57:06 2015 From: figgypops at hotmail.com (Edgar Figueroa) Date: Thu, 5 Feb 2015 17:57:06 -0600 Subject: [Tutor] How do I call a variable within an input () function? Message-ID: Hello group. I'm trying to call the variable "name" within my input () function. Here's what I have: name = input("Hello. What's your name? ") print("\nHello", name, ". Nice to meet you.") favFood1 = input("\n", name, ", what's your favorite food? ") Obviously it isn't working. It tells me I have too many arguments for the input () function. Basically, I want the output to read as follows: Hello. What's your name? user enters "Frank" Hello Frank. Nice to meet you. Frank, what's your favorite food? Any help would be greatly appreciated. Thanks. From dyoo at hashcollision.org Fri Feb 6 08:20:04 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 5 Feb 2015 23:20:04 -0800 Subject: [Tutor] How do I call a variable within an input () function? In-Reply-To: References: Message-ID: On Thu, Feb 5, 2015 at 3:57 PM, Edgar Figueroa wrote: > Hello group. I'm trying to call the variable "name" within my input () function. > Here's what I have: > name = input("Hello. What's your name? ") > print("\nHello", name, ". Nice to meet you.") > favFood1 = input("\n", name, ", what's your favorite food? ") > Obviously it isn't working. It tells me I have too many arguments for the input () Try not to paraphrase error messages. Rather, copy-and-paste the error message exactly as the computer says. This might seem counter to what you're used to doing, but it helps because sometimes the slightest detail helps to figure out what's going on. In particular, your program has *two* uses of input. But the error message should have said which one was problematic, and I'm pretty sure it has done so! But since you've paraphrased the message, we would not be able to tell which one was broken, even if the error message said exactly which one was wrong. *That's* why you should avoid paraphrasing error messages. In any case, since there's only two, we can look and see that the problematic one is probably this: favFood1 = input("\n", name, ", what's your favorite food? ") You want to pass input() a single string. But you have a few strings there. Do you know about "string appending" or "string concatenation"? From alan.gauld at btinternet.com Fri Feb 6 08:21:33 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 06 Feb 2015 07:21:33 +0000 Subject: [Tutor] How do I call a variable within an input () function? In-Reply-To: References: Message-ID: On 05/02/15 23:57, Edgar Figueroa wrote: > name = input("Hello. What's your name? ") > print("\nHello", name, ". Nice to meet you.") > favFood1 = input("\n", name, ", what's your favorite food? ") > Obviously it isn't working. You need to construct a single string argument. There are several options: "\n" + name + ", what's your favorite food? " Or, better IMHO, use string formatting: "\n {}, what's your favorite food? ".format(name) formatting has the advantage of allowing you to insert multiple values of different types and control spacing, justification and other aspects of appearance. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From davea at davea.name Fri Feb 6 08:29:50 2015 From: davea at davea.name (DaveA) Date: Fri, 06 Feb 2015 07:29:50 +0000 Subject: [Tutor] How do I call a variable within an input () function? In-Reply-To: References: Message-ID: <56FCB0A7-FBDD-4384-9263-CD82073C33A0@davea.name> On February 5, 2015 6:57:06 PM EST, Edgar Figueroa wrote: >Hello group. I'm trying to call the variable "name" within my input () You're not needing to call it, but to use it. The simplest answer is just to print the prompt separately, and just call input (). Next option is to build a string in another variable, like prompt= and then do input (prompt) But there's no reason you can't just pass a single string expression directly to input. Something like X = input (name + ", what's your favorite food? ") Now input gets exactly one argument. >function. >Here's what I have: >name = input("Hello. What's your name? ") >print("\nHello", name, ". Nice to meet you.") >favFood1 = input("\n", name, ", what's your favorite food? ") >Obviously it isn't working. It tells me I have too many arguments for >the input () function. Basically, I want the output to read as >follows: >Hello. What's your name? >user enters "Frank" >Hello Frank. Nice to meet you. >Frank, what's your favorite food? >Any help would be greatly appreciated. >Thanks. >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >https://mail.python.org/mailman/listinfo/tutor -- Sent from my Android device with K-9 Mail. Please excuse my brevity. From linux at barrowhillfarm.org.uk Fri Feb 6 10:25:23 2015 From: linux at barrowhillfarm.org.uk (Bob Williams) Date: Fri, 06 Feb 2015 09:25:23 +0000 Subject: [Tutor] Nested for loops, possibly? In-Reply-To: References: <54D36FC1.5070800@barrowhillfarm.org.uk> <5C17E4E2-69AC-40F4-9B5B-F7DD55B10D23@davea.name> <54D3A984.8050704@barrowhillfarm.org.uk> Message-ID: <54D48883.30509@barrowhillfarm.org.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 05/02/15 18:46, DaveA wrote: > You don't need much class understanding at all for this. Something > like: > > class Job: def __init__(self, retain, srcpath, suffix, syncpath, > snappath, ...): self.retain = retain = datetime.timedelta (days = > retain) self.srcpath = os.path.join (srcpath, suffix) self.syncpath > = os.path.join (.... > > Notice that in the above method, the object is called self, while > in the loop in main it'll be called job, or whatever you use as a > loop variable. > >>> >>>>> The class would hold retain, srcpath, syncpath, snappath, >>>>> etc. And your list would have 7 instances of that class >>>>> currently, corresponding to your doc, pic, misc, ... >>>>> >>>>> That list would be THE global, replacing these 35 or so. It >>>>> would be populated something like: >>>>> >>>>> def initialize (worklist=[]): worklist . append (Job (90, >>>>> src_path, "Documents", "documents", "docsnaps") worklist >>>>> .append (Job (90, src_path, "Pictures", ... .... return >>>>> worklist > (Reformatting ) > > def initialize (worklist=[]): worklist . append (Job (90, > src_path, "Documents", "documents", "docsnaps") worklist > .append(Job (90, src_path, "Pictures", ... .... return worklist > >>>>> >>>>> Now all the joins and globs are done in the Job >>>>> initializer, just once. >>>>> > > >>>>>>> >>>>>>> def main(): print("Backing up ", src_path, >>>>>>> "/Documents\n", sep='') do_sync(doc_srcpath, >>>>>>> doc_syncpath) create_snaps(doc_syncpath, doc_snappath) >>>>>>> print("Documents backup completed.") >>>>>>> expire_snaps(doc_snaplist, today, doc_retain) >>>>> >>>>> At this point main becomes something like >>>>> > def main (): jobs = initialize () for job in jobs: do_sync > (job.srcpath, job.syncpath) create_snaps (job.syncpath, > job.snappath) expire_snaps (job.snaplist, ... > Thanks, that formatted nicely, and is a nice clear explanation. Bob - -- Bob Williams System: Linux 3.16.7-7-desktop Distro: openSUSE 13.2 (x86_64) with KDE Development Platform: 4.14.3 Uptime: 06:00am up 7:55, 3 users, load average: 0.16, 0.05, 0.06 -----BEGIN PGP SIGNATURE----- Version: GnuPG v2 iEYEARECAAYFAlTUiIIACgkQ0Sr7eZJrmU6arwCfXABX41NotsGViaEuozzqRJG1 UUUAmwd8zbZO1uOQuCTSoyDxt/kTx/yB =RkjX -----END PGP SIGNATURE----- From steve at pearwood.info Fri Feb 6 08:28:11 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 6 Feb 2015 18:28:11 +1100 Subject: [Tutor] How do I call a variable within an input () function? In-Reply-To: References: Message-ID: <20150206072810.GE2498@ando.pearwood.info> On Thu, Feb 05, 2015 at 05:57:06PM -0600, Edgar Figueroa wrote: > Hello group. I'm trying to call the variable "name" within my input () function. > Here's what I have: > name = input("Hello. What's your name? ") *Your* input function? Is that different from the standard input function? Are you using Python 2 or Python 3, because the standard input function is different between the two. You should use input() is Python 3, but raw_input() in Python 2. > print("\nHello", name, ". Nice to meet you.") > favFood1 = input("\n", name, ", what's your favorite food? ") > Obviously it isn't working. It tells me I have too many arguments for the input () function. Basically, I want the output to read as follows: Nothing is "obvious" in programming :-) Rather than summarise the error, please copy and paste the full traceback: py> input("Frank", "what's your favourite food?") Traceback (most recent call last): File "", line 1, in TypeError: input expected at most 1 arguments, got 2 If you are talking about the standard input function in Python 3, then you need a single string argument. You have two strings (ignoring the "\n" which is unneeded). How do you get one string from two? Here are four ways: py> name = "Frank" py> name + ", what's your favourite food?" # String concatenation. "Frank, what's your favourite food?" py> "%s, what's your favourite food?" % name # String interpolation. "Frank, what's your favourite food?" py> "{}, what's your favourite food?".format(name) # format method. "Frank, what's your favourite food?" py> from string import Template # String templating. py> tmpl = Template("$name, what's your favourite food?") py> tmpl.safe_substitute(name=name) "Frank, what's your favourite food?" Take your pick, for this case they will all be about as good as the others. I would normally choose % interpolation. -- Steve From breamoreboy at yahoo.co.uk Fri Feb 6 15:56:11 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 06 Feb 2015 14:56:11 +0000 Subject: [Tutor] How do I call a variable within an input () function? In-Reply-To: References: Message-ID: On 06/02/2015 07:20, Danny Yoo wrote: > On Thu, Feb 5, 2015 at 3:57 PM, Edgar Figueroa wrote: >> Hello group. I'm trying to call the variable "name" within my input () function. >> Here's what I have: >> name = input("Hello. What's your name? ") >> print("\nHello", name, ". Nice to meet you.") >> favFood1 = input("\n", name, ", what's your favorite food? ") >> Obviously it isn't working. It tells me I have too many arguments for the input () > > Try not to paraphrase error messages. Rather, copy-and-paste the > error message exactly as the computer says. This might seem counter > to what you're used to doing, but it helps because sometimes the > slightest detail helps to figure out what's going on. > > In particular, your program has *two* uses of input. But the error > message should have said which one was problematic, and I'm pretty > sure it has done so! But since you've paraphrased the message, we > would not be able to tell which one was broken, even if the error > message said exactly which one was wrong. *That's* why you should > avoid paraphrasing error messages. > > In any case, since there's only two, we can look and see that the > problematic one is probably this: > > favFood1 = input("\n", name, ", what's your favorite food? ") > > You want to pass input() a single string. But you have a few strings there. > > Do you know about "string appending" or "string concatenation"? > String formatting should also be mentioned, old style using the % operator as in C or new style using {} and format. favFood1 = input("\n%s what's your favorite food? " % name) favFood1 = input("\n{} what's your favorite food? ".format(name)) I much prefer the latter as I find it far more flexible. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From cwood1121 at gmail.com Sat Feb 7 23:36:41 2015 From: cwood1121 at gmail.com (Conner Wood) Date: Sat, 7 Feb 2015 16:36:41 -0600 Subject: [Tutor] Need help writing code with python Message-ID: I fell behind 2 weeks in my class due to surgery and have a coding project due tonight (Saturday, Feb. 7). I've attached my project to this email. Please help! Also, I'm using a Mac laptop if that helps in anyway. Please get back to me as soon as you can. Thanks, Conner Wood From ben+python at benfinney.id.au Sun Feb 8 09:54:24 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 08 Feb 2015 19:54:24 +1100 Subject: [Tutor] Need help writing code with python References: Message-ID: <85d25keqbj.fsf@benfinney.id.au> Conner Wood writes: > I fell behind 2 weeks in my class due to surgery and have a coding > project due tonight (Saturday, Feb. 7). I've attached my project to > this email. My sympathies with your situation, I hope your surgery was successful and you are in good health. This is not a forum for doing your project; you will need to do your own project. Rather, this is a forum for publicly discussing much more focussed topics. We tutor each other in learning Python and its idioms and ecosystem. We don't do one-on-one tutoring, and we don't do coding for you. If you have a *small* portion of code that demonstrates some behaviour that confuses you, we can talk you through the confusion (provided the code can also behave the same for us, and provided we know what you expected from that code). If you have a large project, you'll need to do the work, or get some largesse from the people expecting that work. It seems you have an entirely valid reason to ask for a time extension. Good hunting! -- \ ?I knew things were changing when my Fraternity Brothers threw | `\ a guy out of the house for mocking me because I'm gay.? | _o__) ?postsecret.com, 2010-01-19 | Ben Finney From alan.gauld at btinternet.com Sun Feb 8 09:54:32 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 08 Feb 2015 08:54:32 +0000 Subject: [Tutor] Need help writing code with python In-Reply-To: References: Message-ID: On 07/02/15 22:36, Conner Wood wrote: > I fell behind 2 weeks in my class due to surgery and have a coding project > due tonight (Saturday, Feb. 7). I've attached my project to this email. > Please help! Also, I'm using a Mac laptop if that helps in anyway. Please > get back to me as soon as you can. First. We won't do homework for you so we need to see what you have done. You need to have made some kind of attempt. Or at least have some specific questions. Second Asking for a response on the day that the assignment is due on a mailing list isn't going to work, it didn't get here until Sunday. I hope you got something done on Saturday but you need to give a mailing list a bit more notice. Email can take up to 24 hours to reach its destination, never assume it will be quicker than that (even if 99% of the time it is). Third, The attachment didn't get here. So I've no idea what your assignment was. Its usually better to copy the text into the mail body. Fourth. Please give more than the fact you've got a Mac. So have I; its an old iBook that runs MacOS 10.4 on a 600MHz PowerPC chip. I suspect that's quite different to yours. Tell us the OS version and the Python version you are using. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From davea at davea.name Sun Feb 8 09:55:56 2015 From: davea at davea.name (Dave Angel) Date: Sun, 08 Feb 2015 03:55:56 -0500 Subject: [Tutor] Need help writing code with python In-Reply-To: References: Message-ID: <54D7249C.4080808@davea.name> On 02/07/2015 05:36 PM, Conner Wood wrote: > I fell behind 2 weeks in my class due to surgery and have a coding project > due tonight (Saturday, Feb. 7). I've attached my project to this email. > Please help! Also, I'm using a Mac laptop if that helps in anyway. Please > get back to me as soon as you can. > Welcome to Python-tutor. This seems to be your first post. Thanks for making it a text email. And for mentioning your OS. But you also should be specifying the Python version. There's no attachment to your message in the mailing list. And many people here can't see attachments anyway. If your project is too big to include directly in your email message, you may be out of luck. How big a project is it, and how much of it have you been able to do so far? Is there some particular problem that has you stumped? We're here to help you get past some sticking point, not to do your assignment for you. I'd expect your prof would give you an extension if you can't get it in because of unexpected surgery. -- DaveA From ben+python at benfinney.id.au Sun Feb 8 10:02:17 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 08 Feb 2015 20:02:17 +1100 Subject: [Tutor] Need help writing code with python References: Message-ID: <858ug8epye.fsf@benfinney.id.au> Alan Gauld writes: > Third, > The attachment didn't get here. So I've no idea what your assignment > was. Its usually better to copy the text into the mail body. Given that the attachment was described as ?my project?, I would advise not sending it here in any form. Copy text here if it's *small*, and *focussed*, and relevant to some part of the discussion. If the text is ?my project?, it's better not put here at all. I am glad the attachment was discarded, it sounds like sending it to all recipients of this forum would have been only an annoyance. Conner, please obtain the time to do the project unhurried; then, feel free to come to this forum with *focussed* questions on aspects of the Python code you are writing. We don't need to see the project. -- \ ?I find the whole business of religion profoundly interesting. | `\ But it does mystify me that otherwise intelligent people take | _o__) it seriously.? ?Douglas Adams | Ben Finney From shawnbyers47 at gmail.com Mon Feb 9 00:01:52 2015 From: shawnbyers47 at gmail.com (Shawn Byers) Date: Sun, 8 Feb 2015 18:01:52 -0500 Subject: [Tutor] Explanation of this print statement Message-ID: Hello I was wondering if someone could explain this print statement for r in range(6,0,-1): print((6-r)*''+r*'o') From alan.gauld at btinternet.com Mon Feb 9 01:19:23 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 09 Feb 2015 00:19:23 +0000 Subject: [Tutor] Explanation of this print statement In-Reply-To: References: Message-ID: On 08/02/15 23:01, Shawn Byers wrote: > Hello I was wondering if someone could explain this print statement > > for r in range(6,0,-1): > print((6-r)*''+r*'o') Have you tried running it? Do you see what it is doing? Try evaluating range(6,0,-1) at the interpreter (you may want to convert it to a list) to see what it does. >>> print( list(range(6,0,-1)) ) Try substituting values for (6-r) and see what string results you get for each value. eg >>> print(6 * '' + 0 * 'o') >>> print(0 * '' + 6 * 'o') >>> print(3 * '' + 3 * 'o') >>> print(3 * '' + 4 * 'o') >>> etc In other words, experiment in the >>> interpreter. That's what it's there for. And its quicker than sending an email and waiting for a reply (which may not cover the bit you want to understand anyway). Then if there's still something you don't understand come back and ask us about that specific aspect. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Mon Feb 9 01:46:07 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 09 Feb 2015 00:46:07 +0000 Subject: [Tutor] Explanation of this print statement In-Reply-To: References: Message-ID: On 09/02/2015 00:19, Alan Gauld wrote: > On 08/02/15 23:01, Shawn Byers wrote: >> Hello I was wondering if someone could explain this print statement >> >> for r in range(6,0,-1): >> print((6-r)*''+r*'o') > > Have you tried running it? > Do you see what it is doing? > > Try evaluating range(6,0,-1) at the interpreter (you may want to convert > it to a list) to see what it does. > > >>> print( list(range(6,0,-1)) ) > > Try substituting values for (6-r) and see what string > results you get for each value. > eg > >>> print(6 * '' + 0 * 'o') > >>> print(0 * '' + 6 * 'o') > >>> print(3 * '' + 3 * 'o') > >>> print(3 * '' + 4 * 'o') > >>> etc > > In other words, experiment in the >>> interpreter. That's > what it's there for. And its quicker than sending an email > and waiting for a reply (which may not cover the bit you > want to understand anyway). > > Then if there's still something you don't understand come > back and ask us about that specific aspect. > If it is a print statement the brackets are not needed, otherwise it's either the Python 3 or (Python 2 with from __future__ import print_function) print function. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From davea at davea.name Mon Feb 9 02:00:19 2015 From: davea at davea.name (Dave Angel) Date: Sun, 08 Feb 2015 20:00:19 -0500 Subject: [Tutor] Explanation of this print statement In-Reply-To: References: Message-ID: <54D806A3.7040300@davea.name> On 02/08/2015 06:01 PM, Shawn Byers wrote: > Hello I was wondering if someone could explain this print statement > > for r in range(6,0,-1): > print((6-r)*''+r*'o') You probably intended to have a blank between the first two single-quotes. for r in range(6,0,-1): print((6-r)*' '+r*'o') Perhaps it'd be more interesting to put some other character in the quotes: for r in range(6,0,-1): print( (6-r)*'X' + r*'o' ) -- DaveA From rakeshsharma14 at hotmail.com Mon Feb 9 08:20:23 2015 From: rakeshsharma14 at hotmail.com (rakesh sharma) Date: Mon, 9 Feb 2015 12:50:23 +0530 Subject: [Tutor] Creating a pojo in python Message-ID: How can one create a POJO in python.I mean a class like this class A { private a; private b; public getA() { return a; } public getB() { return b }} I tried creating class in python but the variables were accessible as public data members. Any help? From dyoo at hashcollision.org Mon Feb 9 08:44:15 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 8 Feb 2015 23:44:15 -0800 Subject: [Tutor] Creating a pojo in python In-Reply-To: References: Message-ID: On Feb 8, 2015 11:21 PM, "rakesh sharma" wrote: > > How can one create a POJO in python.I mean a class like this > class A { private a; private b; public getA() { return a; } public getB() { return b }} > I tried creating class in python but the variables were accessible as public data members. The acronym POJO stands for "plain old Java object", so technically speaking, Python style won't encourage what you're trying. Traditionally, if you add an underscore as a prefix to your field name, other programmers are supposed to pretend that it is private. This is conventional. If you are an advanced user, you can look into properties which can be used to lock down access more thoroughly. But for most users, using the underscore convention is enough. Can you explain more why you are trying to do a POJO? In Java, POJOs are used because of the desire to manage the access to data exclusively through method calls. But we can get this in Python with properties, without doing the exact same thing as Java. From alan.gauld at btinternet.com Mon Feb 9 10:20:55 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 09 Feb 2015 09:20:55 +0000 Subject: [Tutor] Creating a pojo in python In-Reply-To: References: Message-ID: On 09/02/15 07:20, rakesh sharma wrote: > How can one create a POJO in python.I mean a class like this > class A { private a; private b; public getA() { return a; } public getB() { return b }} > I tried creating class in python but the variables were accessible as public data members. First you have to answer the question "why do you want to hide your data attributes, only to expose them via getters?" If you have a good and legitimate reason for doing that then Python has mechanisms for doing it, but they are quite rarely used, since there are few cases where you really need to do that. Python's style says that we are all adults and can be trusted to behave responsibly so we don't need to make all attributes private. Of course you should still design your classes after good OOP principles so data attributes are mainly there to support object behaviour. As such, most object access will be via methods. But that should be true in Java too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Mon Feb 9 17:08:34 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 09 Feb 2015 16:08:34 +0000 Subject: [Tutor] Creating a pojo in python In-Reply-To: References: Message-ID: On 09/02/2015 07:20, rakesh sharma wrote: > How can one create a POJO in python.I mean a class like this > class A { private a; private b; public getA() { return a; } public getB() { return b }} > I tried creating class in python but the variables were accessible as public data members. > Any help? Further to the answers from Alan Gauld and Danny Yoo I suggest that you read http://dirtsimple.org/2004/12/python-is-not-java.html and http://dirtsimple.org/2004/12/java-is-not-python-either.html -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From davea at davea.name Mon Feb 9 17:50:39 2015 From: davea at davea.name (Dave Angel) Date: Mon, 09 Feb 2015 11:50:39 -0500 Subject: [Tutor] Creating a pojo in python In-Reply-To: References: Message-ID: <54D8E55F.5050309@davea.name> On 02/09/2015 02:20 AM, rakesh sharma wrote: > How can one create a POJO in python.I mean a class like this > class A { private a; private b; public getA() { return a; } public getB() { return b }} > I tried creating class in python but the variables were accessible as public data members. > Any help? The other respondents so far (Danny, Alan, and Mark) are right on. But there are times when you might want APPROXIMATELY what you call POJO in Python. Obviously you wouldn't want exactly that, since that class is totally useless. Without any setters or constructor, those class members cannot be initialized to any value. (I don't know if java has the equivalent of C++ friends, or whether derived classes could change those private values, so I may be wrong here) So the real question is why DO you want the Python version of this. If it's because your teacher is trying to make some point, and assigned you to figure this out, then try using the @property decorator on the get function. Naturally, the get function is called a, and the private data is _a_hidden_attribute_that_you_dont_want_the_caller_to_use The public interface of that class is then just the same as though the class had a and b attributes, except that writing to those will give a runtime error. If it's because you have a bunch of code that you already transliterated from java, and it uses this class you haven't written yet, then my sympathies. I've been there, and the cure is to go back to all those uses, and change each function call of the form: obj.getA() to obj.a If all that code was transliterated by somebody else, and you're not allowed to mess with it, then go back to the teacher example. -- DaveA From bw_dw at fastmail.fm Mon Feb 9 19:03:19 2015 From: bw_dw at fastmail.fm (dw) Date: Mon, 09 Feb 2015 10:03:19 -0800 Subject: [Tutor] Wondering if there is a print in location command for terminal? Message-ID: <1423504999.3061859.225202593.2754E3BD@webmail.messagingengine.com> Hi Python Gang, In the olden days of Basic, there was a "Locate" command to locate strings in specific x/y locations on the terminal. For example: Locate 9,10:print "THE POWER OF PYTHON" Would count down from top of terminal 9 increments. And the count (from left to right of terminal) 10 spaces. Then print the string there. I wonder if what I'm looking for is the "Curses" library? I'm running Python 2.6 in Linux and 2.7 in Window. Thanks! dw :-] -- Bw_dw at fastmail.net From alan.gauld at btinternet.com Tue Feb 10 01:40:49 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Feb 2015 00:40:49 +0000 Subject: [Tutor] Wondering if there is a print in location command for terminal? In-Reply-To: <1423504999.3061859.225202593.2754E3BD@webmail.messagingengine.com> References: <1423504999.3061859.225202593.2754E3BD@webmail.messagingengine.com> Message-ID: On 09/02/15 18:03, dw wrote: > Hi Python Gang, > In the olden days of Basic, there was a "Locate" command to locate > strings in specific x/y locations on the terminal. > > For example: > Locate 9,10:print "THE POWER OF PYTHON" > Would count down from top of terminal 9 increments. > And the count (from left to right of terminal) 10 spaces. > Then print the string there. > > I wonder if what I'm looking for is the "Curses" library? > I'm running Python 2.6 in Linux and 2.7 in Window. Yes curses is probably the best fit here. It doesn't work so well on Windows but on Linux/MacOS it does a good job. Just remember that Terminals come in all sorts of shapes and sizes so curses can only do its best to adjust things. There are some other library packages that emulate the old DOS conio package and include x/y coordinate location, but they often require ANSI.SYS or similar to be installed. And they are all third party rather than being standard library items like curses. There are lots of curses tutorials out there. The C ones should be quite usable since the curses calls are pretty much a straight mapping to the C library. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From eryksun at gmail.com Tue Feb 10 04:48:35 2015 From: eryksun at gmail.com (eryksun) Date: Mon, 9 Feb 2015 21:48:35 -0600 Subject: [Tutor] Wondering if there is a print in location command for terminal? In-Reply-To: References: <1423504999.3061859.225202593.2754E3BD@webmail.messagingengine.com> Message-ID: On Mon, Feb 9, 2015 at 6:40 PM, Alan Gauld wrote: > > Yes curses is probably the best fit here. It doesn't work > so well on Windows but on Linux/MacOS it does a good job. curses for Windows (based on PDCurses): http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses > There are some other library packages that emulate the > old DOS conio package and include x/y coordinate location, The msvcrt module wraps the conio functions kbhit, getch, getche, ungetch, and putch (plus the [w]ide alternatives). > but they often require ANSI.SYS or similar to be installed. That's the old-school DOS driver. For Windows try ANSICON. It injects ANSI32.DLL or ANSI64.DLL to hook WriteConsole and WriteFile. https://github.com/adoxa/ansicon From alan.gauld at btinternet.com Tue Feb 10 10:02:01 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Feb 2015 09:02:01 +0000 Subject: [Tutor] Wondering if there is a print in location command for terminal? In-Reply-To: References: <1423504999.3061859.225202593.2754E3BD@webmail.messagingengine.com> Message-ID: On 10/02/15 03:48, eryksun wrote: > On Mon, Feb 9, 2015 at 6:40 PM, Alan Gauld wrote: > > curses for Windows (based on PDCurses): > http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses I've tried this but several iof the functions didn't work consistently. Of course it might just be my set up or something but I wasn't overly impressed. >> There are some other library packages that emulate the >> old DOS conio package and include x/y coordinate location, > > The msvcrt module wraps the conio functions kbhit, getch, getche, > ungetch, and putch (plus the [w]ide alternatives). msvcrt wraps the Microsoft Vis C Runtime functions which don't include positional commands. Conio was a DOS library developed by the compiler makers as a way to access the BIOS calls and has a gotoXY() and similar functions. It first appeared, as I recall, in Turbo Pascal but was later picked up by the C compilers as well. There are at least 2 libraries on PyPi that simulate conio >> but they often require ANSI.SYS or similar to be installed. > > That's the old-school DOS driver. For Windows try ANSICON. It injects > ANSI32.DLL or ANSI64.DLL to hook WriteConsole and WriteFile. I'll need to look those up. New to me, thanks for the pointer. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From eryksun at gmail.com Tue Feb 10 15:29:56 2015 From: eryksun at gmail.com (eryksun) Date: Tue, 10 Feb 2015 08:29:56 -0600 Subject: [Tutor] Wondering if there is a print in location command for terminal? In-Reply-To: References: <1423504999.3061859.225202593.2754E3BD@webmail.messagingengine.com> Message-ID: On Tue, Feb 10, 2015 at 3:02 AM, Alan Gauld wrote: > msvcrt wraps the Microsoft Vis C Runtime functions which don't > include positional commands. > > Conio was a DOS library developed by the compiler makers as a way to access > the BIOS calls and has a gotoXY() and similar functions. It first appeared, > as I recall, in Turbo Pascal but was later picked > up by the C compilers as well. > There are at least 2 libraries on PyPi that simulate conio OK, the only conio I was aware of was the conio.h API provided by various C runtime libraries on Windows, as described here: https://en.wikipedia.org/wiki/Conio.h From siya at goodhost.co.za Tue Feb 10 17:29:46 2015 From: siya at goodhost.co.za (Siya Radebe) Date: Tue, 10 Feb 2015 18:29:46 +0200 Subject: [Tutor] Timeline Script in Python Message-ID: <4AF81C6C-BB16-4278-91E7-A70010D1A51D@goodhost.co.za> Hi, Can you please help with a timeline script in python, in conjunction with how to use their timeline library? I would love advise of how to best approach this, in going about developing an event/ activity stream timeline I found two different libraries, one from Python, and other from Django which is best, and how do i go about developing the script to show a timeline of events? https://pypi.python.org/pypi/timeline/0.0.1 https://pypi.python.org/pypi/django-admin-timeline Looking forward to your favorable response Kind Regards, Siya From alan.gauld at btinternet.com Tue Feb 10 19:59:15 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Feb 2015 18:59:15 +0000 Subject: [Tutor] Timeline Script in Python In-Reply-To: <4AF81C6C-BB16-4278-91E7-A70010D1A51D@goodhost.co.za> References: <4AF81C6C-BB16-4278-91E7-A70010D1A51D@goodhost.co.za> Message-ID: On 10/02/15 16:29, Siya Radebe wrote: > Hi, > > Can you please help with a timeline script in python, in conjunction with how to use their timeline library? > Thus list is for those learning the Python language and its standard library. Any information about third party modules will depend on whether anyone here has used it, usually you are better asking on a dedicated forum (or via email to the author) Django has a user forum, the PyPI package may not. > I would love advise of how to best approach this, in going about developing an event/ activity stream timeline I think you need to be more specific about what you want to do. Are you building it in real-time or from a database analysis? What volume of events do you need to deal with? etc... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From ankos at live.com Wed Feb 11 04:37:28 2015 From: ankos at live.com (Andrew K.) Date: Tue, 10 Feb 2015 22:37:28 -0500 Subject: [Tutor] Asking for help with installation of pyttsx (text to speech) Message-ID: To whom it may concern. I started the project CrocToy, a complex robotic toy in a form of a crocodile. I would like to use Python as programming platform. Having limited programming skills, I have troubles with software development. Particularly, right now I try to learn how to use pyttsx (text to speech). I would be very grateful for any help with installation and programming. Thank you very much, Andrew PS I would be very thankful if any mature Python programmer would like to participate in my project. Thank you, Andrew From daaqou at gmail.com Wed Feb 11 03:39:50 2015 From: daaqou at gmail.com (daaku gee) Date: Tue, 10 Feb 2015 18:39:50 -0800 Subject: [Tutor] Importing from classes Message-ID: Hi When importing from other modules, I've seen syntax like: import from import And another one: import from as Is one better than the other or is it just personal choice? Thanks \d From alan.gauld at btinternet.com Wed Feb 11 10:24:27 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Feb 2015 09:24:27 +0000 Subject: [Tutor] Asking for help with installation of pyttsx (text to speech) In-Reply-To: References: Message-ID: On 11/02/15 03:37, Andrew K. wrote: > I started the project CrocToy, a complex robotic toy in a form of a crocodile. > I would like to use Python as programming platform. > Having limited programming skills, I have troubles with software development. This much we can help with since the list is here for those learning Python and programming in general. > Particularly, right now I try to learn how to use pyttsx (text to speech). But we do limit ourselves to the standard library modules so for anything else you will be gambling on somebody here already having used it. Usually you are better sending module specific queries to the module support forum (or the author.) > I would be very grateful for any help with installation and programming. Do you have any specific queries? The more specific the query the more specific the answer will be. Please include details of your OS and Python version. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Feb 11 10:32:02 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Feb 2015 09:32:02 +0000 Subject: [Tutor] Importing from classes In-Reply-To: References: Message-ID: On 11/02/15 02:39, daaku gee wrote: > When importing from other modules, I've seen syntax like: > > import from from import Note you don't import classes from modules you import names. (The name might be the name of a class of course!) This form is for cases where you only want to use one or two features of a module and don't want to have the inconvenience of typing the module name in front each time you use them. > import This is the normal usage. It gives you indirect access to all of the module features using the . notation > import from as import as or from import as These tend to be used where the module has a very long name that you don't want to type out in full each time, so you give it a shorter alias. You might also use it if you are working on code that already has a variable with the same name as the module/feature that you want to import. You either rename all your variable references or you choose an alias that does not conflict. > Is one better than the other or is it just personal choice? 'better' is often a subjective term. There are reasons for each as described above. What is best depends on the circumstance. If in doubt use import HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Wed Feb 11 11:18:17 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 11 Feb 2015 21:18:17 +1100 Subject: [Tutor] Importing from classes In-Reply-To: References: Message-ID: <20150211101817.GZ2498@ando.pearwood.info> On Tue, Feb 10, 2015 at 06:39:50PM -0800, daaku gee wrote: > Hi > > When importing from other modules, I've seen syntax like: > > import from > import > > And another one: > import from as Not quite. The syntax is: import import as from import # not necessarily a class from import as > Is one better than the other or is it just personal choice? As far as Python is concerned, there is no difference at all. The "as name" version just lets you pick a different name, usually to save typing: import module_with_a_really_long_name as module Obviously the usual rule for naming things applies here too: names should be meaningful, they should not lie, or be confusing: # Bad ideas. import math as string # What? import string as fred import os as barney Beware of names which are easily confused, or have common meanings: - try to avoid `l` and `I` because in some fonts they look like 1 - same for `O` and 0 - i is normally used for for-loop counters and other integers - n is also used for integers - x and y for floats But apart from that, the names you choose are entirely up to you. -- Steve From robertvstepp at gmail.com Wed Feb 11 14:27:30 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Wed, 11 Feb 2015 07:27:30 -0600 Subject: [Tutor] How to pass varying number of arguments to functions called by a dictionary? Message-ID: Python 2.4.4, Solaris 10 I have a file of functions. Based on what is read in a data file, different functions in the file of functions will need to be called. I have been trying to make the following approach work, so far unsuccessfully as, in general, each function may have a different number of arguments that might have to be passed to it. def func1(x1, x2, x3): pass def func2(y1, y2): pass def func3(z): pass call_fcn = {'a': func1, 'b': func2, 'c': func3} call_fcn[key_letter](???) How can I successfully pass the needed arguments needed for each possible function with this approach? I naively tried to do something like: pass_args = {'a': (x1, x2, x3), 'b': (y1, y2), 'c': (z)} call_fcn[key_letter](key_letter) But ran into the syntax error that I was giving one argument when (possibly) multiple arguments are expected. Is what I am trying to do a viable approach that can be made to work? Otherwise, I will brute-force my way through with if-elif-else statements. Thanks! -- boB From joel.goldstick at gmail.com Wed Feb 11 15:23:15 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 11 Feb 2015 09:23:15 -0500 Subject: [Tutor] How to pass varying number of arguments to functions called by a dictionary? In-Reply-To: References: Message-ID: On Wed, Feb 11, 2015 at 8:27 AM, boB Stepp wrote: > Python 2.4.4, Solaris 10 > > I have a file of functions. Based on what is read in a data file, > different functions in the file of functions will need to be called. I > have been trying to make the following approach work, so far > unsuccessfully as, in general, each function may have a different > number of arguments that might have to be passed to it. > > def func1(x1, x2, x3): > pass > > def func2(y1, y2): > pass > > def func3(z): > pass > > call_fcn = {'a': func1, 'b': func2, 'c': func3} > > call_fcn[key_letter](???) > > How can I successfully pass the needed arguments needed for each > possible function with this approach? I naively tried to do something > like: > > pass_args = {'a': (x1, x2, x3), 'b': (y1, y2), 'c': (z)} > call_fcn[key_letter](key_letter) > > But ran into the syntax error that I was giving one argument when > (possibly) multiple arguments are expected. > > Is what I am trying to do a viable approach that can be made to work? > Otherwise, I will brute-force my way through with if-elif-else > statements. > > Thanks! > > First, its best to cut and paste your code along with the traceback for the errors you got. You might want to look up python *args and *kwargs. > -- > boB > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From eryksun at gmail.com Wed Feb 11 15:44:53 2015 From: eryksun at gmail.com (eryksun) Date: Wed, 11 Feb 2015 08:44:53 -0600 Subject: [Tutor] How to pass varying number of arguments to functions called by a dictionary? In-Reply-To: References: Message-ID: On Wed, Feb 11, 2015 at 7:27 AM, boB Stepp wrote: > > pass_args = {'a': (x1, x2, x3), 'b': (y1, y2), 'c': (z)} > call_fcn[key_letter](key_letter) > > But ran into the syntax error that I was giving one argument when > (possibly) multiple arguments are expected. Do it like this: pass_args = { 'a': (x1, x2, x3), 'b': (y1, y2), 'c': (z,), } call_fcn[key_letter](*pass_args[key_letter]) Note the 'c' tuple is written as (z,). A comma is required to create a tuple. Also note the call uses the "* expression" syntax to merge an iterable with the call's positional arguments. For example, f(x0, *(x1,x2,x3)) is equivalent to f(x0, x1, x2, x3). Refer to the glossary definition of "argument", and for a more detailed discussion, see the section on calls in the language reference. https://docs.python.org/2/glossary.html#term-argument https://docs.python.org/2/reference/expressions.html#calls From davea at davea.name Wed Feb 11 15:45:53 2015 From: davea at davea.name (Dave Angel) Date: Wed, 11 Feb 2015 09:45:53 -0500 Subject: [Tutor] How to pass varying number of arguments to functions called by a dictionary? In-Reply-To: References: Message-ID: <54DB6B21.1030002@davea.name> On 02/11/2015 08:27 AM, boB Stepp wrote: > Python 2.4.4, Solaris 10 > > I have a file of functions. Based on what is read in a data file, > different functions in the file of functions will need to be called. I > have been trying to make the following approach work, so far > unsuccessfully as, in general, each function may have a different > number of arguments that might have to be passed to it. > > def func1(x1, x2, x3): > pass > > def func2(y1, y2): > pass > > def func3(z): > pass > > call_fcn = {'a': func1, 'b': func2, 'c': func3} > > call_fcn[key_letter](???) > > How can I successfully pass the needed arguments needed for each > possible function with this approach? I naively tried to do something > like: > > pass_args = {'a': (x1, x2, x3), 'b': (y1, y2), 'c': (z)} > call_fcn[key_letter](key_letter) > > But ran into the syntax error that I was giving one argument when > (possibly) multiple arguments are expected. > > Is what I am trying to do a viable approach that can be made to work? > Otherwise, I will brute-force my way through with if-elif-else > statements. > > Thanks! > Sure, it's viable, but the best approach depends on your goal (use case), and your restrictions. Are these functions really totally unrelated to each other? You not only don't have the same number of arguments, but the values don't even have anything in common? There's an implied constraint that you're not permitted to change the functions. Are you really constrained to only change the caller? Assuming that you seriously want to be able to do this, the only use case I can imagine are: 1) you're writing an interpreter 2) you're interfacing some network channel, where something at the opposite end is sending you messages that you have to turn into local function calls, and return results. A kind of RPC. In each case, there are probably better ways. But you want this way, so here goes: (code is untested) pass_arg_dictionary = {'a': (x1, x2, x3), 'b': (y1, y2), 'c': (z)} pass_args = pass_arg_dictionary[key_letter] #a list call_fcn[key_letter]( *pass_args ) -- DaveA From robertvstepp at gmail.com Wed Feb 11 16:16:40 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Wed, 11 Feb 2015 09:16:40 -0600 Subject: [Tutor] How to pass varying number of arguments to functions called by a dictionary? In-Reply-To: References: Message-ID: On Wed, Feb 11, 2015 at 8:44 AM, eryksun wrote: > On Wed, Feb 11, 2015 at 7:27 AM, boB Stepp wrote: >> >> pass_args = {'a': (x1, x2, x3), 'b': (y1, y2), 'c': (z)} >> call_fcn[key_letter](key_letter) >> >> But ran into the syntax error that I was giving one argument when >> (possibly) multiple arguments are expected. > > Do it like this: > > pass_args = { > 'a': (x1, x2, x3), > 'b': (y1, y2), > 'c': (z,), > } > > call_fcn[key_letter](*pass_args[key_letter]) > > Note the 'c' tuple is written as (z,). A comma is required to create a > tuple. Also note the call uses the "* expression" syntax to merge an > iterable with the call's positional arguments. For example, f(x0, > *(x1,x2,x3)) is equivalent to f(x0, x1, x2, x3). Refer to the glossary > definition of "argument", and for a more detailed discussion, see the > section on calls in the language reference. I was trying to puzzle out this "* expression" syntax from "Learning Python, 4th Ed." from a more general table of function argument-matching forms (author's table 18-1) when your post arrived. Your explanation cleared things up immediately. Thanks! -- boB From robertvstepp at gmail.com Wed Feb 11 16:29:34 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Wed, 11 Feb 2015 09:29:34 -0600 Subject: [Tutor] How to pass varying number of arguments to functions called by a dictionary? In-Reply-To: <54DB6B21.1030002@davea.name> References: <54DB6B21.1030002@davea.name> Message-ID: On Wed, Feb 11, 2015 at 8:45 AM, Dave Angel wrote: > On 02/11/2015 08:27 AM, boB Stepp wrote: [...] > > Sure, it's viable, but the best approach depends on your goal (use case), > and your restrictions. Are these functions really totally unrelated to each > other? You not only don't have the same number of arguments, but the values > don't even have anything in common? The file/module containing functions extract information from another software application (with its own scripting language) and ask that software to perform certain calculations in its scripting language. The dictionary keys are conventional symbols for types of calculations that someone might request. I have a current set of requested calculations, but this will likely be augmented with new ones in the future. Depending on the request, there might be no arguments passed, meaning there is a simple request for information from the software application that requires only a look-up, or the actual software application may have to do calculations requiring one or more passed values. Which and how many values depends on the type of calculation requested. > There's an implied constraint that you're not permitted to change the > functions. Are you really constrained to only change the caller? I think this is the case, but I am open to other ideas. > Assuming that you seriously want to be able to do this, the only use case I > can imagine are: > 1) you're writing an interpreter I was not thinking explicitly in this way, but in effect I am translating requests in Python code into a proprietary scripting language, and vice versa. [...] > In each case, there are probably better ways... I am open to suggestions! Thanks! -- boB From davea at davea.name Wed Feb 11 17:58:35 2015 From: davea at davea.name (Dave Angel) Date: Wed, 11 Feb 2015 11:58:35 -0500 Subject: [Tutor] How to pass varying number of arguments to functions called by a dictionary? In-Reply-To: References: <54DB6B21.1030002@davea.name> Message-ID: <54DB8A3B.2020109@davea.name> On 02/11/2015 10:29 AM, boB Stepp wrote: > On Wed, Feb 11, 2015 at 8:45 AM, Dave Angel wrote: >> On 02/11/2015 08:27 AM, boB Stepp wrote: > [...] >> >> Sure, it's viable, but the best approach depends on your goal (use case), >> and your restrictions. Are these functions really totally unrelated to each >> other? You not only don't have the same number of arguments, but the values >> don't even have anything in common? > > The file/module containing functions extract information from another > software application (with its own scripting language) and ask that > software to perform certain calculations in its scripting language. > The dictionary keys are conventional symbols for types of calculations > that someone might request. I have a current set of requested > calculations, but this will likely be augmented with new ones in the > future. Depending on the request, there might be no arguments passed, > meaning there is a simple request for information from the software > application that requires only a look-up, or the actual software > application may have to do calculations requiring one or more passed > values. Which and how many values depends on the type of calculation > requested. > >> There's an implied constraint that you're not permitted to change the >> functions. Are you really constrained to only change the caller? > > I think this is the case, but I am open to other ideas. > >> Assuming that you seriously want to be able to do this, the only use case I >> can imagine are: >> 1) you're writing an interpreter > > I was not thinking explicitly in this way, but in effect I am > translating requests in Python code into a proprietary scripting > language, and vice versa. > > [...] > >> In each case, there are probably better ways... > > I am open to suggestions! > So where does the data for these parameters come from? In other words, who is your user? Why isn't that user just calling the functions directly? You mention you're getting the function code-letters from a data file. Are you getting the data for the parameters from there as well? If all the data, and the corresponding function codes, are coming from the data file, then you must be deserializing that file in some way. And unless the data is always strings, there's more work to do there than in the wrapping of the calls themselves. There are libraries for serializing and deserializing arbitrary data. Some use xml, some use json, axon, csv, YAML, and probably tons of others. Likewise there are protocols such as SOAP, for remote procedure calls. Is the file entirely linear, or are you going to be doing branching, subroutining, etc? If there's any more complexity, you need to see the whole picture before you just do the call. Do any of these functions have return values? How are you handling that? -- DaveA From robertvstepp at gmail.com Wed Feb 11 18:47:26 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Wed, 11 Feb 2015 11:47:26 -0600 Subject: [Tutor] How to pass varying number of arguments to functions called by a dictionary? In-Reply-To: <54DB8A3B.2020109@davea.name> References: <54DB6B21.1030002@davea.name> <54DB8A3B.2020109@davea.name> Message-ID: On Wed, Feb 11, 2015 at 10:58 AM, Dave Angel wrote: > On 02/11/2015 10:29 AM, boB Stepp wrote: >> >> On Wed, Feb 11, 2015 at 8:45 AM, Dave Angel wrote: >>> >>> On 02/11/2015 08:27 AM, boB Stepp wrote: [...] >>> In each case, there are probably better ways... >> >> >> I am open to suggestions! >> > > So where does the data for these parameters come from? In other words, who > is your user? Why isn't that user just calling the functions directly? You > mention you're getting the function code-letters from a data file. Are you > getting the data for the parameters from there as well? The user uses their software application to create a treatment plan that they want to evaluate versus agreed values for a variety of parameters. These agreed values will exist in a data file that I create. It is likely that there will eventually be multiple such data files as the planner may be asked to compare their plan versus multiple sets of consensus data, which can come from a variety of sources. But right now I will have just one data file that our group has agreed to use. The user calls my program. The only choices he would get to make are if we move to more than one set of data to compare plans to. Which functions that get called will depend on the data file and existing information in the plan the user created. The passed values to functions will come both from the data file and previously extracted information from the user's plan. > If all the data, and the corresponding function codes, are coming from the > data file, then you must be deserializing that file in some way. And unless > the data is always strings, there's more work to do there than in the > wrapping of the calls themselves. The data is currently entirely in string format. I am currently constructing the file as a template that will also provide the format for the final display window. Basically, the program will copy anything needed for GUI, filling in any information fields that are plan-dependent, and only include organ structures that the user contoured in his plan, evaluating dose to these in accordance with the data table(s) I have been told to include. The data file will not be large. In the end there will probably be no more than 2 or 3 screens worth of data. > There are libraries for serializing and deserializing arbitrary data. Some > use xml, some use json, axon, csv, YAML, and probably tons of others. > Likewise there are protocols such as SOAP, for remote procedure calls. I was told in an earlier question I posted from several months ago that my proposed file design resembled the json format. I am keeping that in the back of my mind as I continue to work my way through this project. > Is the file entirely linear, or are you going to be doing branching, > subroutining, etc? If there's any more complexity, you need to see the > whole picture before you just do the call. For a given organ, the consensus data being used will require one or more checks with the actual plan data. This will vary for each possible organ. So based on the data format I use, it will signal the data reader the number and type of checks to do as well as what values the plan results will be compared to. So there is some complexity here. > Do any of these functions have return values? How are you handling that? Getting information into and out of the planning software can only be done indirectly. Because of this the functions will "print" planning software scripting commands to a temporary file. Once all such operations are done, this temporary file gets run (a reload script), which then actually does the work within the planning software. If information then needs to get from the planning software back to a Python program, then I have two options: 1) Save from within the planning software to a temp file that the Python program can access, or, 2) pass these values via a Unix command to a Python program. -- boB From raphael_raphael at hotmail.com Wed Feb 11 11:44:31 2015 From: raphael_raphael at hotmail.com (Raphael Raphael) Date: Wed, 11 Feb 2015 12:44:31 +0200 Subject: [Tutor] Using goto or labels in Python? In-Reply-To: References: Message-ID: Hello, Is there a way in which people have found to use goto or labels in Python?thank you. Sent from my iPhone > On Feb 11, 2015, at 12:27 PM, tutor-request at python.org wrote: > > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Wondering if there is a print in location command for > terminal? (eryksun) > 2. Timeline Script in Python (Siya Radebe) > 3. Re: Timeline Script in Python (Alan Gauld) > 4. Asking for help with installation of pyttsx (text to speech) > (Andrew K.) > 5. Importing from classes (daaku gee) > 6. Re: Asking for help with installation of pyttsx (text to > speech) (Alan Gauld) > 7. Re: Importing from classes (Alan Gauld) > 8. Re: Importing from classes (Steven D'Aprano) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 10 Feb 2015 08:29:56 -0600 > From: eryksun > To: Alan Gauld > Cc: tutor at python.org > Subject: Re: [Tutor] Wondering if there is a print in location command > for terminal? > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > >> On Tue, Feb 10, 2015 at 3:02 AM, Alan Gauld wrote: >> msvcrt wraps the Microsoft Vis C Runtime functions which don't >> include positional commands. >> >> Conio was a DOS library developed by the compiler makers as a way to access >> the BIOS calls and has a gotoXY() and similar functions. It first appeared, >> as I recall, in Turbo Pascal but was later picked >> up by the C compilers as well. >> There are at least 2 libraries on PyPi that simulate conio > > OK, the only conio I was aware of was the conio.h API provided by > various C runtime libraries on Windows, as described here: > > https://en.wikipedia.org/wiki/Conio.h > > > ------------------------------ > > Message: 2 > Date: Tue, 10 Feb 2015 18:29:46 +0200 > From: Siya Radebe > To: tutor at python.org > Subject: [Tutor] Timeline Script in Python > Message-ID: <4AF81C6C-BB16-4278-91E7-A70010D1A51D at goodhost.co.za> > Content-Type: text/plain; charset=us-ascii > > Hi, > > Can you please help with a timeline script in python, in conjunction with how to use their timeline library? > > I would love advise of how to best approach this, in going about developing an event/ activity stream timeline > > I found two different libraries, one from Python, and other from Django which is best, and how do i go about developing the script to show a timeline of events? > > https://pypi.python.org/pypi/timeline/0.0.1 > > https://pypi.python.org/pypi/django-admin-timeline > > Looking forward to your favorable response > > Kind Regards, > Siya > > ------------------------------ > > Message: 3 > Date: Tue, 10 Feb 2015 18:59:15 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Timeline Script in Python > Message-ID: > Content-Type: text/plain; charset=windows-1252; format=flowed > >> On 10/02/15 16:29, Siya Radebe wrote: >> Hi, >> >> Can you please help with a timeline script in python, in conjunction with how to use their timeline library? > > Thus list is for those learning the Python language and its standard > library. > Any information about third party modules will depend on whether anyone > here has used it, usually you are better asking on a dedicated forum (or > via email to the author) Django has a user forum, the PyPI package may not. > > >> I would love advise of how to best approach this, in going about developing an event/ activity stream timeline > > I think you need to be more specific about what you want to do. > Are you building it in real-time or from a database analysis? > What volume of events do you need to deal with? > etc... > > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > > > ------------------------------ > > Message: 4 > Date: Tue, 10 Feb 2015 22:37:28 -0500 > From: "Andrew K." > To: > Subject: [Tutor] Asking for help with installation of pyttsx (text to > speech) > Message-ID: > Content-Type: text/plain; charset="koi8-r" > > To whom it may concern. > > I started the project CrocToy, a complex robotic toy in a form of a crocodile. I would like to use Python as programming platform. Having limited programming skills, I have troubles with software development. Particularly, right now I try to learn how to use pyttsx (text to speech). I would be very grateful for any help with installation and programming. > Thank you very much, > Andrew > PS > I would be very thankful if any mature Python programmer would like to participate in my project. > Thank you, > Andrew > > ------------------------------ > > Message: 5 > Date: Tue, 10 Feb 2015 18:39:50 -0800 > From: daaku gee > To: tutor at python.org > Subject: [Tutor] Importing from classes > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > Hi > > When importing from other modules, I've seen syntax like: > > import from > import > > And another one: > import from as > > Is one better than the other or is it just personal choice? > > Thanks > \d > > > ------------------------------ > > Message: 6 > Date: Wed, 11 Feb 2015 09:24:27 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Asking for help with installation of pyttsx (text > to speech) > Message-ID: > Content-Type: text/plain; charset=windows-1252; format=flowed > >> On 11/02/15 03:37, Andrew K. wrote: >> >> I started the project CrocToy, a complex robotic toy in a form of a crocodile. >> I would like to use Python as programming platform. >> Having limited programming skills, I have troubles with software > development. > > This much we can help with since the list is here for those learning > Python and programming in general. > >> Particularly, right now I try to learn how to use pyttsx (text to speech). > > But we do limit ourselves to the standard library modules so for > anything else you will be gambling on somebody here already having > used it. Usually you are better sending module specific queries to the > module support forum (or the author.) > >> I would be very grateful for any help with installation and programming. > > Do you have any specific queries? The more specific the query the more > specific the answer will be. > > Please include details of your OS and Python version. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > > > ------------------------------ > > Message: 7 > Date: Wed, 11 Feb 2015 09:32:02 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Importing from classes > Message-ID: > Content-Type: text/plain; charset=windows-1252; format=flowed > >> On 11/02/15 02:39, daaku gee wrote: >> >> When importing from other modules, I've seen syntax like: >> >> import from > > from import > > Note you don't import classes from modules you import names. > (The name might be the name of a class of course!) > > This form is for cases where you only want to use one or two features of > a module and don't want to have the inconvenience of typing the module > name in front each time you use them. > >> import > > This is the normal usage. It gives you indirect access to all of the > module features using the . notation > >> import from as > > import as > or > from import as > > These tend to be used where the module has a very long name that > you don't want to type out in full each time, so you give it a > shorter alias. > You might also use it if you are working on code that already has > a variable with the same name as the module/feature that you want > to import. You either rename all your variable references or you > choose an alias that does not conflict. > >> Is one better than the other or is it just personal choice? > > 'better' is often a subjective term. > There are reasons for each as described above. > What is best depends on the circumstance. If in > doubt use > > import > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > > > ------------------------------ > > Message: 8 > Date: Wed, 11 Feb 2015 21:18:17 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Importing from classes > Message-ID: <20150211101817.GZ2498 at ando.pearwood.info> > Content-Type: text/plain; charset=us-ascii > >> On Tue, Feb 10, 2015 at 06:39:50PM -0800, daaku gee wrote: >> Hi >> >> When importing from other modules, I've seen syntax like: >> >> import from >> import >> >> And another one: >> import from as > > Not quite. The syntax is: > > import > > import as > > from import # not necessarily a class > > from import as > > >> Is one better than the other or is it just personal choice? > > As far as Python is concerned, there is no difference at all. The "as > name" version just lets you pick a different name, usually to save > typing: > > import module_with_a_really_long_name as module > > > Obviously the usual rule for naming things applies here too: names > should be meaningful, they should not lie, or be confusing: > > # Bad ideas. > import math as string # What? > import string as fred > import os as barney > > Beware of names which are easily confused, or have common meanings: > > - try to avoid `l` and `I` because in some fonts they look like 1 > - same for `O` and 0 > - i is normally used for for-loop counters and other integers > - n is also used for integers > - x and y for floats > > But apart from that, the names you choose are entirely up to you. > > > -- > Steve > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 132, Issue 21 > ************************************** From siya360 at gmail.com Wed Feb 11 16:40:22 2015 From: siya360 at gmail.com (Siya 360) Date: Wed, 11 Feb 2015 17:40:22 +0200 Subject: [Tutor] Timeline Script in Python In-Reply-To: <4AF81C6C-BB16-4278-91E7-A70010D1A51D@goodhost.co.za> References: <4AF81C6C-BB16-4278-91E7-A70010D1A51D@goodhost.co.za> Message-ID: <451DB0F2-7218-4D80-A4D5-05801FBBD551@gmail.com> > Hi, > > Can you please help with a timeline script in python, in conjunction with how to use their timeline library? > > I would love advise of how to best approach this, in going about developing an event/ activity stream timeline > > I found two different libraries, one from Python, and other from Django which is best, and how do i go about developing the script to show a timeline of events? > > https://pypi.python.org/pypi/timeline/0.0.1 > > https://pypi.python.org/pypi/django-admin-timeline > > Looking forward to your favorable response > > Kind Regards, > Siya From alan.gauld at btinternet.com Wed Feb 11 19:14:13 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Feb 2015 18:14:13 +0000 Subject: [Tutor] Using goto or labels in Python? In-Reply-To: References: Message-ID: On 11/02/15 10:44, Raphael Raphael wrote: > Hello, Hello, please do not post the entire digest to ask a new question. Some people pay by the byte. Just send a new mail to tutor at python.org. > Is there a way in which people have found to use goto or labels in Python?thank you. No. Python does not have a goto because using goto is considered bad programming practice and is never necessary (although *very* occasionally it can be simpler and clearer to use goto IMHO). What are you trying to do that you think needs a goto and we can see if there is a clearer way to write it without goto. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Wed Feb 11 19:54:32 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 11 Feb 2015 18:54:32 +0000 Subject: [Tutor] Using goto or labels in Python? In-Reply-To: References: Message-ID: On 11/02/2015 18:14, Alan Gauld wrote: > On 11/02/15 10:44, Raphael Raphael wrote: >> Hello, > > Hello, please do not post the entire digest to ask a new question. > Some people pay by the byte. > Just send a new mail to tutor at python.org. > > >> Is there a way in which people have found to use goto or labels in >> Python?thank you. > > No. Python does not have a goto because using goto is > considered bad programming practice and is never necessary > (although *very* occasionally it can be simpler and clearer > to use goto IMHO). http://entrian.com/goto/ but note the warning in bright red right at the top https://github.com/cdjc/goto never tried this one The one time that I'd consider goto is jumping to an error handler. > > What are you trying to do that you think needs a goto and we > can see if there is a clearer way to write it without goto. > Definitely :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at yahoo.co.uk Thu Feb 12 08:23:49 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 12 Feb 2015 07:23:49 +0000 Subject: [Tutor] Asking for help with installation of pyttsx (text to speech) In-Reply-To: References: Message-ID: On 11/02/2015 03:37, Andrew K. wrote: > To whom it may concern. > > I started the project CrocToy, a complex robotic toy in a form of a crocodile. I would like to use Python as programming platform. Having limited programming skills, I have troubles with software development. Particularly, right now I try to learn how to use pyttsx (text to speech). I would be very grateful for any help with installation and programming. > Thank you very much, > Andrew > PS > I would be very thankful if any mature Python programmer would like to participate in my project. > Thank you, > Andrew > As Alan has already said this very much depends on your versions of Python and OS. If you're on any *nix type system the simplest mechanism is simply pip install pyttsx More on pip here https://pip.pypa.io/en/latest/installing.html On Windows you've two options that I'm aware of. Either download pyttsx-1.1-py2-none-any.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/ and install it using pip. This is Python 2 specific. Or for Python 3.4 install Visual Studio Express 2010 and again use:- pip install pyttsx I would *NOT* recommend the latter approach for you as a beginner, but then there is nothing to stop you trying. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From regimari at nb.sympatico.ca Thu Feb 12 12:34:12 2015 From: regimari at nb.sympatico.ca (=?UTF-8?B?UsOpZ2luYWxkIEFyc2VuZWF1?=) Date: Thu, 12 Feb 2015 07:34:12 -0400 Subject: [Tutor] Wave module In-Reply-To: References: Message-ID: <54DC8FB4.7000304@nb.sympatico.ca> I, I'm trying this code for Voice Text To Speech and Wav File Make and Save, but I'm recontering this problem when I import the Editor to Python OnLine. >>> import Editor2 Traceback (most recent call last): File "", line 1, in File "Editor2.py", line 5, in import Sapi5 File "Sapi5.py", line 3, in from comtypes.client import CreateObject ImportError: No module named comtypes.client >>> Do you have an Idea why I rencontering this error message? Thank you in advance. Email adresse: regimari at nb.sympatico.ca R?ginald Arseneau From alan.gauld at btinternet.com Thu Feb 12 23:28:03 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Feb 2015 22:28:03 +0000 Subject: [Tutor] Wave module In-Reply-To: <54DC8FB4.7000304@nb.sympatico.ca> References: <54DC8FB4.7000304@nb.sympatico.ca> Message-ID: On 12/02/15 11:34, R?ginald Arseneau wrote: > I, > I'm trying this code for Voice Text To Speech and Wav File Make and Save, > but I'm recontering this problem when I import the Editor to Python OnLine. This list is for folks learning the python language and its standard library. WE may not be able to offer much help on third party packages. You are usually better asking on the libraries support forum or contacting the author. But to stand any chance... > >>> import Editor2 Tell us where this package comes from, what OS you are using and what Python version. Then there is a possibility that somebody on the list will be able to help. > Traceback (most recent call last): > File "", line 1, in > File "Editor2.py", line 5, in > import Sapi5 > File "Sapi5.py", line 3, in > from comtypes.client import CreateObject > ImportError: No module named comtypes.client It looks like your Editir module has some dependencies and you will need to install them too. The mention of comtypes suggests its a Windows program? Maybe using the PyWin32 package? Have you installed it? HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From vanandy14 at gmail.com Fri Feb 13 02:06:47 2015 From: vanandy14 at gmail.com (andy van) Date: Thu, 12 Feb 2015 17:06:47 -0800 Subject: [Tutor] Comparing two CSV filess using Python Message-ID: Hi, I'm trying to compare two CSV files (and many more like these below). I tried many ways, using lists, dictreader and more but nothing gave me the output I require. I want to compare all those rows that have same !Sample_title and !Sample_geo_accession values (whose positions vary). I've been struggling with this for three days now and couldn't come to a solution. I highly appreciate any help. CSV1: !Sample_title,!Sample_geo_accession,!Sample_status,!Sample_type,!Sample_source_name_ch1 body,GSM501443,Public on july 22 2010,ribonucleic acid,FB_50_12wk foreign,GSM501445,Public on july 22 2010,ribonucleic acid,FB_0_12wk HJCENV,GSM501446,Public on july 22 2010,ribonucleic acid,FB_50_12wk AsDW,GSM501444,Public on july 22 2010,ribonucleic acid,FB_0_12wk CSV2: !Sample_title,!Sample_type,!Sample_source_name_ch1,!Sample_geo_accession AsDW,ribonucleic acid,FB_0,GSM501444 foreign,ribonucleic acid,FB,GSM501449 HJCENV,RNA,12wk,GSM501446 Desired output (with respect to CSV2): Added: {!Sample_status:{HJCENV:Public on july 22 2010,AsDW:Public on july 22 2010}} #Added columns, not rows. Deleted: {} #Since nothing's deleted with respect to CSV2 Changed: {!Sample_title:AsDW,!Sample_source_name_ch1:(FB_0_12wk,FB_0),!Sample_geo_accession:GSM501444 !Sample_title:HJCENV,!Sample_type:(ribonucleic acid,RNA),!Sample_source_name_ch1:(FB_50_12wk,12wk),!Sample_geo_accession:GSM501446} #foreign,ribonucleic acid,FB,GSM501449 doesn't come here since the !Sample_geo_accession column value didn't match. -AN From alan.gauld at btinternet.com Fri Feb 13 09:46:51 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Feb 2015 08:46:51 +0000 Subject: [Tutor] Comparing two CSV filess using Python In-Reply-To: References: Message-ID: On 13/02/15 01:06, andy van wrote: > Hi, I'm trying to compare two CSV files (and many more like these below). I > tried many ways, using lists, dictreader and more but nothing gave me the > output I require. I want to compare all those rows that have same > !Sample_title and !Sample_geo_accession values (whose positions vary). I've > been struggling with this for three days now and couldn't come to a > solution. I highly appreciate any help. I'm afraid your sample data was insufficient for me to figure out your criteria for doing additions/deletions etc. However given that the fields have the same name but varying positions it sounds like a dictreader would be the best starting point. Can you show us what you tried using the dictreader approach? Also can you write a function that does the comparison of two lines and returns an action code (say: 0 = nothing, 1 = add, 2 = delete, 3 = change) That would encapsulate your "business logic" and just leave the issue of comparing the two files. > CSV1: > > !Sample_title,!Sample_geo_accession,!Sample_status,!Sample_type,!Sample_source_name_ch1 > body,GSM501443,Public on july 22 2010,ribonucleic acid,FB_50_12wk > foreign,GSM501445,Public on july 22 2010,ribonucleic acid,FB_0_12wk > HJCENV,GSM501446,Public on july 22 2010,ribonucleic acid,FB_50_12wk > AsDW,GSM501444,Public on july 22 2010,ribonucleic acid,FB_0_12wk > > CSV2: > > !Sample_title,!Sample_type,!Sample_source_name_ch1,!Sample_geo_accession > AsDW,ribonucleic acid,FB_0,GSM501444 > foreign,ribonucleic acid,FB,GSM501449 > HJCENV,RNA,12wk,GSM501446 > > Desired output (with respect to CSV2): > > Added: > {!Sample_status:{HJCENV:Public on july 22 2010,AsDW:Public on july 22 > 2010}} #Added columns, not rows. > > Deleted: > {} #Since nothing's deleted with respect to CSV2 > > Changed: > > {!Sample_title:AsDW,!Sample_source_name_ch1:(FB_0_12wk,FB_0),!Sample_geo_accession:GSM501444 > !Sample_title:HJCENV,!Sample_type:(ribonucleic > acid,RNA),!Sample_source_name_ch1:(FB_50_12wk,12wk),!Sample_geo_accession:GSM501446} > #foreign,ribonucleic acid,FB,GSM501449 doesn't come here since the > !Sample_geo_accession column value didn't match. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Fri Feb 13 10:36:31 2015 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Feb 2015 10:36:31 +0100 Subject: [Tutor] Comparing two CSV filess using Python References: Message-ID: andy van wrote: > Hi, I'm trying to compare two CSV files (and many more like these below). > I tried many ways, using lists, dictreader and more but nothing gave me > the output I require. I want to compare all those rows that have same > !Sample_title and !Sample_geo_accession values (whose positions vary). > I've been struggling with this for three days now and couldn't come to a > solution. I highly appreciate any help. Basically you need to put the csv into dicts that map title/geo to the whole row. You can then easily get the common rows' keys with set operations. For each pair of row dicts you can then compare the data added = newrow.keys() - oldrow.keys() # just dump the values removed = oldrow.keys() - newrow.keys() # just dump the values common = newrow.keys() & oldrow.keys() # need to compare the values # to suppress unchanged ones > > CSV1: > > !Sample_title,!Sample_geo_accession,!Sample_status,!Sample_type,!Sample_source_name_ch1 > body,GSM501443,Public on july 22 2010,ribonucleic acid,FB_50_12wk > foreign,GSM501445,Public on july 22 2010,ribonucleic acid,FB_0_12wk > HJCENV,GSM501446,Public on july 22 2010,ribonucleic acid,FB_50_12wk > AsDW,GSM501444,Public on july 22 2010,ribonucleic acid,FB_0_12wk > > CSV2: > > !Sample_title,!Sample_type,!Sample_source_name_ch1,!Sample_geo_accession > AsDW,ribonucleic acid,FB_0,GSM501444 > foreign,ribonucleic acid,FB,GSM501449 > HJCENV,RNA,12wk,GSM501446 > > Desired output (with respect to CSV2): > > Added: > {!Sample_status:{HJCENV:Public on july 22 2010,AsDW:Public on july 22 > 2010}} #Added columns, not rows. > > Deleted: > {} #Since nothing's deleted with respect to CSV2 > > Changed: > > {!Sample_title:AsDW,!Sample_source_name_ch1: (FB_0_12wk,FB_0),!Sample_geo_accession:GSM501444 > !Sample_title:HJCENV,!Sample_type:(ribonucleic > acid,RNA),!Sample_source_name_ch1: (FB_50_12wk,12wk),!Sample_geo_accession:GSM501446} > #foreign,ribonucleic acid,FB,GSM501449 doesn't come here since the > !Sample_geo_accession column value didn't match. If you want to cheat, here's an implementation (requires Python 3): import csv def get_key(row): return row["!Sample_title"], row["!Sample_geo_accession"] def load_csv(filename): """Put csv data into a dict that maps title/geo to the complete row. """ d = {} with open(filename) as f: for row in csv.DictReader(f, delimiter=","): key = get_key(row) assert key not in d d[key] = row return d def diffs(old, new): yield from added_or_removed("ADDED", new.keys() - old.keys(), new) yield from added_or_removed("REMOVED", old.keys() - new.keys(), old) yield from changed(old, new) def compare_row(key, old, new): i = -1 for i, line in enumerate(diffs(old, new)): if not i: print("/".join(key)) print(" " + line) if i >= 0: print() def added_or_removed(state, keys, d): items = sorted((key, d[key]) for key in keys) for key, value in items: yield "{:10}: {:30} | {:30}".format(state, key, value) def changed(old, new): common_columns = old.keys() & new.keys() for column in sorted(common_columns): oldvalue = old[column] newvalue = new[column] if oldvalue != newvalue: yield "{:10}: {:30} | {:30} | {:30}".format( "CHANGED", column, oldvalue.ljust(30), newvalue.ljust(30)) if __name__ == "__main__": oldcsv = load_csv("2.csv") newcsv = load_csv("1.csv") # title/geo pairs that occur in both files: common = oldcsv.keys() & newcsv.keys() for key in sorted(common): compare_row(key, oldcsv[key], newcsv[key]) From breamoreboy at yahoo.co.uk Sat Feb 14 02:32:59 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 14 Feb 2015 01:32:59 +0000 Subject: [Tutor] Comparing two CSV filess using Python In-Reply-To: References: Message-ID: On 13/02/2015 01:06, andy van wrote: > Hi, I'm trying to compare two CSV files (and many more like these below). I > tried many ways, using lists, dictreader and more but nothing gave me the > output I require. I want to compare all those rows that have same > !Sample_title and !Sample_geo_accession values (whose positions vary). I've > been struggling with this for three days now and couldn't come to a > solution. I highly appreciate any help. > > CSV1: > > !Sample_title,!Sample_geo_accession,!Sample_status,!Sample_type,!Sample_source_name_ch1 > body,GSM501443,Public on july 22 2010,ribonucleic acid,FB_50_12wk > foreign,GSM501445,Public on july 22 2010,ribonucleic acid,FB_0_12wk > HJCENV,GSM501446,Public on july 22 2010,ribonucleic acid,FB_50_12wk > AsDW,GSM501444,Public on july 22 2010,ribonucleic acid,FB_0_12wk > > CSV2: > > !Sample_title,!Sample_type,!Sample_source_name_ch1,!Sample_geo_accession > AsDW,ribonucleic acid,FB_0,GSM501444 > foreign,ribonucleic acid,FB,GSM501449 > HJCENV,RNA,12wk,GSM501446 > > Desired output (with respect to CSV2): > > Added: > {!Sample_status:{HJCENV:Public on july 22 2010,AsDW:Public on july 22 > 2010}} #Added columns, not rows. > > Deleted: > {} #Since nothing's deleted with respect to CSV2 > > Changed: > > {!Sample_title:AsDW,!Sample_source_name_ch1:(FB_0_12wk,FB_0),!Sample_geo_accession:GSM501444 > !Sample_title:HJCENV,!Sample_type:(ribonucleic > acid,RNA),!Sample_source_name_ch1:(FB_50_12wk,12wk),!Sample_geo_accession:GSM501446} > #foreign,ribonucleic acid,FB,GSM501449 doesn't come here since the > !Sample_geo_accession column value didn't match. > > -AN > If you're looking at serious data work then I'd recommend pandas http://pandas.pydata.org/ -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From steve10brink at comcast.net Sat Feb 14 04:17:28 2015 From: steve10brink at comcast.net (steve10brink at comcast.net) Date: Sat, 14 Feb 2015 03:17:28 +0000 (UTC) Subject: [Tutor] trivial simple program..can it be made more concise? In-Reply-To: <36171548.1796544.1423883352134.JavaMail.zimbra@comcast.net> Message-ID: <1273312104.1797364.1423883848882.JavaMail.zimbra@comcast.net> Hi all, I was playing with Python tonight and created a simple program that outputs numbers counting up then counting down all on the same terminal line. The code is as follows: #------------------------------------------------------------ a = 320000 #number to count up to for i in range (a): print i, '\r', for i in range ((a-1),0,-1): print i, '\r', #------------------------------------------------------------ It works as desired. However, I was trying to figure out a way to make it more concise but cannot see a way since the 'range' parameters must be integers (no functions allowed?). Anyone see a way to simplify it? Thanks, Steve From joel.goldstick at gmail.com Sat Feb 14 04:49:42 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 13 Feb 2015 22:49:42 -0500 Subject: [Tutor] trivial simple program..can it be made more concise? In-Reply-To: <1273312104.1797364.1423883848882.JavaMail.zimbra@comcast.net> References: <36171548.1796544.1423883352134.JavaMail.zimbra@comcast.net> <1273312104.1797364.1423883848882.JavaMail.zimbra@comcast.net> Message-ID: On Fri, Feb 13, 2015 at 10:17 PM, wrote: > Hi all, > > I was playing with Python tonight and created a simple program that > outputs numbers counting up then counting down all on the same terminal > line. The code is as follows: > > > > #------------------------------------------------------------ > a = 320000 #number to count up to > > > for i in range (a): > print i, '\r', > > for i in range ((a-1),0,-1): > print i, '\r', > > #------------------------------------------------------------ > > > > > It works as desired. However, I was trying to figure out a way to make it > more concise but > > cannot see a way since the 'range' parameters must be integers (no > functions allowed?). > > > > > Anyone see a way to simplify it? > > > you don't need the \r. print will print each line on a new line > > > Thanks, > > Steve > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From __peter__ at web.de Sat Feb 14 08:38:41 2015 From: __peter__ at web.de (Peter Otten) Date: Sat, 14 Feb 2015 08:38:41 +0100 Subject: [Tutor] trivial simple program..can it be made more concise? References: <36171548.1796544.1423883352134.JavaMail.zimbra@comcast.net> <1273312104.1797364.1423883848882.JavaMail.zimbra@comcast.net> Message-ID: steve10brink at comcast.net wrote: > I was playing with Python tonight and created a simple program that > outputs numbers counting up then counting down all on the same terminal > line. The code is as follows: > > > > #------------------------------------------------------------ > a = 320000 #number to count up to > > > for i in range (a): > print i, '\r', > > for i in range ((a-1),0,-1): > print i, '\r', > > #------------------------------------------------------------ > > > > > It works as desired. However, I was trying to figure out a way to make it > more concise but > > cannot see a way since the 'range' parameters must be integers (no > functions allowed?). > Anyone see a way to simplify it? r = range(320000) for i in r + r[::-1]: print i, "\r", However, this has the disadvantage of building a list with 620000 items. To avoid that you can write from itertools import chain r = xrange(320000) for i in chain(r, reversed(r)): print i, "\r", but you probably don't see that as a simplification. From breamoreboy at yahoo.co.uk Sat Feb 14 08:48:56 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 14 Feb 2015 07:48:56 +0000 Subject: [Tutor] trivial simple program..can it be made more concise? In-Reply-To: <1273312104.1797364.1423883848882.JavaMail.zimbra@comcast.net> References: <36171548.1796544.1423883352134.JavaMail.zimbra@comcast.net> <1273312104.1797364.1423883848882.JavaMail.zimbra@comcast.net> Message-ID: On 14/02/2015 03:17, steve10brink at comcast.net wrote: > Hi all, > > I was playing with Python tonight and created a simple program that outputs numbers counting up then counting down all on the same terminal line. The code is as follows: > > > > #------------------------------------------------------------ > a = 320000 #number to count up to > > > for i in range (a): > print i, '\r', > > for i in range ((a-1),0,-1): > print i, '\r', > > #------------------------------------------------------------ > > It works as desired. However, I was trying to figure out a way to make it more concise but > cannot see a way since the 'range' parameters must be integers (no functions allowed?). If the functions return integers that's fine. for i in range(int('0'), int('5'), int('1')):print(i) 0 1 2 3 4 > > Anyone see a way to simplify it? > Well you could have:- a = 5 for start, stop, step in ((0, a, 1), (a-1, 0, -1)): for i in range(start, stop, step): print(i) 0 1 2 3 4 4 3 2 1 But is it actually simpler? I find your original code far easier to read so quite frankly I'd leave it as is. If it ain't broke, don't fix it :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From steve at pearwood.info Sat Feb 14 10:07:02 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 14 Feb 2015 20:07:02 +1100 Subject: [Tutor] trivial simple program..can it be made more concise? In-Reply-To: <1273312104.1797364.1423883848882.JavaMail.zimbra@comcast.net> References: <36171548.1796544.1423883352134.JavaMail.zimbra@comcast.net> <1273312104.1797364.1423883848882.JavaMail.zimbra@comcast.net> Message-ID: <20150214090702.GU2498@ando.pearwood.info> On Sat, Feb 14, 2015 at 03:17:28AM +0000, steve10brink at comcast.net wrote: > Hi all, > > I was playing with Python tonight and created a simple program that > outputs numbers counting up then counting down all on the same > terminal line. The code is as follows: > > #------------------------------------------------------------ > a = 320000 #number to count up to > > for i in range (a): > print i, '\r', > > for i in range ((a-1),0,-1): > print i, '\r', > > #------------------------------------------------------------ > > It works as desired. However, I was trying to figure out a way to make > it more concise but cannot see a way since the 'range' parameters must > be integers (no functions allowed?). Parameters to range can be anything which evaluates to integers, but I'm not sure how that will help you. Also, in Python 2 xrange is a little more efficient than range. How's this? a = 320000 counts = (xrange(a), xrange(a-1, 0, -1)) for counter in counts: for i in counter: print i, '\r' BUT I'm not sure why you are worried about making it more concise when your code doesn't do what you want, as far as I can tell. You want the counter to be written on the same line, not 640 thousand lines, but when I try it, I get each number written to a different line. Try this instead: import sys a = 320000 counts = (xrange(a), xrange(a-1, 0, -1)) for counter in counts: for i in counter: sys.stdout.write(str(i) + '\r') sys.stdout.flush() -- Steve From street.sweeper at mailworks.org Sat Feb 14 02:24:37 2015 From: street.sweeper at mailworks.org (street.sweeper at mailworks.org) Date: Fri, 13 Feb 2015 20:24:37 -0500 Subject: [Tutor] sql-like join on two lists or dictionaries Message-ID: <1423877077.197303.227364393.5C66E157@webmail.messagingengine.com> Hello all, Basically what I have here is header and line data for sales or purchase orders, and I'm trying to do a sql-like join to bring them together (which ultimately I did because I couldn't figure this out :)). I've managed to get the files into python using string slicing, that's not a problem. headers - h.dat B134542 Bob ZQ775235 B875432 Joe ZQ987656 B567943 Steve ZQ256222 lines - l.dat B134542 112342 0012 B134542 176542 0001 B875732 76542 0003 B567943 654565 0001 B567943 900011 0001 desired result - hl.dat B134542 112342 0012 Bob ZQ775235 B134542 176542 0001 Bob ZQ775235 B875732 76542 0003 Joe ZQ987656 B567943 654565 0001 Steve ZQ256222 B567943 900011 0001 Steve ZQ256222 in python3 on linux: #!/usr/bin/env python3 import os basepath=os.path.join(os.path.expanduser('~'),'temp',) linefile=os.path.join(basepath,'l.dat') headerfile=os.path.join(basepath,'h.dat') with open(headerfile) as h, open(linefile) as l: lines = l.readlines() headers = h.readlines() llist = [[linedata[0:7], linedata[14:23], linedata[23:27]] for linedata in lines] hlist = [[headerdata[0:7], headerdata[11:19], headerdata[19:28]] for headerdata in headers] ldict = [{linedata[0:7]: [linedata[14:23], linedata[23:27]]} for linedata in lines] hdict = [{headerdata[0:7]: [headerdata[11:19], headerdata[19:28]]} for headerdata in headers] # :) quit() Details on the data are that it's a one or many lines to one header relationship, at least one of each will exist in each file, and performance probably isn't an issue as it will only be a few tens to about 100 lines maximum in the lines file. The match string will be the 0:7 slice. You can probably guess my questions: should I be making lists or dictionaries out of this data, and then of course, what should I do with them to arrive at the combined file? I saw some examples of joining two two-item lists, or dictionaries with a single string as the value, but I couldn't seem to adapt them to what I'm doing here. I also ran across the dict.extend method, but looking at the result, I didn't think that was going to go anywhere, particularly with the one to many headers:lines relationship. After a while I pulled this into a sqlite file in memory and did the join. Using writelines I think I'll be able to get it out to a file, but it seems to me that there's probably a way to do this without resorting to sql. Or is there? Thanks! From __peter__ at web.de Sat Feb 14 10:55:04 2015 From: __peter__ at web.de (Peter Otten) Date: Sat, 14 Feb 2015 10:55:04 +0100 Subject: [Tutor] sql-like join on two lists or dictionaries References: <1423877077.197303.227364393.5C66E157@webmail.messagingengine.com> Message-ID: street.sweeper at mailworks.org wrote: > Hello all, > > Basically what I have here is header and line data for sales or purchase > orders, and I'm trying to do a sql-like join to bring them together > (which ultimately I did because I couldn't figure this out :)). I've > managed to get the files into python using string slicing, that's not a > problem. > > headers - h.dat > > B134542 Bob ZQ775235 > B875432 Joe ZQ987656 > B567943 Steve ZQ256222 > > lines - l.dat > > B134542 112342 0012 > B134542 176542 0001 > B875732 76542 0003 > B567943 654565 0001 > B567943 900011 0001 > > desired result - hl.dat > > B134542 112342 0012 Bob ZQ775235 > B134542 176542 0001 Bob ZQ775235 > B875732 76542 0003 Joe ZQ987656 > B567943 654565 0001 Steve ZQ256222 > B567943 900011 0001 Steve ZQ256222 > > > > in python3 on linux: > > #!/usr/bin/env python3 > > import os > > basepath=os.path.join(os.path.expanduser('~'),'temp',) > linefile=os.path.join(basepath,'l.dat') > headerfile=os.path.join(basepath,'h.dat') > > with open(headerfile) as h, open(linefile) as l: > lines = l.readlines() > headers = h.readlines() > > llist = [[linedata[0:7], > linedata[14:23], > linedata[23:27]] for linedata in lines] > > hlist = [[headerdata[0:7], > headerdata[11:19], > headerdata[19:28]] for headerdata in headers] > > ldict = [{linedata[0:7]: > [linedata[14:23], > linedata[23:27]]} for linedata in lines] > > hdict = [{headerdata[0:7]: > [headerdata[11:19], > headerdata[19:28]]} for headerdata in headers] > > # :) > > quit() > > > > Details on the data are that it's a one or many lines to one header > relationship, at least one of each will exist in each file, and > performance probably isn't an issue as it will only be a few tens to > about 100 lines maximum in the lines file. The match string will be the > 0:7 slice. > > You can probably guess my questions: should I be making lists or > dictionaries out of this data, and then of course, what should I do with > them to arrive at the combined file? I saw some examples of joining two > two-item lists, or dictionaries with a single string as the value, but I > couldn't seem to adapt them to what I'm doing here. I also ran across > the dict.extend method, but looking at the result, I didn't think that > was going to go anywhere, particularly with the one to many > headers:lines relationship. > > After a while I pulled this into a sqlite file in memory and did the > join. Using writelines I think I'll be able to get it out to a file, > but it seems to me that there's probably a way to do this without > resorting to sql. Or is there? You only need one dictionary that maps the first column in headerfile to the complete line: with open(headerfile) as f: lookup_header = { headerdata[:6]: headerdata.rstrip("\n") for headerdata in f} Then you can iterate over the lines in linefile, extract the key from that and look it up in the dict: with open(linefile) as lines, open("hl.dat", "w") as joined: for line in lines: try: header = lookup_header[line[:6]] except KeyError: header = "" print(line.rstrip("\n"), header, sep="", file=joined) This approach works with linefiles of arbitrary size as you only ever have one line of that file in memory. As written the output file includes lines with no matching header; replace header = "" with a continue statement to get an inner join. A general remark: whenever possible you should avoid the readlines() method which creates a list of lines and instead iterate over the file directly. From davea at davea.name Sat Feb 14 12:40:56 2015 From: davea at davea.name (Dave Angel) Date: Sat, 14 Feb 2015 06:40:56 -0500 Subject: [Tutor] trivial simple program..can it be made more concise? In-Reply-To: <20150214090702.GU2498@ando.pearwood.info> References: <36171548.1796544.1423883352134.JavaMail.zimbra@comcast.net> <1273312104.1797364.1423883848882.JavaMail.zimbra@comcast.net> <20150214090702.GU2498@ando.pearwood.info> Message-ID: <54DF3448.404@davea.name> On 02/14/2015 04:07 AM, Steven D'Aprano wrote: > On Sat, Feb 14, 2015 at 03:17:28AM +0000, steve10brink at comcast.net wrote: >> Hi all, >> >> I was playing with Python tonight and created a simple program that >> outputs numbers counting up then counting down all on the same >> terminal line. The code is as follows: >> >> #------------------------------------------------------------ >> a = 320000 #number to count up to >> >> for i in range (a): >> print i, '\r', >> >> for i in range ((a-1),0,-1): >> print i, '\r', >> >> #------------------------------------------------------------ >> >> It works as desired. However, I was trying to figure out a way to make >> it more concise but cannot see a way since the 'range' parameters must >> be integers (no functions allowed?). > > > Parameters to range can be anything which evaluates to integers, but > I'm not sure how that will help you. Also, in Python 2 xrange is a > little more efficient than range. > > How's this? > > a = 320000 > counts = (xrange(a), xrange(a-1, 0, -1)) > for counter in counts: > for i in counter: > print i, '\r' > > > BUT I'm not sure why you are worried about making it more concise when > your code doesn't do what you want, as far as I can tell. You want the > counter to be written on the same line, not 640 thousand lines, but when > I try it, I get each number written to a different line. That's probably because you've dropped the trailing comma that the OP used in the print statements. > > Try this instead: > > import sys > a = 320000 > counts = (xrange(a), xrange(a-1, 0, -1)) > for counter in counts: > for i in counter: > sys.stdout.write(str(i) + '\r') > sys.stdout.flush() > > -- DaveA From steve at pearwood.info Sat Feb 14 13:51:56 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 14 Feb 2015 23:51:56 +1100 Subject: [Tutor] trivial simple program..can it be made more concise? In-Reply-To: <54DF3448.404@davea.name> References: <36171548.1796544.1423883352134.JavaMail.zimbra@comcast.net> <1273312104.1797364.1423883848882.JavaMail.zimbra@comcast.net> <20150214090702.GU2498@ando.pearwood.info> <54DF3448.404@davea.name> Message-ID: <20150214125156.GY2498@ando.pearwood.info> On Sat, Feb 14, 2015 at 06:40:56AM -0500, Dave Angel wrote: > On 02/14/2015 04:07 AM, Steven D'Aprano wrote: > >On Sat, Feb 14, 2015 at 03:17:28AM +0000, steve10brink at comcast.net wrote: [...] > >>for i in range (a): > >> print i, '\r', [...] > >BUT I'm not sure why you are worried about making it more concise when > >your code doesn't do what you want, as far as I can tell. You want the > >counter to be written on the same line, not 640 thousand lines, but when > >I try it, I get each number written to a different line. > > That's probably because you've dropped the trailing comma that the OP > used in the print statements. So I did :-( Have I mentioned recently just how awesome Python 3's print is? for i in range(100000): print(i, end='\r') Much nicer :-) -- Steve From alan.gauld at btinternet.com Sat Feb 14 14:03:48 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Feb 2015 13:03:48 +0000 Subject: [Tutor] sql-like join on two lists or dictionaries In-Reply-To: References: <1423877077.197303.227364393.5C66E157@webmail.messagingengine.com> Message-ID: On 14/02/15 09:55, Peter Otten wrote: > with open(headerfile) as f: > lookup_header = { > headerdata[:6]: headerdata.rstrip("\n") for headerdata in f} > > Then you can iterate over the lines in linefile, extract the key from that > and look it up in the dict: > > with open(linefile) as lines, open("hl.dat", "w") as joined: > for line in lines: > try: > header = lookup_header[line[:6]] > except KeyError: > header = "" > print(line.rstrip("\n"), header, sep="", file=joined) > The try/except could be written more concisely as header = lookup_header.get(line[:6], "") HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From joel.goldstick at gmail.com Sat Feb 14 15:40:09 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 14 Feb 2015 09:40:09 -0500 Subject: [Tutor] sql-like join on two lists or dictionaries In-Reply-To: References: <1423877077.197303.227364393.5C66E157@webmail.messagingengine.com> Message-ID: On Sat, Feb 14, 2015 at 8:03 AM, Alan Gauld wrote: > On 14/02/15 09:55, Peter Otten wrote: > > with open(headerfile) as f: >> lookup_header = { >> headerdata[:6]: headerdata.rstrip("\n") for headerdata in f} >> >> Then you can iterate over the lines in linefile, extract the key from that >> and look it up in the dict: >> >> with open(linefile) as lines, open("hl.dat", "w") as joined: >> for line in lines: >> try: >> header = lookup_header[line[:6]] >> except KeyError: >> header = "" >> print(line.rstrip("\n"), header, sep="", file=joined) >> >> > The try/except could be written more concisely as > > header = lookup_header.get(line[:6], "") > > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > You can dispense with the slicing if you use the str.split() method. It > will put each item in a list. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From davea at davea.name Sat Feb 14 19:17:37 2015 From: davea at davea.name (Dave Angel) Date: Sat, 14 Feb 2015 13:17:37 -0500 Subject: [Tutor] trivial simple program..can it be made more concise? In-Reply-To: <20150214125156.GY2498@ando.pearwood.info> References: <36171548.1796544.1423883352134.JavaMail.zimbra@comcast.net> <1273312104.1797364.1423883848882.JavaMail.zimbra@comcast.net> <20150214090702.GU2498@ando.pearwood.info> <54DF3448.404@davea.name> <20150214125156.GY2498@ando.pearwood.info> Message-ID: <54DF9141.1010106@davea.name> On 02/14/2015 07:51 AM, Steven D'Aprano wrote: > On Sat, Feb 14, 2015 at 06:40:56AM -0500, Dave Angel wrote: >> On 02/14/2015 04:07 AM, Steven D'Aprano wrote: >>> On Sat, Feb 14, 2015 at 03:17:28AM +0000, steve10brink at comcast.net wrote: > > [...] >>>> for i in range (a): >>>> print i, '\r', > [...] > >>> BUT I'm not sure why you are worried about making it more concise when >>> your code doesn't do what you want, as far as I can tell. You want the >>> counter to be written on the same line, not 640 thousand lines, but when >>> I try it, I get each number written to a different line. >> >> That's probably because you've dropped the trailing comma that the OP >> used in the print statements. > > So I did :-( > > Have I mentioned recently just how awesome Python 3's print is? > > for i in range(100000): > print(i, end='\r') > > Much nicer :-) > > Agreed. But don't you need " \r" so when you're counting down you don't have the trailing crud? The space was implicit on Python 2, because it mistakenly thought the code was printing two elements. -- DaveA From unee0x at gmail.com Sat Feb 14 23:12:59 2015 From: unee0x at gmail.com (Unee0x) Date: Sat, 14 Feb 2015 17:12:59 -0500 Subject: [Tutor] Mobile apps in Python Message-ID: <20B3A9FC-3BA5-4CC5-AFB0-7437B274625E@gmail.com> I am a fairly new student of Python, and so far I've been impressed with the speed,ease and comfort of it. In the near future, I would like to build 3d graphical mobile games. Is there any platform out there that would allow me to build 3d mobile apps using the Python language exclusively? Thanks in advance From steve at pearwood.info Sun Feb 15 03:22:04 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 15 Feb 2015 13:22:04 +1100 Subject: [Tutor] Mobile apps in Python In-Reply-To: <20B3A9FC-3BA5-4CC5-AFB0-7437B274625E@gmail.com> References: <20B3A9FC-3BA5-4CC5-AFB0-7437B274625E@gmail.com> Message-ID: <20150215022204.GD2498@ando.pearwood.info> On Sat, Feb 14, 2015 at 05:12:59PM -0500, Unee0x wrote: > I am a fairly new student of Python, and so far I've been impressed > with the speed,ease and comfort of it. In the near future, I would > like to build 3d graphical mobile games. Is there any platform out > there that would allow me to build 3d mobile apps using the Python > language exclusively? Oh, if only there were a website where you could type in simple queries and have the website search the entire Internet for an answer! https://duckduckgo.com/html/?q=how+to+search+the+internet http://www.google.com.au/search?q=how+to+search+the+internet *wink* If you search for "Python mobile apps", e.g. using this: https://startpage.com/do/search/?q=Python+mobile+apps then the top search result that comes up is for Kivy: http://kivy.org/ which is probably the most popular of the mobile app frameworks for Python. Searching for 3D apps: http://www.bing.com/search?q=python+3d+mobile+apps also suggests PyMob and QPython. -- Steve From wolfrage8765 at gmail.com Sun Feb 15 05:21:45 2015 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Sat, 14 Feb 2015 23:21:45 -0500 Subject: [Tutor] Mobile apps in Python In-Reply-To: <20B3A9FC-3BA5-4CC5-AFB0-7437B274625E@gmail.com> References: <20B3A9FC-3BA5-4CC5-AFB0-7437B274625E@gmail.com> Message-ID: I definitely recommend Kivy. I have enjoyed great success with it, and it was very easy to port my code to work on Android. From anubhav1691 at gmail.com Sun Feb 15 09:51:35 2015 From: anubhav1691 at gmail.com (Anubhav Yadav) Date: Sun, 15 Feb 2015 14:21:35 +0530 Subject: [Tutor] Does anyone here has the problems of CS231 saved? Message-ID: I used to solve the programming problems of the CS231 course of the Michigan State University, they had many python programming problems listed on a website [1]. Now suddenly the website seems to be down and I was wondering if anyone has a local copy of this problems with them and is willing to share with me? There were about 10-12 good problems each on topics on the following concepts: 1) First Steps 2) Control statements 3) Working with strings 4) Functions 5) List and tuples 6) Dictionaries and sets 7) Classes and Class Designs And the problems were nicely mixed with concepts from gui programming, game programming, they used modules like turtle graphics etc. There even used to concepts from natural language processing or information retrieval. So if someone does have a copy of the all the examples, please share it with me. There used to be a pdf for each problem statement clearly explaining what needs to be done with the examples. So I wonder if someone has saved all the pdf's it would be really helpful. There is also a cached version of the website [2]. But I am not able to access the problem links in the cached contents. Worst case if no one has a copy to all the examples, can someone suggest me a different website with python programming assignments for the same purpose? Thank you. [1] http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/ [2] http://webcache.googleusercontent.com/search?q=cache:http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/ -- Regards, Anubhav Yadav From __peter__ at web.de Sun Feb 15 11:06:22 2015 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Feb 2015 11:06:22 +0100 Subject: [Tutor] Does anyone here has the problems of CS231 saved? References: Message-ID: Anubhav Yadav wrote: > I used to solve the programming problems of the CS231 course of the > Michigan State University, they had many python programming problems > listed on a website [1]. > > Now suddenly the website seems to be down and I was wondering if anyone > has a local copy of this problems with them and is willing to share with > me? Looks like the Internet Archive has a copy from 2013-Jun-23: From anubhav1691 at gmail.com Sun Feb 15 11:36:15 2015 From: anubhav1691 at gmail.com (Anubhav Yadav) Date: Sun, 15 Feb 2015 16:06:15 +0530 Subject: [Tutor] Does anyone here has the problems of CS231 saved? In-Reply-To: References: Message-ID: > > Looks like the Internet Archive has a copy from 2013-Jun-23: > > < > https://web.archive.org/web/*/http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/ > > > > > Thanks a lot. That helps a lot. Although the problems are very less in comparison to the ones that were latest, I think I can do with it. Thanks again. -- Regards, Anubhav Yadav KPIT Technologies, Pune. From __peter__ at web.de Sun Feb 15 20:14:11 2015 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Feb 2015 20:14:11 +0100 Subject: [Tutor] sql-like join on two lists or dictionaries References: <1423877077.197303.227364393.5C66E157@webmail.messagingengine.com> Message-ID: Joel Goldstick wrote: > You can dispense with the slicing if you use the str.split() method. It > will put each item in a list. Only if there are no whitespace chars in the field. OT: Joel, your comments are already quoted when you first post them. Something is broken in your workflow. From __peter__ at web.de Sun Feb 15 20:36:03 2015 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Feb 2015 20:36:03 +0100 Subject: [Tutor] sql-like join on two lists or dictionaries References: <1423877077.197303.227364393.5C66E157@webmail.messagingengine.com> Message-ID: Alan Gauld wrote: > On 14/02/15 09:55, Peter Otten wrote: > >> with open(headerfile) as f: >> lookup_header = { >> headerdata[:6]: headerdata.rstrip("\n") for headerdata in f} >> >> Then you can iterate over the lines in linefile, extract the key from >> that and look it up in the dict: >> >> with open(linefile) as lines, open("hl.dat", "w") as joined: >> for line in lines: >> try: >> header = lookup_header[line[:6]] >> except KeyError: >> header = "" >> print(line.rstrip("\n"), header, sep="", file=joined) >> > > The try/except could be written more concisely as > > header = lookup_header.get(line[:6], "") Yep, I originally had something like for line in lines: try: header = lookup_header[line[:6]] except KeyError: contine print(...) in mind. By the way, the print(..., sep="", ...) # no idea why I did this is wrong and should be omitted. Also, you (OP) probably don't want the key column to appear twice in the output, so the second occurence can be sliced off: print(line.rstrip("\n"), header[6:], file=joined) From taylor.hazug at gmail.com Mon Feb 16 02:26:35 2015 From: taylor.hazug at gmail.com (Tina Figz) Date: Sun, 15 Feb 2015 19:26:35 -0600 Subject: [Tutor] Python Help with Program Message-ID: I'm having a problem with my program and I'm not sure how to correct it (I'm in an intro programming class). My program is supposed two numbers and count the number of carry operations. This is what I have: n1 = int(raw_input('Number #1: ')) n2 = int(raw_input('Number #2: ')) add = n1 + n2 print ' ' print n1, '+', n2, '=', add print ' ' sn1 = str(n1) sn2 = str(n2) num1 = 1 num2 = 1 num1 == num2 last_n1 = sn1[-num1] last_n2 = sn2[-num2] int_lastn1 = int(last_n1) int_lastn2 = int(last_n2) eq = int_lastn1 + int_lastn2 carry = 0 while eq >= 10 and carry < len(sn1) and carry < len(sn2): num1 += 1 num2 += 1 carry += 1 print 'Number of carries:', carry When I input 239 & 123 as my two numbers it equals 362, which is correct. But it says I have 3 carries, when the answer should be 1 carry operation. I'm not sure how to correct this error. Thanks, Taylor From alan.gauld at btinternet.com Mon Feb 16 09:24:01 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Feb 2015 08:24:01 +0000 Subject: [Tutor] Python Help with Program In-Reply-To: References: Message-ID: On 16/02/15 01:26, Tina Figz wrote: > I'm having a problem with my program and I'm not sure how to correct it > (I'm in an intro programming class). > > My program is supposed two numbers and count the number of carry > operations. > > This is what I have: > > n1 = int(raw_input('Number #1: ')) > n2 = int(raw_input('Number #2: ')) > add = n1 + n2 > print ' ' > print n1, '+', n2, '=', add Down to here everything is ok and you get the sum of the two numbers > sn1 = str(n1) > sn2 = str(n2) > num1 = 1 > num2 = 1 > num1 == num2 This line doesn't do anything. > last_n1 = sn1[-num1] > last_n2 = sn2[-num2] > int_lastn1 = int(last_n1) > int_lastn2 = int(last_n2) > eq = int_lastn1 + int_lastn2 > carry = 0 Before entering the loop you have (for your example) sn1 = '239', sn2 = '123' num1 = 1, num2 = 1 last_n1 = '9',last_n2 = '3', int_lastn1 = 9, int_lastn2 = 3 eq = 12 carry = 0 > while eq >= 10 and carry < len(sn1) and carry < len(sn2): > num1 += 1 > num2 += 1 > carry += 1 Your loop only changes num1, num2 and carry. But only carry is tested in the loop condition. So in effect you just keep adding 1 to carry until it is > then len(sn1 or len(sn2), ie 3. You are not changing anything else, so you are effectively just counting the number of characters in your shortest number. > When I input 239 & 123 as my two numbers it equals 362, which is correct. > But it says I have 3 carries, when the answer should be 1 carry operation. You need to completely redesign your algorithm. Try writing it out using pen and paper to figure out how you would do it manually. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Mon Feb 16 09:51:32 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 16 Feb 2015 08:51:32 +0000 Subject: [Tutor] Python Help with Program In-Reply-To: References: Message-ID: On 16/02/2015 08:24, Alan Gauld wrote: > On 16/02/15 01:26, Tina Figz wrote: >> I'm having a problem with my program and I'm not sure how to correct it >> (I'm in an intro programming class). >> >> My program is supposed two numbers and count the number of carry >> operations. >> >> This is what I have: >> >> n1 = int(raw_input('Number #1: ')) >> n2 = int(raw_input('Number #2: ')) >> add = n1 + n2 > > print ' ' > > print n1, '+', n2, '=', add > > Down to here everything is ok and you get the sum of the two numbers > > >> sn1 = str(n1) >> sn2 = str(n2) >> num1 = 1 >> num2 = 1 >> num1 == num2 > > This line doesn't do anything. > >> last_n1 = sn1[-num1] >> last_n2 = sn2[-num2] >> int_lastn1 = int(last_n1) >> int_lastn2 = int(last_n2) >> eq = int_lastn1 + int_lastn2 >> carry = 0 > > Before entering the loop you have (for your example) > sn1 = '239', sn2 = '123' num1 = 1, num2 = 1 > last_n1 = '9',last_n2 = '3', int_lastn1 = 9, int_lastn2 = 3 > eq = 12 > carry = 0 > >> while eq >= 10 and carry < len(sn1) and carry < len(sn2): >> num1 += 1 >> num2 += 1 >> carry += 1 > > Your loop only changes num1, num2 and carry. > But only carry is tested in the loop condition. > So in effect you just keep adding 1 to carry > until it is > then len(sn1 or len(sn2), ie 3. > > You are not changing anything else, so you are effectively > just counting the number of characters in your shortest > number. > >> When I input 239 & 123 as my two numbers it equals 362, which is correct. >> But it says I have 3 carries, when the answer should be 1 carry >> operation. > > You need to completely redesign your algorithm. > Try writing it out using pen and paper to figure > out how you would do it manually. > I'd start this exercise at line 1 and work right the way through the code, e.g. why bother doing all the work to get sn1 and sn2? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From steve at pearwood.info Mon Feb 16 13:17:22 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 16 Feb 2015 23:17:22 +1100 Subject: [Tutor] Python Help with Program In-Reply-To: References: Message-ID: <20150216121721.GM2498@ando.pearwood.info> Hi Tina, or Taylor, welcome! Sorry but your email "From" header says your name is Tina and your signature says Taylor so I'm not sure which name you prefer. On Sun, Feb 15, 2015 at 07:26:35PM -0600, Tina Figz wrote: > I'm having a problem with my program and I'm not sure how to correct it > (I'm in an intro programming class). > > My program is supposed two numbers and count the number of carry > operations. Let's start by working it out using pencil and paper. Write down two numbers, lined up on the right: 472837 29152 for example. Let's go through and check for carries: Number of carries so far: 0 7 and 2 = 9, no carry. 3 and 5 = 8, no carry. 8 and 1 = 9, no carry 2 and 9 = 11, carry the 1. Add one to the number of carries. 7 and 2, plus the 1 we carried, = 10, carry the 1. So add one to number of carries. 4, plus the 1 we carried, = 5, no carry. So the number of carries is two. The process is to take the digits of each number, starting from the right-hand end, in pairs. If you run out of digits for one number before the other, use 0. Add the two digits together, plus any carry digit from before, and if the result is larger than 9, there's a carry. We start with the number of carries equal to 0, and add 1 to that *only* if adding the pair of digits is larger than 9. Let's see what you have: [snip part of the code] > eq = int_lastn1 + int_lastn2 > carry = 0 > while eq >= 10 and carry < len(sn1) and carry < len(sn2): > num1 += 1 > num2 += 1 > carry += 1 You start on the right track: you check whether the last two digits add to more than 9. But, you never check the next two digits, or the two after that. You calculate "eq" (which is not a good name, by the way) once, outside the loop, but never calculate it again with any additional digits. Instead, you add 1 to carry *every single time*, regardless of the digits (apart from the first). Fun fact: (well, not that fun) you have to repeat the calculation each time through the loop, otherwise you're just using the same result over and over again. Example: py> my_string = "12345" py> position = -1 py> total = int(my_string[position]) + 1000 py> while position > -len(my_string): ... print(total) ... position = position - 1 ... 1005 1005 1005 1005 The total never changes, because we never re-calculate it. Instead: py> my_string = "12345" py> position = -1 py> while position > -len(my_string): ... total = int(my_string[position]) + 1000 ... print(total) ... position = position - 1 ... 1005 1004 1003 1002 Does that help you see why your code counts the wrong number of carries, and help you fix it? -- Steve From courtneyelizabeth983 at gmail.com Mon Feb 16 17:27:04 2015 From: courtneyelizabeth983 at gmail.com (Courtney Skinner) Date: Mon, 16 Feb 2015 11:27:04 -0500 Subject: [Tutor] Help with program Message-ID: <19E50925-D4C3-4DE6-9574-C97904AE2C82@gmail.com> Hello, I am trying to build a program that approximates the value of cosine - this is my program so far. It is not returning the right values. Could you tell me what I am doing wrong? def main(): import math print("This program approximates the cosine of x by summing") print("the terms of this series: x^0 / 0!, -x^2 / 2!,") print("x^4 / 4!, -x^6 / 6!...") n = eval(input("How many terms should be used? ")) x = eval(input("What value should be used for x? ")) s = 1 d = 1 e = 1 value = 0 for i in range(n - 1): value = value + s + (x**e / math.factorial(d)) s = s * 1 e = e + 2 d + d + 2 print("Approximation for cos(x) calculated by this program: ") print(value) print() difference = math.cos(x) - value print("Difference between this value and math.cos(x): ") print(difference) main() Thank you! C.Skinner From breamoreboy at yahoo.co.uk Mon Feb 16 19:45:38 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 16 Feb 2015 18:45:38 +0000 Subject: [Tutor] Help with program In-Reply-To: <19E50925-D4C3-4DE6-9574-C97904AE2C82@gmail.com> References: <19E50925-D4C3-4DE6-9574-C97904AE2C82@gmail.com> Message-ID: On 16/02/2015 16:27, Courtney Skinner wrote: > Hello, > > I am trying to build a program that approximates the value of cosine - this is my program so far. It is not returning the right values. Could you tell me what I am doing wrong? > > > def main(): > > import math Not that it matters but imports are usually done at the top of the module. > > print("This program approximates the cosine of x by summing") > print("the terms of this series: x^0 / 0!, -x^2 / 2!,") > print("x^4 / 4!, -x^6 / 6!...") > > n = eval(input("How many terms should be used? ")) > x = eval(input("What value should be used for x? ")) *DON'T* use eval, it's potentially dangerous. n = int(input("How many terms should be used? ")) x = float(input("What value should be used for x? ")) > > s = 1 > d = 1 > e = 1 > > value = 0 > > for i in range(n - 1): Are you aware that this will count from zero to n - 2? > value = value + s + (x**e / math.factorial(d)) > > s = s * 1 > e = e + 2 > d + d + 2 Whoops :) > print("Approximation for cos(x) calculated by this program: ") > print(value) > print() > > difference = math.cos(x) - value > > print("Difference between this value and math.cos(x): ") > print(difference) > > main() We'd usually write:- if __name__ == "__main__": main() > > Thank you! > > C.Skinner -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at btinternet.com Mon Feb 16 19:55:23 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Feb 2015 18:55:23 +0000 Subject: [Tutor] Help with program In-Reply-To: <19E50925-D4C3-4DE6-9574-C97904AE2C82@gmail.com> References: <19E50925-D4C3-4DE6-9574-C97904AE2C82@gmail.com> Message-ID: On 16/02/15 16:27, Courtney Skinner wrote: > Hello, > > I am trying to build a program that approximates the value of cosine > def main(): > > import math Its usual to do the imports outside the function at the tyop of the file. Python doesn't actually care much but its 'standard practice'. > print("This program approximates the cosine of x by summing") > print("the terms of this series: x^0 / 0!, -x^2 / 2!,") > print("x^4 / 4!, -x^6 / 6!...") > > n = eval(input("How many terms should be used? ")) > x = eval(input("What value should be used for x? ")) Don't use eval(). Use int() for the first one and float() for the second. eval() is a security hazard and potentially dangerous. > s = 1 > d = 1 > e = 1 > value = 0 > > for i in range(n - 1): > value = value + s + (x**e / math.factorial(d)) Your description says you subtract every second value (eg -x**2/2!) You are adding them all. Also you are adding 1(s) every time, surely you just want to add it the first time. In other words you want value to start at 1 and the loop to iterate from 2-(n-1)? You also want a sign multiplier which toggles between +/-1 Also you can get Python to do most the work for you by specifying a third step-size argument to range: ... for e in range(2, (n*2)+1, 2): #step by 2 value += (x**e)/math.factorial(e) * sign ... You no longer need any of the other increments or variables. > s = s * 1 > e = e + 2 > d + d + 2 > print("Approximation for cos(x) calculated by this program: ") > print(value) > print() You probably want all of these outside the loop. You might like to add a print(value) though while you are debugging. > > difference = math.cos(x) - value > > print("Difference between this value and math.cos(x): ") > print(difference) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Mon Feb 16 20:04:03 2015 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Feb 2015 20:04:03 +0100 Subject: [Tutor] Help with program References: <19E50925-D4C3-4DE6-9574-C97904AE2C82@gmail.com> Message-ID: Courtney Skinner wrote: > Hello, > > I am trying to build a program that approximates the value of cosine - > this is my program so far. It is not returning the right values. Could you > tell me what I am doing wrong? > > > def main(): > > import math > > print("This program approximates the cosine of x by summing") > print("the terms of this series: x^0 / 0!, -x^2 / 2!,") > print("x^4 / 4!, -x^6 / 6!...") > > n = eval(input("How many terms should be used? ")) > x = eval(input("What value should be used for x? ")) Consider the more restrictive int() and float() instead of eval(). > s = 1 A nice suggestive name like "sign" instead of "s" might help you with your debugging efforts. Of course the same goes for your other names. > d = 1 > e = 1 > > value = 0 > > for i in range(n - 1): > value = value + s + (x**e / math.factorial(d)) With the name suggested above the error value = value + sign + (x**e / math.factorial(d)) should almost be obvious. sign plus? wait what... Add print("current exponent", e) to see another problem. > > s = s * 1 That shows signs of a missing sign ;) > e = e + 2 > d + d + 2 > > > > print("Approximation for cos(x) calculated by this program: ") > print(value) > print() > > difference = math.cos(x) - value > > print("Difference between this value and math.cos(x): ") > print(difference) > > main() > > Thank you! > > C.Skinner From robertvstepp at gmail.com Mon Feb 16 20:52:16 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Mon, 16 Feb 2015 13:52:16 -0600 Subject: [Tutor] What are *appropriate* uses for exec() and eval() ? Message-ID: I have heard periodically about the potential evils of using exec() and eval(), including today, on this list. I gather that the first requirement for safely using these functions is that the passed argument MUST be from a trusted source. So what would be examples where the use of these functions IS appropriate? -- boB From beachkidken at gmail.com Mon Feb 16 22:26:17 2015 From: beachkidken at gmail.com (Ken G.) Date: Mon, 16 Feb 2015 16:26:17 -0500 Subject: [Tutor] Popen was deprecated since Python 2.6, now what? Message-ID: <54E26079.5090500@gmail.com> Wow, just found out this morning that the following terms of: import os pr = os.popen("lpr", "w") pr.write(month), pr.write(" "), pr.write("\t\tLine ") was deprecated. In place there of, there is a subprocess to use. I have not been able to figure out on how to use a subprocess in place of my former popen. I have been reading the new materials on the subprocess all day and it is still not quite understandable. Is there an easy tutorial of how to replace popen with the subprocess? I am using Python 2.7.6 on an Ubuntu 14.04.1 system. In advance, thanking you all for your assistance. Ken From dyoo at hashcollision.org Mon Feb 16 23:11:06 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 16 Feb 2015 14:11:06 -0800 Subject: [Tutor] Popen was deprecated since Python 2.6, now what? In-Reply-To: <54E26079.5090500@gmail.com> References: <54E26079.5090500@gmail.com> Message-ID: On Mon, Feb 16, 2015 at 1:26 PM, Ken G. wrote: > Wow, just found out this morning that the following > terms of: > > import os > pr = os.popen("lpr", "w") > pr.write(month), pr.write(" "), > pr.write("\t\tLine ") > > was deprecated. In place there of, there is > a subprocess to use. Hi Ken, Yes: subprocess.Popen(), along with Popen.communicate(), are what you want to look at. For your example above, the change is relatively direct: ############################################## import subprocess pr = subprocess.Popen(['lpr', 'w']) pr.communicate(month + ' ' + '\t\tLine ') ############################################## The main difference between this and what you had earlier is that you send all the input at once using Popen.communicate(). There's a quick-and-dirty section in the documentation for converting from the os.popen call to the subprocess equivalents. See: https://docs.python.org/2/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3 From dyoo at hashcollision.org Mon Feb 16 23:18:24 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 16 Feb 2015 14:18:24 -0800 Subject: [Tutor] What are *appropriate* uses for exec() and eval() ? In-Reply-To: References: Message-ID: On Mon, Feb 16, 2015 at 11:52 AM, boB Stepp wrote: > I have heard periodically about the potential evils of using exec() > and eval(), including today, on this list. I gather that the first > requirement for safely using these functions is that the passed > argument MUST be from a trusted source. So what would be examples > where the use of these functions IS appropriate? Given that there are language environments that do perfectly ok without those functions, the flippant answer would be: those functions aren't necessary. But to be more serious: they'd probably be most useful when you're defining your own interactive programming environment. For example, consider a debugger or an IDE (such as IDLE. Or if you come from the Java world, imagine Eclipse). In a debugger, you're running another program, and allowing the user to do something programmatic in the context of that program. Setting breakpoints, or looking at the value of certain expressions. In this scenario, we want to be able to access the same runtime data structures that drive the running program... within the program itself! It's this introspection that drives the need for an eval or exec. Enormously powerful. Enormously dangerous in the wrong hands. That being said, almost all programs are neither debuggers nor IDEs at their heart. (Despite the joke that every program strives to become Emacs at a certain point.) From alan.gauld at btinternet.com Tue Feb 17 00:26:12 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Feb 2015 23:26:12 +0000 Subject: [Tutor] Popen was deprecated since Python 2.6, now what? In-Reply-To: <54E26079.5090500@gmail.com> References: <54E26079.5090500@gmail.com> Message-ID: On 16/02/15 21:26, Ken G. wrote: > I have not been able to figure out on how to use a > subprocess in place of my former popen. I have been > reading the new materials on the subprocess all day > and it is still not quite understandable. Here is what the docs say: ########################################################### 17.5.5.5. Replacing os.popen(), os.popen2(), os.popen3() (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdin, child_stdout) = (p.stdin, p.stdout) (child_stdin, child_stdout, child_stderr) = os.popen3(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) (child_stdin, child_stdout, child_stderr) = (p.stdin, p.stdout, p.stderr) (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) ==> p = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) Return code handling translates as follows: pipe = os.popen(cmd, 'w') ... rc = pipe.close() if rc is not None and rc >> 8: print("There were some errors") ==> process = Popen(cmd, 'w', stdin=PIPE) ... process.stdin.close() if process.wait() != 0: print("There were some errors") 17.5.5.6. Replacing functions from the popen2 module Note If the cmd argument to popen2 functions is a string, the command is executed through /bin/sh. If it is a list, the command is directly executed. (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) ==> p = Popen("somestring", shell=True, bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode) ==> p = Popen(["mycmd", "myarg"], bufsize=bufsize, stdin=PIPE, stdout=PIPE, close_fds=True) (child_stdout, child_stdin) = (p.stdout, p.stdin) popen2.Popen3 and popen2.Popen4 basically work as subprocess.Popen, except that: Popen raises an exception if the execution fails. the capturestderr argument is replaced with the stderr argument. stdin=PIPE and stdout=PIPE must be specified. popen2 closes all file descriptors by default, but you have to specify close_fds=True with Popen to guarantee this behavior on all platforms or past Python versions. ############################################################# Which bits of that don't you understand? That way we have something concrete to work with. For example, Your popen program: import os pr = os.popen("lpr", "w") pr.write(month), pr.write(" "), pr.write("\t\tLine ") Translates according to the above as import subprocess as sub pr = sub.Popen(["lpr"], stdin = sub.PIPE) pr.stdin.write(month) pr.stdin.write(" ") pr.stdin.close() if pr.wait() != 0: print 'Errors!' Now, how can we help further clarify things? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From beachkidken at gmail.com Tue Feb 17 01:10:56 2015 From: beachkidken at gmail.com (Ken G.) Date: Mon, 16 Feb 2015 19:10:56 -0500 Subject: [Tutor] Popen was deprecated since Python 2.6, now what? In-Reply-To: References: <54E26079.5090500@gmail.com> Message-ID: <54E28710.6030108@gmail.com> On 02/16/2015 05:11 PM, Danny Yoo wrote: > On Mon, Feb 16, 2015 at 1:26 PM, Ken G. wrote: >> Wow, just found out this morning that the following >> terms of: >> >> import os >> pr = os.popen("lpr", "w") >> pr.write(month), pr.write(" "), >> pr.write("\t\tLine ") >> >> was deprecated. In place there of, there is >> a subprocess to use. > Hi Ken, > > > Yes: subprocess.Popen(), along with Popen.communicate(), are what you > want to look at. > > For your example above, the change is relatively direct: > > ############################################## > import subprocess > pr = subprocess.Popen(['lpr', 'w']) > pr.communicate(month + ' ' + '\t\tLine ') > ############################################## > > The main difference between this and what you had earlier is that you > send all the input at once using Popen.communicate(). > > There's a quick-and-dirty section in the documentation for converting > from the os.popen call to the subprocess equivalents. See: > > https://docs.python.org/2/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3 > . Thank you for helping me get on the road here. I printed out your response and I'll be playing with it. Ken From beachkidken at gmail.com Tue Feb 17 01:12:45 2015 From: beachkidken at gmail.com (Ken G.) Date: Mon, 16 Feb 2015 19:12:45 -0500 Subject: [Tutor] Popen was deprecated since Python 2.6, now what? In-Reply-To: References: <54E26079.5090500@gmail.com> Message-ID: <54E2877D.60408@gmail.com> On 02/16/2015 06:26 PM, Alan Gauld wrote: > On 16/02/15 21:26, Ken G. wrote: >> I have not been able to figure out on how to use a >> subprocess in place of my former popen. I have been >> reading the new materials on the subprocess all day >> and it is still not quite understandable. > > > Here is what the docs say: > > ########################################################### > 17.5.5.5. Replacing os.popen(), os.popen2(), os.popen3() > > (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize) > ==> > p = Popen(cmd, shell=True, bufsize=bufsize, > stdin=PIPE, stdout=PIPE, close_fds=True) > (child_stdin, child_stdout) = (p.stdin, p.stdout) > > > > > (child_stdin, > child_stdout, > child_stderr) = os.popen3(cmd, mode, bufsize) > ==> > p = Popen(cmd, shell=True, bufsize=bufsize, > stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) > (child_stdin, > child_stdout, > child_stderr) = (p.stdin, p.stdout, p.stderr) > > > > > (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize) > ==> > p = Popen(cmd, shell=True, bufsize=bufsize, > stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True) > (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout) > > > > > > Return code handling translates as follows: > > pipe = os.popen(cmd, 'w') > ... > rc = pipe.close() > if rc is not None and rc >> 8: > print("There were some errors") > ==> > process = Popen(cmd, 'w', stdin=PIPE) > ... > process.stdin.close() > if process.wait() != 0: > print("There were some errors") > > > > 17.5.5.6. Replacing functions from the popen2 module > > Note > If the cmd argument to popen2 functions is a string, the command is > executed through /bin/sh. If it is a list, the command is directly > executed. > > > > (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode) > ==> > p = Popen("somestring", shell=True, bufsize=bufsize, > stdin=PIPE, stdout=PIPE, close_fds=True) > (child_stdout, child_stdin) = (p.stdout, p.stdin) > > > > (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], > bufsize, mode) > ==> > p = Popen(["mycmd", "myarg"], bufsize=bufsize, > stdin=PIPE, stdout=PIPE, close_fds=True) > (child_stdout, child_stdin) = (p.stdout, p.stdin) > > > popen2.Popen3 and popen2.Popen4 basically work as subprocess.Popen, > except that: > Popen raises an exception if the execution fails. > the capturestderr argument is replaced with the stderr argument. > stdin=PIPE and stdout=PIPE must be specified. > popen2 closes all file descriptors by default, > but you have to specify close_fds=True with Popen > to guarantee this behavior on all platforms or past Python versions. > ############################################################# > > Which bits of that don't you understand? > That way we have something concrete to work with. > > For example, Your popen program: > > import os > pr = os.popen("lpr", "w") > pr.write(month), pr.write(" "), > pr.write("\t\tLine ") > > Translates according to the above as > > import subprocess as sub > pr = sub.Popen(["lpr"], stdin = sub.PIPE) > pr.stdin.write(month) > pr.stdin.write(" ") > pr.stdin.close() > if pr.wait() != 0: print 'Errors!' > > Now, how can we help further clarify things? > Thank for the translation of the hard-to-read docs. Reading the docs threw me for a loop. I printed out your response and will be studying to try best understand it. Ken From dyoo at hashcollision.org Tue Feb 17 02:00:22 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 16 Feb 2015 17:00:22 -0800 Subject: [Tutor] Popen was deprecated since Python 2.6, now what? In-Reply-To: <54E2877D.60408@gmail.com> References: <54E26079.5090500@gmail.com> <54E2877D.60408@gmail.com> Message-ID: > Thank for the translation of the hard-to-read docs. Reading the docs threw > me for a loop. I printed out your response and will be studying to try best > understand it. No problem; feel free to ask questions on anything that doesn't make sense, and we'll try to help as best as we can. From steve at pearwood.info Tue Feb 17 03:15:26 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 17 Feb 2015 13:15:26 +1100 Subject: [Tutor] What are *appropriate* uses for exec() and eval() ? In-Reply-To: References: Message-ID: <20150217021525.GP2498@ando.pearwood.info> On Mon, Feb 16, 2015 at 01:52:16PM -0600, boB Stepp wrote: > I have heard periodically about the potential evils of using exec() > and eval(), including today, on this list. I gather that the first > requirement for safely using these functions is that the passed > argument MUST be from a trusted source. So what would be examples > where the use of these functions IS appropriate? The flippant reply would be "there aren't any". But that is not true. In the broader context of programming in general, not just Python, the use of eval/exec is incredibly powerful because it allows you to write dynamic code that uses information available at runtime to solve problems which cannot even be expressed at compile time. Think about it like this: A programming language is like a toolbox filled with tools for solving problems. You combine those tools like Lego blocks, combining them in different ways to make new tools. One of those Lego blocks is a robot, called eval or exec, which you can instruct to make new tools, instead of making them yourself. There are various downsides: the extra complexity of telling the robot which Lego blocks to use, instead of just directly using the blocks yourself, means that using the robot is slower, more complex, harder to read, error messages are less useful, and if your instructions contain data coming from strangers, they may be able to subvert your intention, sneak instructions into your code, and take control of the robot. But it means you can put off the decision for which Lego block to use until runtime when more information is available. exec is literally a Python interpreter embedded inside Python, so if you have a particularly hard problem to solve, one of the ways you can solve it is to write a program to *write a program to solve it*, then use exec to run that second program. All this discussion has been very abstract. Here are some concrete examples of good use of eval/exec. In the standard library, we have the timeit module which takes a code snippet from the user, executes it as Python code, and measures how long it takes. There's no way to take *code* from the user except as a string, if you type it directly Python will interpret it immediately. To delay execution, you have to put the code inside a string, and then later interpret the string as Python code. In other words, exec. Likewise, we have the doctest module. Inside your function docstrings, you can write samples of interactive output: def spam(n): """Return n lots of spam. >>> spam(3) 'spam spam spam' """ ... The doctest module scans the docstring, extracts anything which looks like interactive output (starting with >>> prompt), execs that text as Python code, and checks that the output matches what you gave it. Your sample code is *executable documentation*, so long as you remember to run dotest over it, you can always be sure that the sample code is correct. In the collections module, there is a factory function called namedtuple for creating record-like tuples with named fields. How it works is you provide the name of the fields, they get plugged into a class definition template, and the template executed as Python code, which creates a new class. That class is returned for you to use: py> from collections import namedtuple py> Record = namedtuple("Record", "x y z") py> point = Record(23, 42, 19) py> print(point) Record(x=23, y=42, z=19) py> point.x 23 Here is the original version which eventually became part of the collections module: http://code.activestate.com/recipes/500261-named-tuples/ Here is a fork of that recipe. It uses an inner class for the new namedtuple class. The only thing which needs exec is the __new__ method. http://code.activestate.com/recipes/578918-yet-another-namedtuple/ This demonstrates a powerful truth about Python: *most of the time* you don't need to use exec or eval because the standard language features are powerful enough to solve the problem for you. Using a dynamically created inner class is *almost* enough to solve this problem, only the __new__ method defeats it. If our requirements where just a little less demanding, we could avoid exec completely. In some languages, if you want to define functions are runtime, the only way to do it is to write a function template, fill in the blanks at runtime, then exec it: template = """ def add(x): return x + %s """ namespace = {} exec(template % 10, namespace) addTen = namespace['add'] print(addTen(23)) With Python, going to all that trouble is unnecessary: def factory(n): """Return a new function which adds n to its argument.""" def add(x): return x + n return add addTen = factory(10) print(addTen(23)) The result is easier to read, faster, and more secure. -- Steve From davea at davea.name Tue Feb 17 03:31:49 2015 From: davea at davea.name (Dave Angel) Date: Mon, 16 Feb 2015 21:31:49 -0500 Subject: [Tutor] Help with program In-Reply-To: <19E50925-D4C3-4DE6-9574-C97904AE2C82@gmail.com> References: <19E50925-D4C3-4DE6-9574-C97904AE2C82@gmail.com> Message-ID: <54E2A815.1080807@davea.name> On 02/16/2015 11:27 AM, Courtney Skinner wrote: > Hello, > > I am trying to build a program that approximates the value of cosine - this is my program so far. It is not returning the right values. Could you tell me what I am doing wrong? > > You've got several answers that point out several problems in your code. But I think you're missing a key concept. If you're faced with a problem that's beyond your present abilities, or that's got you stumped, always consider factoring the problem into simpler ones. To me the first thing you should factor out is a factorial function. Write one, that takes a positive int and returns the factorial, and test it against the one in the math library. Once it's correct, then use it in the cosine problem. Now you've got a simpler loop to write. And you know part of the code works. Next, see if you can avoid most of those three variables you're using. For example, What do you get when you calculate (-1) ** (i) Can you use that to simplify things? -- DaveA From jeanpierreda at gmail.com Tue Feb 17 04:10:21 2015 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Mon, 16 Feb 2015 19:10:21 -0800 Subject: [Tutor] What are *appropriate* uses for exec() and eval() ? In-Reply-To: <20150217021525.GP2498@ando.pearwood.info> References: <20150217021525.GP2498@ando.pearwood.info> Message-ID: On Mon, Feb 16, 2015 at 6:15 PM, Steven D'Aprano wrote: > Here is a fork of that recipe. It uses an inner class for the new > namedtuple class. The only thing which needs exec is the __new__ method. > > http://code.activestate.com/recipes/578918-yet-another-namedtuple/ > > This demonstrates a powerful truth about Python: *most of the time* you > don't need to use exec or eval because the standard language features > are powerful enough to solve the problem for you. Using a dynamically > created inner class is *almost* enough to solve this problem, only the > __new__ method defeats it. If our requirements where just a little less > demanding, we could avoid exec completely. No, exec is not necessary at all. If they had to the author could have reimplemented the argument assignment logic by hand. They chose not to because it is "too hard". (And it is.) Fortunately, they don't have to go that far: signature = inspect.Signature([ inspect.Parameter(field_name, inspect.Parameter.POSITIONAL_OR_KEYWORD) for field_name in field_names]) def __new__(cls, *args, **kwargs): return tuple.__new__(cls, signature.bind(*args, **kwargs).arguments.values()) -- Devin From cs at zip.com.au Tue Feb 17 04:20:38 2015 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 17 Feb 2015 14:20:38 +1100 Subject: [Tutor] What are *appropriate* uses for exec() and eval() ? In-Reply-To: References: Message-ID: <20150217032038.GA53906@cskk.homeip.net> On 16Feb2015 19:10, Devin Jeanpierre wrote: >On Mon, Feb 16, 2015 at 6:15 PM, Steven D'Aprano wrote: >> Here is a fork of that recipe. It uses an inner class for the new >> namedtuple class. The only thing which needs exec is the __new__ method. >> >> http://code.activestate.com/recipes/578918-yet-another-namedtuple/ >> >> This demonstrates a powerful truth about Python: *most of the time* you >> don't need to use exec or eval because the standard language features >> are powerful enough to solve the problem for you. Using a dynamically >> created inner class is *almost* enough to solve this problem, only the >> __new__ method defeats it. If our requirements where just a little less >> demanding, we could avoid exec completely. > >No, exec is not necessary at all. If they had to the author could have >reimplemented the argument assignment logic by hand. [... example...] I see your counter counter example and raise you another counter. One might use exec() to use code that is valid in one python version but not another, when you need your program to run in both i.e. to get code that is syntacticly invalid in one version, but to use it (conditionally) in another version. I only have one use case for this presently: I have a use of exec() in my cs.py3 python2/3 compatability module: def raise3(exc_type, exc_value, exc_traceback): if sys.hexversion >= 0x03000000: raise exc_type(exc_value).with_traceback(exc_traceback) else: # subterfuge to let this pass a python3 parser; ugly exec('raise exc_type, exc_value, exc_traceback') I'm using exec() here because a Python 3 interpreter will reject the 3 argument form of raise. Elsewhere in my code I just call cs.py3.raise3() with the requisite arguments. Note that the string passed to exec() is hardwired, not obtained from elsewhere in any form. Like all sane people, I consider using exec() a code smell: if you're using it you should consider heavily alternatives to it. Cheers, Cameron Simpson I think... Therefore I ride. I ride... Therefore I am. - Mark Pope From jeanpierreda at gmail.com Tue Feb 17 04:45:22 2015 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Mon, 16 Feb 2015 19:45:22 -0800 Subject: [Tutor] What are *appropriate* uses for exec() and eval() ? In-Reply-To: <20150217032038.GA53906@cskk.homeip.net> References: <20150217032038.GA53906@cskk.homeip.net> Message-ID: On Mon, Feb 16, 2015 at 7:20 PM, Cameron Simpson wrote: > One might use exec() to use code that is valid in one python version but not > another, when you need your program to run in both i.e. to get code that is > syntacticly invalid in one version, but to use it (conditionally) in another > version. > > I only have one use case for this presently: I have a use of exec() in my > cs.py3 python2/3 compatability module: > > def raise3(exc_type, exc_value, exc_traceback): > if sys.hexversion >= 0x03000000: > raise exc_type(exc_value).with_traceback(exc_traceback) > else: > # subterfuge to let this pass a python3 parser; ugly > exec('raise exc_type, exc_value, exc_traceback') > > I'm using exec() here because a Python 3 interpreter will reject the 3 > argument form of raise. Elsewhere in my code I just call cs.py3.raise3() > with the requisite arguments. Note that the string passed to exec() is > hardwired, not obtained from elsewhere in any form. I'd try conditional imports, first: if sys.hexversion >= ...: from .compat_py3 import raise3 else: from .compat_py2 import raise3 But maybe this breaks with the setuptools pre-compilation shenanigans? At any rate, I didn't mean to make a general statement. Obviously, sometimes exec/eval is necessary. If for no other reason than because sometimes the requirement is to use exec (e.g. if you are implementing something equivalent to python -i, etc.). -- Devin From leviadissi at gmail.com Tue Feb 17 05:22:57 2015 From: leviadissi at gmail.com (Levi Adissi) Date: Mon, 16 Feb 2015 20:22:57 -0800 Subject: [Tutor] Hey guys! Message-ID: So I'm kind of stuck trying to program a function that returns a list of tuples. The function takes 2 lists containing circles of which it should compare list1[0] to list2[0] to see if they intersect. If they intersect or touch then I should return them on a list of tuples(in the tuple would be both intersecting circles). I can't get circles_only to work the way I see it I'm comparing h to x only if they're both in the same place on the list (hence my "h==x") I know it doesn't work because the test returns None so I would really appreciate an alternative method if you guys see one. Here are my functions: def circles_overlap(c1, c2): x=(c2.center.y-c1.center.y)**2 y=(c2.center.x-c1.center.x)**2 distancemid=math.sqrt(x+y) distancerad=(c1.radius+c2.radius) if distancemid > distancerad: return 1 elif distancemid < distancerad: return -1 elif distancemid == distancerad: return 0 def circles_only(lst1, lst2): newlst=[] for h in lst1: for x in lst2: if h==x: if circles_overlap(lst1[h],lst2[x])== -1: newlst.append(lst1[h],lst2[x]) elif circles_overlap(lst1[h],lst2[x])== 0: newlst.append(lst1[h],lst2[x]) print newlst TEST CASE: def test_circles_olap1(self): list1=[data_2.Circle(data_2.Point(2,3), 2),data_2.Circle(data_2.Point(2,3), 2), data_2.Circle(data_2.Point(2,3), 2) ] list2=[data_2.Circle(data_2.Point(6,3), 2),data_2.Circle(data_2.Point(10,3), 2), data_2.Circle(data_2.Point(5,3), 2) ] testor=functions_2.circles_only(list1,list2) newlist=[(data_2.Circle(data_2.Point(2,3), 2),data_2.Circle(data_2.Point(6,3), 2)),(data_2.Circle(data_2.Point(2,3), 2),data_2.Circle(data_2.Point(10,3), 2))] self.assertEqual(testor, newlist) Thanks in advance! From alan.gauld at btinternet.com Tue Feb 17 09:45:34 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Feb 2015 08:45:34 +0000 Subject: [Tutor] Hey guys! In-Reply-To: References: Message-ID: On 17/02/15 04:22, Levi Adissi wrote: Hello. Thanks for your post. However could you please use a subject that rflects the content. Otherwise we wind up with an archive full of "Hey Guys", "Hello chaps", "Gday mate", Bonjour" etc Not very useful for searching. > So I'm kind of stuck trying to program a function that returns a list of > tuples. Note that your function prints the list it does not return the list. The two are very different. > The function takes 2 lists containing circles of which it should > compare list1[0] to list2[0] to see if they intersect. If they intersect or > touch then I should return them on a list of tuples(in the tuple would be > both intersecting circles). > > I can't get circles_only to work the way I see it I'm comparing h to x only > if they're both in the same place on the list (hence my "h==x") I know it > doesn't work because the test returns None so I would really appreciate an > alternative method if you guys see one. > > Here are my functions: > > > def circles_overlap(c1, c2): > x=(c2.center.y-c1.center.y)**2 > y=(c2.center.x-c1.center.x)**2 > distancemid=math.sqrt(x+y) > distancerad=(c1.radius+c2.radius) > if distancemid > distancerad: > return 1 > elif distancemid < distancerad: > return -1 > elif distancemid == distancerad: > return 0 > Since this is a test you should probably just return True or False. Either they overlap or they don't. If you want to use touching as a third result you can still give a boolean for the general case: return 1 for overlap -1 for touching 0 for not touching 1 and -1 both evaluate to True in a boolean sense 0 evaluates to False This makes the test code in your second function look like: if circles_overlap(c1,c2): newlst.append((c1,c2)) and you don't need the else clause > def circles_only(lst1, lst2): > newlst=[] > for h in lst1: > for x in lst2: > if h==x: Why do you have this test? You only check if they overlap when they are equal? That seems odd to me. Also h and x seem an odd choice of name for two circles. Why not for c1 in lst1: for c2 in lst2: > if circles_overlap(lst1[h],lst2[x])== -1: > newlst.append(lst1[h],lst2[x]) Now you are trying to use indexing to extract the circles but you are (quite rightly) iterating over the lists directly not using indexes. So h and x are circles, you don't need to get them out of the lists. Also you are trying to store two items in your newlist rather than a tuple. (See my suggested test above.) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From davea at davea.name Tue Feb 17 11:36:28 2015 From: davea at davea.name (Dave Angel) Date: Tue, 17 Feb 2015 05:36:28 -0500 Subject: [Tutor] Hey guys! In-Reply-To: References: Message-ID: <54E319AC.9010009@davea.name> On 02/16/2015 11:22 PM, Levi Adissi wrote: Thank you for using text email, rather than the html mail that so many newcomers use. > So I'm kind of stuck trying to program a function that returns a list of > tuples. The function takes 2 lists containing circles of which it should > compare list1[0] to list2[0] to see if they intersect. If they intersect or > touch then I should return them on a list of tuples(in the tuple would be > both intersecting circles). > > I can't get circles_only to work the way I see it I'm comparing h to x only > if they're both in the same place on the list (hence my "h==x") I know it > doesn't work because the test returns None so I would really appreciate an > alternative method if you guys see one. > > Here are my functions: > > > def circles_overlap(c1, c2): > x=(c2.center.y-c1.center.y)**2 > y=(c2.center.x-c1.center.x)**2 > distancemid=math.sqrt(x+y) > distancerad=(c1.radius+c2.radius) > if distancemid > distancerad: > return 1 > elif distancemid < distancerad: > return -1 > elif distancemid == distancerad: > return 0 > > def circles_only(lst1, lst2): > newlst=[] > for h in lst1: > for x in lst2: > if h==x: That's silly. You don't want to compare the two circles to see if they're equal. Remove this line. > if circles_overlap(lst1[h],lst2[x])== -1: Why don't you tell us the exception this line causes? lst1 is subscripted by integers, not by circle objects. What you really want in this line is something like: if circles_overlap(h, x) ! = 1: newlst.append(h, x) > newlst.append(lst1[h],lst2[x]) > > elif circles_overlap(lst1[h],lst2[x])== 0: > newlst.append(lst1[h],lst2[x]) > > print newlst Don't print it, return it. Otherwise, you're returning None. > > > TEST CASE: > > def test_circles_olap1(self): > list1=[data_2.Circle(data_2.Point(2,3), > 2),data_2.Circle(data_2.Point(2,3), 2), data_2.Circle(data_2.Point(2,3), 2) > ] > list2=[data_2.Circle(data_2.Point(6,3), > 2),data_2.Circle(data_2.Point(10,3), 2), data_2.Circle(data_2.Point(5,3), 2) > ] > testor=functions_2.circles_only(list1,list2) > newlist=[(data_2.Circle(data_2.Point(2,3), > 2),data_2.Circle(data_2.Point(6,3), 2)),(data_2.Circle(data_2.Point(2,3), > 2),data_2.Circle(data_2.Point(10,3), 2))] > self.assertEqual(testor, newlist) > The test code makes no sense to me at all. it's a method of some unspecified class, and it uses some namespaces called data_2 and functions_2 for an unknown purpose. -- -- DaveA From steve at pearwood.info Tue Feb 17 16:31:06 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 18 Feb 2015 02:31:06 +1100 Subject: [Tutor] What are *appropriate* uses for exec() and eval() ? In-Reply-To: References: <20150217021525.GP2498@ando.pearwood.info> Message-ID: <20150217153105.GT2498@ando.pearwood.info> On Mon, Feb 16, 2015 at 07:10:21PM -0800, Devin Jeanpierre wrote: > On Mon, Feb 16, 2015 at 6:15 PM, Steven D'Aprano wrote: > > Here is a fork of that recipe. It uses an inner class for the new > > namedtuple class. The only thing which needs exec is the __new__ method. > > > > http://code.activestate.com/recipes/578918-yet-another-namedtuple/ > > > > This demonstrates a powerful truth about Python: *most of the time* you > > don't need to use exec or eval because the standard language features > > are powerful enough to solve the problem for you. Using a dynamically > > created inner class is *almost* enough to solve this problem, only the > > __new__ method defeats it. If our requirements where just a little less > > demanding, we could avoid exec completely. > > No, exec is not necessary at all. I'm not sure that I said that exec was "necessary" anywhere, but since you mention it, how about the two earlier examples I gave, timeit and doctest? Especially doctest. How would you implement doctests without exec? Of course you could write your own Python parser, and build your own Python interpreter. But that's just re-inventing exec. And it would be horribly slow. Back in the very early days of PyPy, they wrote a Python interpreter using nothing but pure Python. It was about 100 times slower than the regular Python interpreter. Another reasonable use for exec is to develop your own language or mini-language. You generate Python code, compile it, then execute it. Template engines like Mako, Jinja2 and Genshi work like this, or so I am lead to believe. > If they had to the author could have > reimplemented the argument assignment logic by hand. They chose not to > because it is "too hard". (And it is.) Fortunately, they don't have > to go that far: > > signature = inspect.Signature([ > inspect.Parameter(field_name, inspect.Parameter.POSITIONAL_OR_KEYWORD) > for field_name in field_names]) Hmmm. Well, namedtuple was added to Python in version 2.6. [steve at ando ~]$ python2.6 Python 2.6.7 (r267:88850, Mar 10 2012, 12:32:58) [GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2 Type "help", "copyright", "credits" or "license" for more information. py> from inspect import Signature Traceback (most recent call last): File "", line 1, in ImportError: cannot import name Signature So much for that idea. Of course you are right that using exec is rarely the *only possible* way to solve a problem. But it's a tool like any other tool, we shouldn't be afraid to use it when it is the best tool for the job. The problem comes from people using it when it is the *wrong* tool for the job, or using it carelessly. -- Steve From robertvstepp at gmail.com Tue Feb 17 18:57:03 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 17 Feb 2015 11:57:03 -0600 Subject: [Tutor] Potential problem with Game Over 2.0 problem in "Python Programming for the Absolute Beginner, 3rd Ed." Message-ID: I know that there have been multiple posts in the past about Michael Dawson's book, "Python Programming for the Absolute Beginner, 3rd ed.". Because of this I thought I might mention something my son encountered this morning. I have finally gotten my son to start working in this book. He came to me with a problem this morning, which he could not figure out when trying to replicate the author's (Michael Dawson) Game Over 2.0 program in chapter two on page 17. The object of this program is to do ASCII-style art to generate a large rendition of "Game Over" using the following characters: "_" , "\" , "|" , and "/" . When my son tried to do his version, the "Over" portion did not print correctly. The top half of "Over" printed first followed by the second half of the word next to it. I don't want to say too much for those working through this book, but the essence of the issue is illustrated by the following: Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> print( """ boB Stepp """ ) boB Stepp >>> print( """ boB\ Stepp """ ) boBStepp This led to a discussion with my son about the invisible characters that terminate lines in Window and *nix, escape sequences, etc. Hopefully this might prove helpful to those starting this book without just giving the answer if this problem comes up in their efforts. -- boB From b.perezmila at gmail.com Tue Feb 17 14:49:43 2015 From: b.perezmila at gmail.com (Beatrice Perez) Date: Tue, 17 Feb 2015 13:49:43 +0000 Subject: [Tutor] mySQL and Python Message-ID: Hi, I am looking for tools to use mySQL and python. I saw in a question posted in Stack Overflow ( http://stackoverflow.com/questions/23376103/python-3-4-0-with-mysql-database) that mySQLdb is not compatible with python 3 but the post was 9 months ago. I haven't been able to find updated information (maybe because I'm not sure how to look...) I found the mySQL/Python connector but in the python versions supported, the last one listed is 3.3. I have 3.4 does this mean that it won't work? I have only ever used php with mySQL so I need some help. What would be the best library/extension to get? If I use mySQLdb or PyMySQL would I need the connector as well? thanks for your help, --Beatrice From dyoo at hashcollision.org Tue Feb 17 19:38:23 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 17 Feb 2015 10:38:23 -0800 Subject: [Tutor] mySQL and Python In-Reply-To: References: Message-ID: On Tue, Feb 17, 2015 at 5:49 AM, Beatrice Perez wrote: > I have only ever used php with mySQL so I need some help. What would be the > best library/extension to get? If I use mySQLdb or PyMySQL would I need the > connector as well? Unfortunately, I don't know. Since this is the Tutor mailing list, we help with general learning questions: database module installation questions are a little out of scope. You might get better MySQL and Python-specific help on the general mailing list: https://mail.python.org/mailman/listinfo/python-list I'd recommend checking with the. Let's see... From looking at the wiki: https://wiki.python.org/moin/MySQL I see that there's a "PyMySQL" library that is labeled as supporting Python 3, but I have no personal experience with it. From robertvstepp at gmail.com Tue Feb 17 20:12:23 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 17 Feb 2015 13:12:23 -0600 Subject: [Tutor] Potential problem with Game Over 2.0 problem in "Python Programming for the Absolute Beginner, 3rd Ed." In-Reply-To: References: Message-ID: On Tue, Feb 17, 2015 at 12:43 PM, Danny Yoo wrote: [...] > Ah ha. Escape characters. I see what you mean. :P > > > Just to add: there is a "raw" string literal syntax that will turn off > escape sequence handling. Using a raw string literal may make it > easier to type the value in question. > > We can use raw literal strings by prepending a 'r' in the front of the > string literal. e.g.: > > ########################################## >>>> x = r''' > ... this\ > ... is\ > ... a/ > ... test\ > ... ''' >>>> x > '\nthis\\\nis\\\na/\ntest\\\n' >>>> print x > > this\ > is\ > a/ > test\ > ########################################## Actually, that is the solution I recommended to my son to use. > It might be that the question is trying to motivate the use of raw > string literals, or teaching about escape sequences. I don't have the > book, so I can't say for sure. At this point in the text he is not talking about raw literal strings. I examined the author's source and he has obviously inserted at least one space between each use of a backslash at the end of a line and the EOL terminating characters. He did not do this with the "Game" portion of the code, which did not make any use of "\" . When the file is run everything behaves as desired. But if, as my son did, you leave no spaces between the last backslash and the EOL termination characters, then the problem behavior occurs. Actually, I realize I have a question: If I do the following in the Win7 command line Python interpreter: Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AM D64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print(""" ... boB\ ... Stepp ... """ ... ) boB\ Stepp Here I placed exactly one space between "\" and where I pressed "Enter". This would be the Game Over 2.0 desired behavior. However, if I bring up the IDLE Python interpreter and do the exact same thing: Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> print(""" boB\ Stepp """ ) boBStepp it gives the undesired behavior. I typed exactly the same character sequences, though IDLE displayed things slightly differently, e.g., the command line interpreter put in "..." in several places, where the IDLE interpreter did not. I am currently scratching my head on these differences, and am currently guessing that IDLE implements the Python interpreter somewhat differently than the implementation that occurs in the Windows command line. Do you have an explanation for these differences? -- boB From davea at davea.name Tue Feb 17 20:47:28 2015 From: davea at davea.name (Dave Angel) Date: Tue, 17 Feb 2015 14:47:28 -0500 Subject: [Tutor] Potential problem with Game Over 2.0 problem in "Python Programming for the Absolute Beginner, 3rd Ed." In-Reply-To: References: Message-ID: <54E39AD0.50606@davea.name> On 02/17/2015 02:12 PM, boB Stepp wrote: See https://docs.python.org/3.4/reference/lexical_analysis.html#string-and-bytes-literals > > At this point in the text he is not talking about raw literal strings. > I examined the author's source and he has obviously inserted at least > one space between each use of a backslash at the end of a line and the > EOL terminating characters. Then he's teaching you wrong. Backslash followed by space is not a valid escape sequence, and to do it at the end of line is particularly odious. I wouldn't even suggest it in real code, never mind in something that's published on paper. The docs admit that the invalid escape sequences behave differently than C, in that the backslash is retained. I think it should be a syntax error to have an invalid sequence. If the backslash immediately precedes the newline, then the two characters both get eaten, and the two lines are combined into one. That can be useful if you want to define a string that's too long to fit in your source file. I would never intentionally make any trailing whitespace in source code be significant. And years ago I used an editor that routinely deleted any such invisible characters. From the rest of your message, it looks like IDLE may have that behavior. > He did not do this with the "Game" portion > of the code, which did not make any use of "\" . When the file is run > everything behaves as desired. But if, as my son did, you leave no > spaces between the last backslash and the EOL termination characters, > then the problem behavior occurs. -- DaveA From dyoo at hashcollision.org Tue Feb 17 19:43:23 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 17 Feb 2015 10:43:23 -0800 Subject: [Tutor] Potential problem with Game Over 2.0 problem in "Python Programming for the Absolute Beginner, 3rd Ed." In-Reply-To: References: Message-ID: > Dawson) Game Over 2.0 program in chapter two on page 17. The object of > this program is to do ASCII-style art to generate a large rendition of > "Game Over" using the following characters: "_" , "\" , "|" , and "/" > . When my son tried to do his version, the "Over" portion did not > print correctly. Hi boB, Ah ha. Escape characters. I see what you mean. :P Just to add: there is a "raw" string literal syntax that will turn off escape sequence handling. Using a raw string literal may make it easier to type the value in question. We can use raw literal strings by prepending a 'r' in the front of the string literal. e.g.: ########################################## >>> x = r''' ... this\ ... is\ ... a/ ... test\ ... ''' >>> x '\nthis\\\nis\\\na/\ntest\\\n' >>> print x this\ is\ a/ test\ ########################################## It might be that the question is trying to motivate the use of raw string literals, or teaching about escape sequences. I don't have the book, so I can't say for sure. From dyoo at hashcollision.org Tue Feb 17 21:28:47 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 17 Feb 2015 12:28:47 -0800 Subject: [Tutor] Fwd: Need help with find error In-Reply-To: References: Message-ID: This was mailed just to me by accident. Forwarding to tutor. Apologies for not forwarding this ten days ago: I missed it. ---------- Forwarded message ---------- From: ?????? ??????? Date: Sat, Feb 7, 2015 at 12:27 AM Subject: Re: [Tutor] Need help with find error To: Danny Yoo Sorry for my absense, but you want to say, that loop in code isn't working? (in main()-function) When category is empty code must print 2 last rows, but I have error.... I learn python book M. Dawson and this exercise from his book. I add original working files, where points count as score +=1 and all works. But if I add some points to each question code don't work. I can't understand it/ 2015-02-04 20:24 GMT+02:00 Danny Yoo : > > As a revision of my initial question, when we look at next_block(), > it's documented as follows: > > ############################################ > def next_block(the_file): > """Return the next block of data from the trivia file.""" > .... > ############################################ > > What if there are no more blocks in the file? What should happen then? > > Let's say that we do a test, where we pass in the empty file to next_block(). > > ###################### > from io import StringIO > x = next_block(StringIO('')) > ###################### > > What do you want to happen in this situation? > > --- > > As a side note: if you have control over the data format, you might > want to consider using JSON rather than a line-based format. If you > use JSON, this takes care of a few issues that you are working around > now. > > For example, you can reuse the newline escapes rather than define your > own convention. Also, rather than read a stream of records, where you > have to deal with the end of the file, you might just read one JSON > object that represents your whole trivia file, which will simplify > your program's logic. > > See: https://docs.python.org/2/library/json.html and use your favorite > web search engine for 'json python tutorial', and you should be able > to find some useful information. If you have questions, please feel > free to ask. -------------- next part -------------- An Episode You Can't Refuse On the Run With a Mammal Let's say you turn state's evidence and need to "get on the lamb." If you wait /too long, what will happen? You'll end up on the sheep You'll end up on the cow You'll end up on the goat You'll end up on the emu 1 A lamb is just a young sheep. The Godfather Will Get Down With You Now Let's say you have an audience with the Godfather of Soul. How would it be /smart to address him? Mr. Richard Mr. Domino Mr. Brown Mr. Checker 3 James Brown is the Godfather of Soul. That's Gonna Cost Ya If you paid the Mob protection money in rupees, what business would you most /likely be insuring? Your tulip farm in Holland Your curry powder factory in India Your vodka distillery in Russian Your army knife warehouse in Switzerland 2 The Rupee is the standard monetary unit of India. Keeping It the Family If your mother's father's sister's son was in "The Family," how are you /related to the mob? By your first cousin once removed By your first cousin twice removed By your second cousin once removed By your second cousin twice removed 1 Your mother's father's sister is her aunt -- and her son is your /mother's first cousin. Since you and your mother are exactly one generation /apart, her first cousin is your first cousin once removed. A Maid Man If you were to literally launder your money, but didn't want the green in your /bills to run, what temperature should you use? Hot Warm Tepid Cold 4 According to my detergent bottle, cold is best for colors that might run. From robertvstepp at gmail.com Tue Feb 17 22:05:20 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 17 Feb 2015 15:05:20 -0600 Subject: [Tutor] Potential problem with Game Over 2.0 problem in "Python Programming for the Absolute Beginner, 3rd Ed." In-Reply-To: <54E39AD0.50606@davea.name> References: <54E39AD0.50606@davea.name> Message-ID: On Tue, Feb 17, 2015 at 1:47 PM, Dave Angel wrote: > On 02/17/2015 02:12 PM, boB Stepp wrote: > > See > https://docs.python.org/3.4/reference/lexical_analysis.html#string-and-bytes-literals >> >> >> At this point in the text he is not talking about raw literal strings. >> I examined the author's source and he has obviously inserted at least >> one space between each use of a backslash at the end of a line and the >> EOL terminating characters. > > > Then he's teaching you wrong. Backslash followed by space is not a valid > escape sequence, and to do it at the end of line is particularly odious. I > wouldn't even suggest it in real code, never mind in something that's > published on paper. I guess I am inclined to cut the author some slack here. The point of his example was NOT to teach escape sequences, but instead show how using keyboard characters you could create a text picture, in this instance of a large "Game Over". He at this point was talking about the print function used with quotes and triple quotes. A little bit later in this same chapter he talks about escape sequences. The point of my original post was to point out that because the author is using a backslash as part of his ASCII art, that unintended consequences might result. I will admit that I was surprised that the author did not think of this potential issue and warn the reader of possible problems, especially as the book is aimed at total beginners. But I suppose it is difficult to anticipate all possible problems. But sure enough, my son stumbled into this one! [...] > I would never intentionally make any trailing whitespace in source code be > significant. And years ago I used an editor that routinely deleted any such > invisible characters. From the rest of your message, it looks like IDLE may > have that behavior. This seems to be the case. On a related note, I wanted to copy and paste the author's source code, showing how he generated the large, "Game Over", but my Gmail keeps collapsing the white space, making the result look like gibberish. So far I cannot find a setting to eliminate this undesired behavior. Argh! -- boB From robertvstepp at gmail.com Tue Feb 17 22:22:49 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 17 Feb 2015 15:22:49 -0600 Subject: [Tutor] Potential problem with Game Over 2.0 problem in "Python Programming for the Absolute Beginner, 3rd Ed." In-Reply-To: References: <54E39AD0.50606@davea.name> Message-ID: On Tue, Feb 17, 2015 at 3:05 PM, boB Stepp wrote: > This seems to be the case. On a related note, I wanted to copy and > paste the author's source code, showing how he generated the large, > "Game Over", but my Gmail keeps collapsing the white space, making the > result look like gibberish. So far I cannot find a setting to > eliminate this undesired behavior. Argh! ? ?I have found the problem. During some previous update or other Google-induced behavior, all of the work I did to have a specific fixed-width ?font with an extension has apparently been undone. Anyway, here is the snippet of the author's source code that I had intended to send earlier: ? print( """ _____ ___ ___ ___ _____ / ___| / | / |/ | | ___| | | / /| | / /| /| | | |__ | | _ / ___ | / / |__/ | | | __| | |_| | / / | | / / | | | |___ \_____/ /_/ |_| /_/ |_| |_____| _____ _ _ _____ _____ / _ \ | | / / | ___| | _ \ | | | | | | / / | |__ | |_| | | | | | | | / / | __| | _ / | |_| | | |/ / | |___ | | \ \ \_____/ |___/ |_____| |_| \_\ """ ) ? -- boB From dyoo at hashcollision.org Tue Feb 17 21:29:15 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 17 Feb 2015 12:29:15 -0800 Subject: [Tutor] Fwd: Need help with find error In-Reply-To: References: Message-ID: Forwarding to tutor. Again, apologies that I didn't respond earlier. Overloaded. ---------- Forwarded message ---------- From: ?????? ??????? Date: Tue, Feb 17, 2015 at 11:58 AM Subject: Re: [Tutor] Need help with find error To: Danny Yoo Anybody can help with this? 2015-02-07 10:27 GMT+02:00 ?????? ??????? : > > Sorry for my absense, but you want to say, that loop in code isn't working? (in main()-function) > When category is empty code must print 2 last rows, but I have error.... > > I learn python book M. Dawson and this exercise from his book. > I add original working files, where points count as score +=1 and all works. > But if I add some points to each question code don't work. > I can't understand it/ > > > > 2015-02-04 20:24 GMT+02:00 Danny Yoo : >> >> As a revision of my initial question, when we look at next_block(), >> it's documented as follows: >> >> ############################################ >> def next_block(the_file): >> """Return the next block of data from the trivia file.""" >> .... >> ############################################ >> >> What if there are no more blocks in the file? What should happen then? >> >> Let's say that we do a test, where we pass in the empty file to next_block(). >> >> ###################### >> from io import StringIO >> x = next_block(StringIO('')) >> ###################### >> >> What do you want to happen in this situation? >> >> --- >> >> As a side note: if you have control over the data format, you might >> want to consider using JSON rather than a line-based format. If you >> use JSON, this takes care of a few issues that you are working around >> now. >> >> For example, you can reuse the newline escapes rather than define your >> own convention. Also, rather than read a stream of records, where you >> have to deal with the end of the file, you might just read one JSON >> object that represents your whole trivia file, which will simplify >> your program's logic. >> >> See: https://docs.python.org/2/library/json.html and use your favorite >> web search engine for 'json python tutorial', and you should be able >> to find some useful information. If you have questions, please feel >> free to ask. > > From joel.goldstick at gmail.com Tue Feb 17 22:34:37 2015 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 17 Feb 2015 16:34:37 -0500 Subject: [Tutor] Potential problem with Game Over 2.0 problem in "Python Programming for the Absolute Beginner, 3rd Ed." In-Reply-To: References: <54E39AD0.50606@davea.name> Message-ID: On Tue, Feb 17, 2015 at 4:05 PM, boB Stepp wrote: > On Tue, Feb 17, 2015 at 1:47 PM, Dave Angel wrote: >> On 02/17/2015 02:12 PM, boB Stepp wrote: >> >> See >> https://docs.python.org/3.4/reference/lexical_analysis.html#string-and-bytes-literals >>> >>> >>> At this point in the text he is not talking about raw literal strings. >>> I examined the author's source and he has obviously inserted at least >>> one space between each use of a backslash at the end of a line and the >>> EOL terminating characters. >> >> >> Then he's teaching you wrong. Backslash followed by space is not a valid >> escape sequence, and to do it at the end of line is particularly odious. I >> wouldn't even suggest it in real code, never mind in something that's >> published on paper. > > I guess I am inclined to cut the author some slack here. The point of > his example was NOT to teach escape sequences, but instead show how > using keyboard characters you could create a text picture, in this > instance of a large "Game Over". He at this point was talking about > the print function used with quotes and triple quotes. A little bit > later in this same chapter he talks about escape sequences. The point > of my original post was to point out that because the author is using > a backslash as part of his ASCII art, that unintended consequences > might result. I will admit that I was surprised that the author did > not think of this potential issue and warn the reader of possible > problems, especially as the book is aimed at total beginners. But I > suppose it is difficult to anticipate all possible problems. But sure > enough, my son stumbled into this one! > > [...] > >> I would never intentionally make any trailing whitespace in source code be >> significant. And years ago I used an editor that routinely deleted any such >> invisible characters. From the rest of your message, it looks like IDLE may >> have that behavior. > > This seems to be the case. On a related note, I wanted to copy and > paste the author's source code, showing how he generated the large, > "Game Over", but my Gmail keeps collapsing the white space, making the > result look like gibberish. So far I cannot find a setting to > eliminate this undesired behavior. Argh! Do you have gmail set to plain text mode? > -- > boB > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com From robertvstepp at gmail.com Tue Feb 17 22:47:44 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 17 Feb 2015 15:47:44 -0600 Subject: [Tutor] Potential problem with Game Over 2.0 problem in "Python Programming for the Absolute Beginner, 3rd Ed." In-Reply-To: References: <54E39AD0.50606@davea.name> Message-ID: On Tue, Feb 17, 2015 at 3:34 PM, Joel Goldstick wrote: > On Tue, Feb 17, 2015 at 4:05 PM, boB Stepp wrote: >> On Tue, Feb 17, 2015 at 1:47 PM, Dave Angel wrote: >>> On 02/17/2015 02:12 PM, boB Stepp wrote: >> This seems to be the case. On a related note, I wanted to copy and >> paste the author's source code, showing how he generated the large, >> "Game Over", but my Gmail keeps collapsing the white space, making the >> result look like gibberish. So far I cannot find a setting to >> eliminate this undesired behavior. Argh! > > Do you have gmail set to plain text mode? What I just sent out, that showed what I wanted to show, was not plain text, but Google's fixed-width font. Of course, turning that on took away plain text mode. I had a couple of years ago or so (Whenever it was that I started working with Python and interacting with the Tutor list.) installed the Stylish extension to Gmail and set up a plain text, fixed width font. Somehow that font has been removed from my Gmail settings with no known action on my part. I did not notice it until today when I tried to reproduce the ASCII art under discussion in this thread and found that I could not. So apparently I can do plain text, but not fixed width, or I can do fixed width, but not plain text! At least until I come up with a solution. Heavy sighs! -- boB From fomcl at yahoo.com Tue Feb 17 22:53:18 2015 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 17 Feb 2015 21:53:18 +0000 (UTC) Subject: [Tutor] monkey patching question Message-ID: <1396143276.1247913.1424209998419.JavaMail.yahoo@mail.yahoo.com> Hi, I would like to monkey patch a function 'decode' that is defined inside a class. It is defined there because it is a logical place, next to its counterpart *method* 'encode'. I can successfully monkey patch meth1, but when I call meth2, it does not use the patched decorator. How can this be done? In this example, I would like to effectively "turn off" @decode. I am hoping for a solution that works on Python 2.7 and 3.3+. import inspect, functools class Foo(object): def decode(func): @functools.wraps(func) def wrapped(*args, **kwargs): print "original decorator was called" return func(*args, **kwargs).decode("utf-8") return wrapped def encode(self): """this is just here to show why decode() is defined within Foo""" pass def meth1(self): return "original method was called" @decode def meth2(self): return b"python rocks" # ---- works ----- f = Foo() print f.meth1() Foo.meth1 = lambda self: "new method was called" print f.meth1() print "-------------------" # ---- does not work ----- def patched_decode(func): @functools.wraps(func) def wrapped(*args, **kwargs): print "patched decorator was called" return func(*args, **kwargs) return wrapped f = Foo() print 'ORIGINAL' print inspect.getsource(Foo.decode) # shows source code of regular decode (as expected) result = f.meth2() print repr(result), type(result) #setattr(Foo, "decode", patched_decode) Foo.decode = patched_decode print 'PATCHED' print inspect.getsource(f.decode) # shows source code of patched_decode (as expected) result = f.meth2() print repr(result), type(result) # not patched at all! it's still unicode! ##### output: In [1]: %run monkey_patch.py original method was called new method was called ------------------- ORIGINAL def decode(func): @functools.wraps(func) def wrapped(*args, **kwargs): print "original decorator was called" return func(*args, **kwargs).decode("utf-8") return wrapped original decorator was called u'python rocks' PATCHED def patched_decode(func): @functools.wraps(func) def wrapped(*args, **kwargs): print "patched decorator was called" return func(*args, **kwargs) return wrapped original decorator was called u'python rocks' Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From davea at davea.name Tue Feb 17 23:50:04 2015 From: davea at davea.name (Dave Angel) Date: Tue, 17 Feb 2015 17:50:04 -0500 Subject: [Tutor] monkey patching question In-Reply-To: <1396143276.1247913.1424209998419.JavaMail.yahoo@mail.yahoo.com> References: <1396143276.1247913.1424209998419.JavaMail.yahoo@mail.yahoo.com> Message-ID: <54E3C59C.5080400@davea.name> On 02/17/2015 04:53 PM, Albert-Jan Roskam wrote: > Hi, > > I would like to monkey patch a function 'decode' that is defined inside a class. It is defined there because it is a logical place, next to its counterpart *method* 'encode'. I can successfully monkey patch meth1, but when I call meth2, it does not use the patched decorator. How can this be done? In this example, I would like to effectively "turn off" @decode. I am hoping for a solution that works on Python 2.7 and 3.3+. > > > import inspect, functools > class Foo(object): > > def decode(func): > @functools.wraps(func) > def wrapped(*args, **kwargs): > print "original decorator was called" > return func(*args, **kwargs).decode("utf-8") > return wrapped > > def encode(self): > """this is just here to show why decode() is defined > within Foo""" > pass > > def meth1(self): > return "original method was called" > > @decode > def meth2(self): > return b"python rocks" > I assume the monkey patching happens in some other file which will import this one. So by the time the import is finished, the meth2() method has already been decorated by the decode function. > > # ---- works ----- > f = Foo() > print f.meth1() > Foo.meth1 = lambda self: "new method was called" > print f.meth1() > print "-------------------" > > > # ---- does not work ----- > def patched_decode(func): > @functools.wraps(func) > def wrapped(*args, **kwargs): > print "patched decorator was called" > return func(*args, **kwargs) > return wrapped > > f = Foo() > print 'ORIGINAL' > print inspect.getsource(Foo.decode) # shows source code of regular decode (as expected) > result = f.meth2() > print repr(result), type(result) > > #setattr(Foo, "decode", patched_decode) > Foo.decode = patched_decode > > print 'PATCHED' > print inspect.getsource(f.decode) # shows source code of patched_decode (as expected) > result = f.meth2() > print repr(result), type(result) # not patched at all! it's still unicode! > > > > ##### output: > In [1]: %run monkey_patch.py > original method was called > new method was called > ------------------- > ORIGINAL > def decode(func): > @functools.wraps(func) > def wrapped(*args, **kwargs): > print "original decorator was called" > return func(*args, **kwargs).decode("utf-8") > return wrapped > > original decorator was called > u'python rocks' > PATCHED > def patched_decode(func): > @functools.wraps(func) > def wrapped(*args, **kwargs): > print "patched decorator was called" > return func(*args, **kwargs) > return wrapped > > original decorator was called > u'python rocks' I think you're going to have to patch meth2(). Patching decode won't help, since it's already done its work. -- DaveA From dyoo at hashcollision.org Tue Feb 17 23:43:07 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 17 Feb 2015 14:43:07 -0800 Subject: [Tutor] monkey patching question In-Reply-To: <1396143276.1247913.1424209998419.JavaMail.yahoo@mail.yahoo.com> References: <1396143276.1247913.1424209998419.JavaMail.yahoo@mail.yahoo.com> Message-ID: Apologies, but the answer might be unsatisfactory. The syntactic use of decorators is confusing the situation. Let's simplify. Your question is equivalent to the following scenario: ################################ def logged(g): def wrapped(x): print "call" return g(x) return wrapped square = logged(lambda x: x * x) ################################# where we can only interact with the resulting environment afterwards. The function that you want to mock out has *already* been called by the time you have control. Monkey patching as a technique works only under late binding, when there's a name that you can use to swap out an original binding with a new one. But in the situation above, that's not applicable at all. The function value is not being referred to by some name that's externally accessible, so there's no handle to monkey-patch. Can you do something else instead besides trying to monkey-patch? Even if it were possible to do, if you can correct the original code, that might be preferable and use less magic. From robertvstepp at gmail.com Wed Feb 18 00:23:02 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Tue, 17 Feb 2015 17:23:02 -0600 Subject: [Tutor] OT: Preferred email client for sending plain text programming code snippets Message-ID: Hopefully this is not a touchy subject like Emacs vs. Vim. ~(:>)) My home PC uses Win7-64bit. I currently use Chrome, Gmail and have a Nexus 5 phone. The nice thing about all of this is that all of my information usually seamlessly syncs. That is nice! But I am getting increasingly frustrated with Gmail in terms of communicating with this group (and sometimes others). It seems that if I am not constantly attentive, my settings change from plain text to html, or, now, my New Courier fixed-width font vanishes from the Gmail ecosystem and cannot be found. I actually have come to prefer plain text communication as I only rarely need html formatting. And I rarely care to see most of the crap people send me that require html! So are there any recommendations from this group that would make things easy, would still be able to receive/send from my Gmail account, etc.? -- boB From alan.gauld at btinternet.com Wed Feb 18 00:48:30 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Feb 2015 23:48:30 +0000 Subject: [Tutor] OT: Preferred email client for sending plain text programming code snippets In-Reply-To: References: Message-ID: On 17/02/15 23:23, boB Stepp wrote: > So are there any recommendations from this group that would make > things easy, would still be able to receive/send from my Gmail > account, etc.? Thunderbird seems to work for me. I use it for 4 different email accounts (including both yahoo and gmail) as well as over a dozen newsgroups, mostly from gmane (including c.l.p, tutor and tkinter). It can also handle RSS feeds apparently but I don't use that. Some of the accounts I set up to use rich text, others I use plain text. Each account has its own settings. And it works on both my Linux and Windows. By using IMAP I can open any account on any box and see the same mail setup. And in most cases using my Android phone does the same too... The downsides? Occasionally, while editing/composing it blanks out a line of text so it becomes invisible and I have to select the line to get it back. Hopefully a patch will fix that soon. I don't particularly like the split UI where the message action buttons are on a toolbar in the middle of the window (at the top of the message preview). I also don't like when it tries to be too clever. Sometimes it detects list email addresses and replaces the Reply-All button with Reply-List. This is very bad, especially with another list I help moderate. When I'm discussing an iffy mail with my fellow moderators it tries to send it to the list because it detects the list address in the body of the mail - NOT what I want! I've had some embarrassing moments because of that! But overall it does what I want, most of the time. hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From adwc86 at utexas.edu Tue Feb 17 21:30:34 2015 From: adwc86 at utexas.edu (Arnold Chung) Date: Tue, 17 Feb 2015 14:30:34 -0600 Subject: [Tutor] Python Question: Excluding certain keywords. Message-ID: Dear Python Tutor. First of all, thank you for your kindness in advance. I am learning python by myself and having some difficulties in a problem that I encounter. Here I attach my python file. What I am trying to do is: 1) get the data by opening the data source, which is ?apple.son' 2) obtain only the text part of JSON. 3) exclude the certain string which includes certain keywords. Up to part 2), I think it works. However, part 3) it does not return any value. Do you know why? I really appreciate your help and I am looking forward your response.? Thank you again. Best, Arnold DongWoo Chung Master?s Degree Student,? Stan Richards School of Advertising and Public Relations Moody College of Communication The University of Texas at Austin 512.466.6435 |?adwc86 at utexas.edu From davea at davea.name Wed Feb 18 01:04:17 2015 From: davea at davea.name (Dave Angel) Date: Tue, 17 Feb 2015 19:04:17 -0500 Subject: [Tutor] Python Question: Excluding certain keywords. In-Reply-To: References: Message-ID: <54E3D701.50909@davea.name> On 02/17/2015 03:30 PM, Arnold Chung wrote: > Dear Python Tutor. Welcome to the tutor list. As far as I can tell, this is your first post. And thank you for using text mail, rather than html. > > First of all, thank you for your kindness in advance. I am learning python by myself and having some difficulties in a problem that I encounter. > > Here I attach my python file. This mailing list doesn't support attachments. What that means is that even if some subscribers might see the attachment you presumably did, others will not. I do not. Please paste the relevant code into the message. If it's too large for that, then strip it down to a simpler case that is reasonable. You probably will also need to tell us your Python version. -- DaveA From beachkidken at gmail.com Wed Feb 18 01:23:33 2015 From: beachkidken at gmail.com (Ken G.) Date: Tue, 17 Feb 2015 19:23:33 -0500 Subject: [Tutor] Old popen turned in subprocess...[SOLVED] Message-ID: <54E3DB85.6090007@gmail.com> I wish to thanks Danny Yoo and Alan Gauld for providing information on using the new subprocess in printing on paper, replacing my old popen which was deprecated since Python 2.6. After some trial and errors, I got my desired output printed. Not looking forward to updating my old programs. Thanks, guys. Ken From steve at pearwood.info Wed Feb 18 01:30:54 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 18 Feb 2015 11:30:54 +1100 Subject: [Tutor] Python Question: Excluding certain keywords. In-Reply-To: References: Message-ID: <20150218003054.GU2498@ando.pearwood.info> Hi Arnold, and welcome. On Tue, Feb 17, 2015 at 02:30:34PM -0600, Arnold Chung wrote: > Dear Python Tutor. > > First of all, thank you for your kindness in advance. I am learning > python by myself and having some difficulties in a problem that I > encounter. > > Here I attach my python file. [...] Unfortunately you forgot to attach your Python code. If your code is short, say less than 100 lines, please just copy and paste it into the body of your email. If it is more than 100 lines but less than, say, 300, attach it as a .py file. If it is bigger than that, please don't send it to the mailing list without asking first. We are volunteers, and it is very unlikely that anyone is going to spend hours working through a ten thousand line file trying to debug it on your behalf. Thank you, -- Steve From alan.gauld at btinternet.com Wed Feb 18 01:39:35 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Feb 2015 00:39:35 +0000 Subject: [Tutor] Old popen turned in subprocess...[SOLVED] In-Reply-To: <54E3DB85.6090007@gmail.com> References: <54E3DB85.6090007@gmail.com> Message-ID: On 18/02/15 00:23, Ken G. wrote: > I wish to thanks Danny Yoo and Alan Gauld > for providing information on using the new > subprocess in printing on paper, Glad to help. > I got my desired output printed. > > Not looking forward to updating my old programs. If it's a common function in your code why not create a module with a function. Then you can simply import it and call the function. import lprinter lprinter_init() ... lprint('some text here') or similar? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Wed Feb 18 04:48:15 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 18 Feb 2015 03:48:15 +0000 Subject: [Tutor] OT: Preferred email client for sending plain text programming code snippets In-Reply-To: References: Message-ID: On 17/02/2015 23:23, boB Stepp wrote: > Hopefully this is not a touchy subject like Emacs vs. Vim. ~(:>)) > > My home PC uses Win7-64bit. I currently use Chrome, Gmail and have a > Nexus 5 phone. The nice thing about all of this is that all of my > information usually seamlessly syncs. That is nice! But I am getting > increasingly frustrated with Gmail in terms of communicating with this > group (and sometimes others). It seems that if I am not constantly > attentive, my settings change from plain text to html, or, now, my New > Courier fixed-width font vanishes from the Gmail ecosystem and cannot > be found. I actually have come to prefer plain text communication as I > only rarely need html formatting. And I rarely care to see most of the > crap people send me that require html! > > So are there any recommendations from this group that would make > things easy, would still be able to receive/send from my Gmail > account, etc.? > Thunderbird. Access to 300+ Python mailing lists, blogs and the rest all in one place via gmane. Personally I've never had a single problem with it. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From ben+python at benfinney.id.au Wed Feb 18 05:15:42 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 18 Feb 2015 15:15:42 +1100 Subject: [Tutor] OT: Preferred email client for sending plain text programming code snippets References: Message-ID: <85bnkrc0sx.fsf@benfinney.id.au> boB Stepp writes: > Hopefully this is not a touchy subject like Emacs vs. Vim. ~(:>)) Heh. If anyone tries to start a Vim-versus-Emacs fight, feel free to cite me as someone well experienced with both who sees no need to be tribal about either of them. > My home PC uses Win7-64bit. My condolences, I hope you soon find a better environment in which to program. > I currently use Chrome, Gmail and have a Nexus 5 phone. One strong piece of advice: Please don't be tempted to compose email messages on a handheld device. The resulting messages are usually significantly worse, in terms of etiquette. Instead, wait until you're at a proper keyboard where you can compose a message that is considerate of readers. > I actually have come to prefer plain text communication as I only > rarely need html formatting. And I rarely care to see most of the crap > people send me that require html! Congratulations! That is a commendable position, I hope you can persuade others within your influence to make the same decision. > So are there any recommendations from this group that would make > things easy, would still be able to receive/send from my Gmail > account, etc.? There are many good email clients. I would recommend you select one which uses standard protocols (nearly all of them do), and which is licensed as free software and works on all major platforms. Google Mail still (I believe) allows you to communicate as the same identity by sending mail using SMTP and accessing your mailboxes via IMAP. You need to learn their specific servers and ports to configure your mail client. On the Android operating system, the leader seems to be K-9 Mail ; though, again, I'll caution you against composing messages unless you have a real keyboard plugged in and can edit the text easily. On a desktop operating system, I would recommend one of: * Mozilla Thunderbird , very comprehensive and mature. * Claws Mail , lighter but still with many features, and a good plug-in ecosystem. * Sylpheed Mail , quite lightweight and focussed. All three are licensed as free software (copyleft, GPL). All three work on the major desktop operating systems. All three have alrge active development and support communities. Interestingly, all three are also ?newsreaders?, clients to Usenet's NNTP protocol. This allows even better aggregation of discussion forums, such as those available at GMane. Good hunting! -- \ ?Contentment is a pearl of great price, and whosoever procures | `\ it at the expense of ten thousand desires makes a wise and | _o__) happy purchase.? ?J. Balguy | Ben Finney From jeanpierreda at gmail.com Wed Feb 18 06:22:23 2015 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Tue, 17 Feb 2015 21:22:23 -0800 Subject: [Tutor] What are *appropriate* uses for exec() and eval() ? In-Reply-To: <20150217153105.GT2498@ando.pearwood.info> References: <20150217021525.GP2498@ando.pearwood.info> <20150217153105.GT2498@ando.pearwood.info> Message-ID: On Tue, Feb 17, 2015 at 7:31 AM, Steven D'Aprano wrote: > On Mon, Feb 16, 2015 at 07:10:21PM -0800, Devin Jeanpierre wrote: >> On Mon, Feb 16, 2015 at 6:15 PM, Steven D'Aprano wrote: >> > Here is a fork of that recipe. It uses an inner class for the new >> > namedtuple class. The only thing which needs exec is the __new__ method. >> > >> > http://code.activestate.com/recipes/578918-yet-another-namedtuple/ >> > >> > This demonstrates a powerful truth about Python: *most of the time* you >> > don't need to use exec or eval because the standard language features >> > are powerful enough to solve the problem for you. Using a dynamically >> > created inner class is *almost* enough to solve this problem, only the >> > __new__ method defeats it. If our requirements where just a little less >> > demanding, we could avoid exec completely. >> >> No, exec is not necessary at all. > > I'm not sure that I said that exec was "necessary" anywhere, You said that most of the time you don't "need" to use it. You then explained how you narrowly had to use exec in this case, and could have avoided it if the restrictions were relaxed. That sure sounds like you were saying it was necessary. Maybe you meant to say something else? > but since > you mention it, how about the two earlier examples I gave, timeit and > doctest? Especially doctest. How would you implement doctests without > exec? I already covered this in my response to Cameron: I only meant that in this particular case exec is not needed. >> If they had to the author could have >> reimplemented the argument assignment logic by hand. They chose not to >> because it is "too hard". (And it is.) Fortunately, they don't have >> to go that far: >> >> signature = inspect.Signature([ >> inspect.Parameter(field_name, inspect.Parameter.POSITIONAL_OR_KEYWORD) >> for field_name in field_names]) > > Hmmm. Well, namedtuple was added to Python in version 2.6. [snip] > So much for that idea. What? Why should what was impossible in the past stop you from doing what is possible now? -- Devin From dyoo at hashcollision.org Wed Feb 18 07:25:38 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 17 Feb 2015 22:25:38 -0800 Subject: [Tutor] Fwd: Re: Fwd: Need help with find error In-Reply-To: References: Message-ID: I do not have time to help you right now. Please continue correspondence with the main tutor mailing list. ---------- Forwarded message ---------- From: "?????? ???????" Date: Feb 17, 2015 9:20 PM Subject: Re: [Tutor] Fwd: Need help with find error To: "Danny Yoo" Cc: Hi, in this folder https://drive.google.com/folderview?id=0B5_iElL_NLhAfllsSDRlV20wR3JKd0ltdUt0UFNscklLWTAwS1k5b3pjbW9LNG1qNEhsZkE&usp=sharing you get 2 original files and folder "my" where is changed code. thanks for help 2015-02-17 22:29 GMT+02:00 Danny Yoo : > Forwarding to tutor. Again, apologies that I didn't respond earlier. > Overloaded. > > > ---------- Forwarded message ---------- > From: ?????? ??????? > Date: Tue, Feb 17, 2015 at 11:58 AM > Subject: Re: [Tutor] Need help with find error > To: Danny Yoo > > > Anybody can help with this? > > 2015-02-07 10:27 GMT+02:00 ?????? ??????? : > > > > Sorry for my absense, but you want to say, that loop in code isn't > working? (in main()-function) > > When category is empty code must print 2 last rows, but I have error.... > > > > I learn python book M. Dawson and this exercise from his book. > > I add original working files, where points count as score +=1 and all > works. > > But if I add some points to each question code don't work. > > I can't understand it/ > > > > > > > > 2015-02-04 20:24 GMT+02:00 Danny Yoo : > >> > >> As a revision of my initial question, when we look at next_block(), > >> it's documented as follows: > >> > >> ############################################ > >> def next_block(the_file): > >> """Return the next block of data from the trivia file.""" > >> .... > >> ############################################ > >> > >> What if there are no more blocks in the file? What should happen then? > >> > >> Let's say that we do a test, where we pass in the empty file to > next_block(). > >> > >> ###################### > >> from io import StringIO > >> x = next_block(StringIO('')) > >> ###################### > >> > >> What do you want to happen in this situation? > >> > >> --- > >> > >> As a side note: if you have control over the data format, you might > >> want to consider using JSON rather than a line-based format. If you > >> use JSON, this takes care of a few issues that you are working around > >> now. > >> > >> For example, you can reuse the newline escapes rather than define your > >> own convention. Also, rather than read a stream of records, where you > >> have to deal with the end of the file, you might just read one JSON > >> object that represents your whole trivia file, which will simplify > >> your program's logic. > >> > >> See: https://docs.python.org/2/library/json.html and use your favorite > >> web search engine for 'json python tutorial', and you should be able > >> to find some useful information. If you have questions, please feel > >> free to ask. > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From studeni2010 at hotmail.com Wed Feb 18 08:50:14 2015 From: studeni2010 at hotmail.com (Tihomir Zjajic) Date: Wed, 18 Feb 2015 08:50:14 +0100 Subject: [Tutor] text file help Message-ID: How can I get this ; kl_number = 1202, kl_number = 1403, kl_number = 1802, kl_number = 2801, kl_number = 2502, kl_number = 2303, kl_number = 2254, kl_number = 1682, kl_number = 1403 kl_number = 1304, from text file(formular doznake) . I got this on this way ; def vrs_drv(): vrs_drv = raw_input("Enter a vrs_drv:") if vrs_drv == "21": return("1") if vrs_drv == "22": return("2") if vrs_drv == "41": return("4") number1 = vrs_drv() print("kl_number1:",number1) def prs_prec(): prs_prec = raw_input("Enter a prs_prec:") if prs_prec == "20": return("20") if prs_prec == "40": return("40") if prs_prec == "80": return("80") number2 = prs_prec() print("kl_number2:",number2) def teh_kl(): teh_kl = raw_input("Enter a teh_kl:") if teh_kl == "1": return("1") if teh_kl == "2": return("2") if teh_kl == ("3"): return("3") if teh_kl == ("4"): return("4") number3 = teh_kl() print("kl_number3:",number3) print(number1+number2+number3) print("\n\nPress the enter key to exit.") formular doznake.txt red_broj = 1 vrs_drv = 21 prs_prec = 20 teh_kl = 2 red_broj = 2 vrs_drv = 21 prs_prec = 40 teh_kl = 3 red_broj = 3 vrs_drv = 21 prs_prec = 80 teh_kl = 2 red_broj = 4 vrs_drv = 22 prs_prec = 80 teh_kl = 1 red_broj = 5 vrs_drv = 22 prs_prec = 50 teh_kl = 2 red_broj = 6 vrs_drv = 22 prs_prec = 30 teh_kl = 3 red_broj = 7 vrs_drv = 22 prs_prec = 25 teh_kl = 4 red_broj = 8 vrs_drv = 41 prs_prec = 68 teh_kl = 2 red_broj = 9 vrs_drv = 41 prs_prec = 40 teh_kl = 3 red_broj = 10 vrs_drv = 41 prs_prec = 30 teh_kl = 4 but , I want get this automatically without raw_input ,from text file. From alan.gauld at btinternet.com Wed Feb 18 10:14:53 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Feb 2015 09:14:53 +0000 Subject: [Tutor] text file help In-Reply-To: References: Message-ID: On 18/02/15 07:50, Tihomir Zjajic wrote: > How can I get this ; kl_number = 1202, kl_number = 1403, kl_number = 1802, kl_number = 2801, kl_number = 2502, kl_number = 2303, kl_number = 2254, kl_number = 1682, kl_number = 1403 > kl_number = 1304, from text file(formular doznake) . I got this on this way ; Your mail seems to assume that we will know what you are talking about. I have no idea what doznake is. I don;t recognize your data sample. > def vrs_drv(): > vrs_drv = raw_input("Enter a vrs_drv:") Its a really bad idea to name a variable the same as the name of the function. > if vrs_drv == "21": > return("1") > if vrs_drv == "22": > return("2") > if vrs_drv == "41": > return("4") I have no idea what these numbers are supposed to signify, they appear to be quite arbitrary and bear no relation to the numbers in your data above... Also what do you do if the user enters a different number from 21,31,41? > number1 = vrs_drv() > print("kl_number1:",number1) You show us your code. What does the output look like? > def prs_prec(): > prs_prec = raw_input("Enter a prs_prec:") Again, don't use the same name as the function. > if prs_prec == "20": > return("20") > if prs_prec == "40": > return("40") > if prs_prec == "80": > return("80") Since you just return the same string as the input you could have saved a lot of coding. What you expect to happen if the user enters something other than 20,40 or 80? > number2 = prs_prec() > print("kl_number2:",number2) Again, can we see the output? > def teh_kl(): > teh_kl = raw_input("Enter a teh_kl:") > if teh_kl == "1": > return("1") > if teh_kl == "2": > return("2") > if teh_kl == ("3"): > return("3") > if teh_kl == ("4"): > return("4") Exactly the same comments as above. > number3 = teh_kl() > print("kl_number3:",number3) > print(number1+number2+number3) > print("\n\nPress the enter key to exit.") OK, Now I see the relationship with the data sample. > formular doznake.txt > > red_broj = 1 > vrs_drv = 21 > prs_prec = 20 > teh_kl = 2 > red_broj = 2 > vrs_drv = 21 > prs_prec = 40 > teh_kl = 3 I assume red_broj indicates the start of a new record? So you can read three lines from the file after you find a red_broj entry? Something like this? (untested) kl_numbers = [] with open('doznake.txt') as doznake for line in doznake: if line.startswith('red_broj') num = makeNumber(next(doznake),next(doznake),next(doznake)) kl_numbers.append(num) def makeNumber(l1,l2,l3): nums = [] for line in (s1,s2,s3): nums.append(line.rstrip().split()[-1]) return ''.join(nums) That should result in you having a list of the kl_numbers you asked for in your data sample. If I understood your question properly. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From fomcl at yahoo.com Wed Feb 18 12:15:40 2015 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 18 Feb 2015 11:15:40 +0000 (UTC) Subject: [Tutor] monkey patching question In-Reply-To: <54E3C59C.5080400@davea.name> References: <54E3C59C.5080400@davea.name> Message-ID: <277510138.141165.1424258140088.JavaMail.yahoo@mail.yahoo.com> ----- Original Message ----- > From: Dave Angel > To: tutor at python.org > Cc: > Sent: Tuesday, February 17, 2015 11:50 PM > Subject: Re: [Tutor] monkey patching question > > On 02/17/2015 04:53 PM, Albert-Jan Roskam wrote: >> Hi, >> >> I would like to monkey patch a function 'decode' that is defined > inside a class. It is defined there because it is a logical place, next to its > counterpart *method* 'encode'. I can successfully monkey patch meth1, > but when I call meth2, it does not use the patched decorator. How can this be > done? In this example, I would like to effectively "turn off" @decode. > I am hoping for a solution that works on Python 2.7 and 3.3+. >> >> >> import inspect, functools >> class Foo(object): >> >> def decode(func): >> @functools.wraps(func) >> def wrapped(*args, **kwargs): >> print "original decorator was called" >> return func(*args, **kwargs).decode("utf-8") >> return wrapped >> >> def encode(self): >> """this is just here to show why decode() is > defined >> within Foo""" >> pass >> >> def meth1(self): >> return "original method was called" >> >> @decode >> def meth2(self): >> return b"python rocks" >> > > I assume the monkey patching happens in some other file which will > import this one. > > So by the time the import is finished, the meth2() method has already > been decorated by the decode function. > > Hi Dave, Danny, aha, now I see why it does not work. The code is patched, but it's too little, too late. >> >> original decorator was called >> u'python rocks' > > > I think you're going to have to patch meth2(). Patching decode won't > help, since it's already done its work. But in reality there is meth2 through methn, where n is at least a dozen. I considered monkey patching because it seemed easy to experiment with and the use case for which this would be needed was not very common. And it's fun to experiment with it of course. But I will have to refactor my decode decorator. Thanks!! Albert-Jan From s.shall at virginmedia.com Wed Feb 18 13:09:56 2015 From: s.shall at virginmedia.com (Sydney Shall) Date: Wed, 18 Feb 2015 12:09:56 +0000 Subject: [Tutor] OT: Preferred email client for sending plain text programming code snippets In-Reply-To: References: Message-ID: <54E48114.2050401@virginmedia.com> On 18/02/2015 03:48, Mark Lawrence wrote: > On 17/02/2015 23:23, boB Stepp wrote: >> Hopefully this is not a touchy subject like Emacs vs. Vim. ~(:>)) >> >> My home PC uses Win7-64bit. I currently use Chrome, Gmail and have a >> Nexus 5 phone. The nice thing about all of this is that all of my >> information usually seamlessly syncs. That is nice! But I am getting >> increasingly frustrated with Gmail in terms of communicating with this >> group (and sometimes others). It seems that if I am not constantly >> attentive, my settings change from plain text to html, or, now, my New >> Courier fixed-width font vanishes from the Gmail ecosystem and cannot >> be found. I actually have come to prefer plain text communication as I >> only rarely need html formatting. And I rarely care to see most of the >> crap people send me that require html! >> >> So are there any recommendations from this group that would make >> things easy, would still be able to receive/send from my Gmail >> account, etc.? >> > > Thunderbird. Access to 300+ Python mailing lists, blogs and the rest > all in one place via gmane. Personally I've never had a single problem > with it. > Mark, Could you give us or point us towards some simple instructions as how one uses gmane.comp.python.tutor with Thunderbird. I had a go and I have found it daunting. Thanks -- Sydney From alan.gauld at btinternet.com Wed Feb 18 13:48:08 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Feb 2015 12:48:08 +0000 Subject: [Tutor] OT: Preferred email client for sending plain text programming code snippets In-Reply-To: <54E48114.2050401@virginmedia.com> References: <54E48114.2050401@virginmedia.com> Message-ID: On 18/02/15 12:09, Sydney Shall wrote: > Could you give us or point us towards some simple instructions as how > one uses gmane.comp.python.tutor with Thunderbird. I had a go and I have > found it daunting. Create a new news account (File-New-OtherAccount) Enter your details, click next Enter the gmane news server address: news.gmane.org Give it a friendly name Finish Thats it. Now on that account page Manage newsgroup subscriptions(wait for it to populate) Use the show items box to filter - eg type comp.python Select the ones you want. Click subscribe Done Now on each newsgroup you can click on it and it will download the latest messages(might take a while first time round. You might want to limit the number to say 50-100) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From james at uplinkzero.com Wed Feb 18 16:24:41 2015 From: james at uplinkzero.com (James Chapman) Date: Wed, 18 Feb 2015 15:24:41 +0000 Subject: [Tutor] mySQL and Python In-Reply-To: References: Message-ID: One of my pet hates about this list... "This is a tutor list, your question is out of scope". Sure there might be better places to seek answers, and sure maybe the first responder doesn't know the answer, but that's not a reason to respond with that phrase. This list is a called python tutor, not python beginner, even if the large majority of the questions are beginner questions. The fact that people can ask any python related question is one of the things I like about it and wish that other languages had similar lists. Back to answer the original question... I recommend using the official MySQL connector because it's supported by MySQL and it's continuously developed, which means it won't stop working when you change Python versions, or MySQL versions, and it's documented. I've tried some other MySQL libs in the past that worked OK but were a nightmare when it came to supporting them due to changes in the environment. Download the connector from https://dev.mysql.com/downloads/connector/python/ The latest version should work just fine on Python 3.4 Documentation on how to use it is also available on the MySQL website: https://dev.mysql.com/doc/connector-python/en/connector-python-examples.html Hope this helps. From juan0christian at gmail.com Wed Feb 18 16:48:14 2015 From: juan0christian at gmail.com (Juan C.) Date: Wed, 18 Feb 2015 15:48:14 +0000 Subject: [Tutor] Python 3 simple socket issue Message-ID: Code: # !/usr/bin/env python3 # -*- coding: utf-8 -*- import socket def main(): target_host = 'www.google.com' target_port = 80 client = socket.socket() client.connect((target_host, target_port)) client.send(b"GET HTTP/1.1\r\nHost:google.com\r\n\r\n") response = client.recv(4096) print(response) Output: C:\Python34\python.exe D:/Documents/PyCharm/Test/__main__.py b'HTTP/1.0 403 Forbidden\r\nContent-Length: 1180\r\nContent-Type: text/html; charset=UTF-8\r\nDate: Wed, 18 Feb 2015 15:43:16 GMT\r\nServer: GFE/2.0\r\nAlternate-Protocol: 80:quic,p=0.08\r\n\r\nSorry...
Google
Sorry...

We\'re sorry...

... but your computer or network may be sending automated queries. To protect our users, we can\'t process your request right now.

See Google Help for more information.

' Process finished with exit code 0 Why a I getting 403? The code seems fine. Python 3.4.2 From robertvstepp at gmail.com Wed Feb 18 16:53:08 2015 From: robertvstepp at gmail.com (boB Stepp) Date: Wed, 18 Feb 2015 09:53:08 -0600 Subject: [Tutor] mySQL and Python In-Reply-To: References: Message-ID: On Wed, Feb 18, 2015 at 9:24 AM, James Chapman wrote: > One of my pet hates about this list... "This is a tutor list, your question > is out of scope". Sure there might be better places to seek answers, and > sure maybe the first responder doesn't know the answer, but that's not a > reason to respond with that phrase. This list is a called python tutor, not > python beginner, even if the large majority of the questions are beginner > questions. The fact that people can ask any python related question is one > of the things I like about it and wish that other languages had similar > lists. I understand the need to warn a questioner that this list *might* not be the best forum for their question; however, I fully enjoy these types of posts as often even if I don't fully understand what is being discussed, I still can cull valuable information. Also, sometimes something *clicks* and I am able to solve an issue that has been baffling me for a while. Plus it gives me thought to what to study in the future... -- boB From zachary.ware+pytut at gmail.com Wed Feb 18 18:00:58 2015 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Wed, 18 Feb 2015 11:00:58 -0600 Subject: [Tutor] Python 3 simple socket issue In-Reply-To: References: Message-ID: On Wed, Feb 18, 2015 at 9:48 AM, Juan C. wrote: >

We\'re sorry...

... but your computer or network may be > sending automated queries. To protect our users, we can\'t process your > request right now.

See Google Help for more > information.

' > > Process finished with exit code 0 > > Why a I getting 403? The code seems fine. Read the response you got back, particularly the link they sent you: https://support.google.com/websearch/answer/86640 The code is fine, the action is not in line with what Google will allow you to do. -- Zach From davea at davea.name Wed Feb 18 18:06:37 2015 From: davea at davea.name (Dave Angel) Date: Wed, 18 Feb 2015 12:06:37 -0500 Subject: [Tutor] Python 3 simple socket issue In-Reply-To: References: Message-ID: <54E4C69D.9090404@davea.name> On 02/18/2015 10:48 AM, Juan C. wrote: > Code: > > # !/usr/bin/env python3 > # -*- coding: utf-8 -*- > > import socket > > def main(): > target_host = 'www.google.com' > target_port = 80 > > client = socket.socket() > client.connect((target_host, target_port)) > client.send(b"GET HTTP/1.1\r\nHost:google.com\r\n\r\n") > > response = client.recv(4096) > print(response) > When I run that, I get: davea at think2b:~/zzztemp$ python juan.py File "juan.py", line 8 target_host = 'www.google.com' ^ IndentationError: expected an indented block davea at think2b:~/zzztemp$ So you might want to fix the indentation. And add a call to main() at top level. Once I do that, I get approximately the same thing you post below. > > Output: > > C:\Python34\python.exe D:/Documents/PyCharm/Test/__main__.py > b'HTTP/1.0 403 Forbidden\r\nContent-Length: 1180\r\nContent-Type: > text/html; charset=UTF-8\r\nDate: Wed, 18 Feb 2015 15:43:16 GMT\r\nServer: > GFE/2.0\r\nAlternate-Protocol: 80:quic,p=0.08\r\n\r\n http-equiv="content-type" content="text/html; > charset=utf-8"/>Sorry...
size=10>Go face=times color=#f3c518 size=10>o size=10>gl face=times color=#c41200 size=10>e
style="border-bottom: 1px solid > #dfdfdf;">Sorry...

We\'re sorry...

... but your computer or network may be > sending automated queries. To protect our users, we can\'t process your > request right now.

See Google Help for more > information.

' > > Process finished with exit code 0 > > Why a I getting 403? The code seems fine. > Could it be because google.com doesn't want automated queries? That's what they say in the text there. See: http://www.google.com/intl/en/policies/terms/ -- DaveA From juan0christian at gmail.com Wed Feb 18 18:56:55 2015 From: juan0christian at gmail.com (Juan C.) Date: Wed, 18 Feb 2015 17:56:55 +0000 Subject: [Tutor] Python 3 simple socket issue References: <54E4C69D.9090404@davea.name> Message-ID: The code is fine, the email should have ruined the indentation. Anyway, indeed, I only saw the 403 error and didn't even read the rest as I thought it was only HTML/CSS code, my bad. Tried with other pages and everything is working, thanks. From s.shall at virginmedia.com Wed Feb 18 19:15:05 2015 From: s.shall at virginmedia.com (Sydney Shall) Date: Wed, 18 Feb 2015 18:15:05 +0000 Subject: [Tutor] unittest for: Raises an exception Message-ID: <54E4D6A9.7090703@virginmedia.com> I use a MAC OSX 10.9.5 Enthought Canopy Python 2.7.6 I am a learner. I am now trying to learn unittests as is often emphasised on this list. I think that I have understood the simple unit tests such as Equal, Greater etc. But I am struggling with the syntax of a test for Raises an exception. The function that I am tring to test is: For some reason my indentation has not been correctly copied. I am sure that it is correct becuase I have chacked it as well as the program. Also the 20 tests that are OK refer to all the other functions in the program. def getSurplusLabourTime(self, ww, uvc): self.ww = ww self.uvc = uvc try: self.surplus_labour_time = self.ww - self.uvc return self.surplus_labour_time except: if self.surplus_labour_time <= 0.0: raise ValueError("Surplus labour time cannot be" + \ " equal to or shorter than zero!") My test code is the following: def test_func_getSurplusLabourTime_Exc(self): self.assertRaises(ValueError,self.cwp.getSurplusLabourTime(self.cwp.ww,self.cwp.uvc)) [This last line should indented, but it refuses to do so!] The traceback is as follows: ====================================================================== ERROR: test_func_getSurplusLabourTime_Exc (__main__.Testcwp) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/sydney/My_Documents/Political_Economy/Capital_Simulation/Capital/Current version/TestCWP_WorkDuration.py", line 88, in test_func_getSurplusLabourTime_Exc self.assertRaises(ValueError, self.cwp.getSurplusLabourTime(self.cwp.ww, self.cwp.uvc)) File "/Applications/Canopy.app/appdata/canopy-1.5.1.2730.macosx-x86_64/Canopy.app/Contents/lib/python2.7/unittest/case.py", line 475, in assertRaises callableObj(*args, **kwargs) TypeError: 'float' object is not callable ---------------------------------------------------------------------- Ran 21 tests in 0.005s FAILED (errors=1) I do know that I have not added the arguments that would sause an exception to be raised. But I have tried several forms and none have worked. I get the same traceback as above. Any guidance would be appreciated. -- Sydney From raulcumplido at gmail.com Wed Feb 18 19:33:45 2015 From: raulcumplido at gmail.com (=?UTF-8?Q?Ra=C3=BAl_Cumplido?=) Date: Wed, 18 Feb 2015 18:33:45 +0000 Subject: [Tutor] unittest for: Raises an exception In-Reply-To: <54E4D6A9.7090703@virginmedia.com> References: <54E4D6A9.7090703@virginmedia.com> Message-ID: Hi, When using self.assertRaises like this you should pass a callable (the function you are going to call), but not call the function on the test. The problem is when the function takes arguments. At this point you need to create a callable with the two arguments. That can be done with functools but it's not easy to follow (If you want me to explain more on this path I can happily do it). For me the nicest syntax to test raising exceptions is to use a context manager. As the following: with self.assertRaises(ValueError): self.cwp.getSurplusLabourTime(self.cwp.ww,self.cwp.uvc) Kind Regards, Raul On Wed, Feb 18, 2015 at 6:15 PM, Sydney Shall wrote: > I use a MAC OSX 10.9.5 > Enthought Canopy Python 2.7.6 > > I am a learner. > > I am now trying to learn unittests as is often emphasised on this list. > I think that I have understood the simple unit tests such as Equal, > Greater etc. > But I am struggling with the syntax of a test for Raises an exception. > > The function that I am tring to test is: > For some reason my indentation has not been correctly copied. > I am sure that it is correct becuase I have chacked it as well as the > program. Also the 20 tests that are OK refer to all the other functions in > the program. > > def getSurplusLabourTime(self, ww, uvc): > self.ww = ww > self.uvc = uvc > try: > self.surplus_labour_time = self.ww - self.uvc > return self.surplus_labour_time > except: > if self.surplus_labour_time <= 0.0: > raise ValueError("Surplus labour time cannot be" + \ > " equal to or shorter than zero!") > > My test code is the following: > > def test_func_getSurplusLabourTime_Exc(self): > > self.assertRaises(ValueError,self.cwp.getSurplusLabourTime(self.cwp.ww,self.cwp.uvc)) > > [This last line should indented, but it refuses to do so!] > > The traceback is as follows: > > ====================================================================== > ERROR: test_func_getSurplusLabourTime_Exc (__main__.Testcwp) > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "/Users/sydney/My_Documents/Political_Economy/Capital_Simulation/Capital/Current > version/TestCWP_WorkDuration.py", line 88, in test_func_ > getSurplusLabourTime_Exc > self.assertRaises(ValueError, self.cwp.getSurplusLabourTime(self.cwp.ww, > self.cwp.uvc)) > File "/Applications/Canopy.app/appdata/canopy-1.5.1.2730. > macosx-x86_64/Canopy.app/Contents/lib/python2.7/unittest/case.py", line > 475, in assertRaises > callableObj(*args, **kwargs) > TypeError: 'float' object is not callable > > ---------------------------------------------------------------------- > Ran 21 tests in 0.005s > > FAILED (errors=1) > > > I do know that I have not added the arguments that would sause an > exception to be raised. But I have tried several forms and none have > worked. I get the same traceback as above. > > > Any guidance would be appreciated. > > > > -- > Sydney > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From dyoo at hashcollision.org Wed Feb 18 19:28:49 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 18 Feb 2015 10:28:49 -0800 Subject: [Tutor] mySQL and Python In-Reply-To: References: Message-ID: On Wed, Feb 18, 2015 at 7:24 AM, James Chapman wrote: > One of my pet hates about this list... "This is a tutor list, your question > is out of scope". Sure there might be better places to seek answers, and > sure maybe the first responder doesn't know the answer, but that's not a > reason to respond with that phrase. This list is a called python tutor, not > python beginner, even if the large majority of the questions are beginner > questions. The fact that people can ask any python related question is one > of the things I like about it and wish that other languages had similar > lists. I'd like to apologize for the brusqueness in my last reply. In no way did I intend to be unfriendly. I do want to make sure that we stay on mailing list topic. Sometimes I get zealous about this, but that's because if the traffic on the list starts becoming very advanced, it can scare away the very folks we're trying to help. That's something that tends to happen when experts talk to each other. > I recommend using the official MySQL connector because it's supported by > MySQL and it's continuously developed, which means it won't stop working > when you change Python versions, or MySQL versions, and it's documented. > I've tried some other MySQL libs in the past that worked OK but were a > nightmare when it came to supporting them due to changes in the environment. Ah, I missed this one. Thanks. From ben+python at benfinney.id.au Wed Feb 18 21:23:03 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 19 Feb 2015 07:23:03 +1100 Subject: [Tutor] =?utf-8?q?Topic_focus_of_=E2=80=98python-tutor=E2=80=99_?= =?utf-8?q?=28was=3A_mySQL_and_Python=29?= References: Message-ID: <85y4nv9dg8.fsf_-_@benfinney.id.au> James Chapman writes: > One of my pet hates about this list... "This is a tutor list, your > question is out of scope". Sure there might be better places to seek > answers, and sure maybe the first responder doesn't know the answer, > but that's not a reason to respond with that phrase. You're right to address problematic tone, such as brusqueness. The poster has apologised, so that's acknowledged. That said, the point made is valid: This is not a general-purpose Python discussion forum, so there are many potential threads that are off-topic and should happen elsewhere. > This list is a called python tutor, not python beginner, even if the > large majority of the questions are beginner questions. The focus of this forum *is* tutoring beginners. The name can't be the sole guide to what's on or off topic, so please don't argue as though it is. > The fact that people can ask any python related question is one of the > things I like about it and wish that other languages had similar > lists. Then you have the wrong forum in mind. While we're not going to boot people out merely for asking ?any Python related question?, there are many Python-related topics that are better not discussed here and it's important that we regulars point that out. If you want a more general Python discussion forum, we have one of those too: it's called ?python-list?, also available via Usenet at ?comp.lang.python?. So it is evident that your needs are already met :-) -- \ ?[R]ightful liberty is unobstructed action, according to our | `\ will, within limits drawn around us by the equal rights of | _o__) others.? ?Thomas Jefferson, 1819 | Ben Finney From ben+python at benfinney.id.au Wed Feb 18 21:40:55 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 19 Feb 2015 07:40:55 +1100 Subject: [Tutor] unittest for: Raises an exception References: <54E4D6A9.7090703@virginmedia.com> Message-ID: <85twyj9cmg.fsf@benfinney.id.au> Sydney Shall writes: > My test code is the following: > > def test_func_getSurplusLabourTime_Exc(self): > > self.assertRaises(ValueError,self.cwp.getSurplusLabourTime(self.cwp.ww,self.cwp.uvc)) > > [This last line should indented, but it refuses to do so!] What is ?it? which refuses to indent your text? You might need to use a better message composition tool. If you're typing into a Web application, please see the discussion happening in this forum about appropriate email clients for posting program code. So I'll reformat that code for readability:: def test_func_getSurplusLabourTime_Exc(self): self.assertRaises( ValueError, self.cwp.getSurplusLabourTime(self.cwp.ww, self.cwp.uvc)) > The traceback is as follows: > > ====================================================================== > ERROR: test_func_getSurplusLabourTime_Exc (__main__.Testcwp) > ---------------------------------------------------------------------- > Traceback (most recent call last): [?] > "/Applications/Canopy.app/appdata/canopy-1.5.1.2730.macosx-x86_64/Canopy.app/Contents/lib/python2.7/unittest/case.py", line 475, in assertRaises > callableObj(*args, **kwargs) > TypeError: 'float' object is not callable The error message is correct: the ?assertRaises? method expects a callable object in the second parameter, but you've supplied an object which is not callable (a float). Have a closer look at the documentation for ?TestCase.assertRaises?:: assertRaises(exception, callable, *args, **kwds) Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). It's unfortunate the documentation doesn't give an example. But note that clause ?when `callable` is called with any [?] arguments that *are also passed to assertRaises*?. So you don't call the function yourself; if you do, you get back its return value (in your case, a float object) and *that's* your argument to ?assertRaises? ? not the function you're trying to test! Instead of calling the function and getting its return value, you pass *the function itself* to ?assertRaises?, along with any arguments you want *the test method* to call it with. This indirection is a little confusing, and again I'm unhappy the documentation doesn't show an example. Here's one:: def test_func_getSurplusLabourTime_Exc(self): self.assertRaises( ValueError, self.cwp.getSurplusLabourTime, self.cwp.ww, self.cwp.uvc) What the documentation does show as an example, though, is a new-ish feature that might suit you better. You can now make your test code more comprehensible by instead using the ?assertRaises? method as a context manager, and then you just call your function normally. Like this:: def test_func_getSurplusLabourTime_Exc(self): with self.assertRaises(ValueError): self.cwp.getSurplusLabourTime(self.cwp.ww, self.cwp.uvc) Context managers are a very helpful feature that can make code more elegant and readable. They might seem a little magic for now if you haven't learned about them yet, but this is a good demonstration of the improvement they can make. -- \ ?? one of the main causes of the fall of the Roman Empire was | `\ that, lacking zero, they had no way to indicate successful | _o__) termination of their C programs.? ?Robert Firth | Ben Finney From dyoo at hashcollision.org Wed Feb 18 22:14:30 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 18 Feb 2015 13:14:30 -0800 Subject: [Tutor] mySQL and Python In-Reply-To: References: Message-ID: >> I recommend using the official MySQL connector because it's supported by >> MySQL and it's continuously developed, which means it won't stop working >> when you change Python versions, or MySQL versions, and it's documented. >> I've tried some other MySQL libs in the past that worked OK but were a >> nightmare when it came to supporting them due to changes in the environment. > > Ah, I missed this one. Thanks. Hi Beatrice, Following up on James's recommendation, it does look like MySQL Connector should support the latest versions of Python, according to: http://dev.mysql.com/doc/connector-python/en/connector-python-versions.html where it says "Python 3.3 and later" are supported. So try using the 2.0 version of the Connector. Also, there appears to be a forum specific to MySQL Connector questions hosted by the MySQL folks at: http://forums.mysql.com/list.php?50 and they should be able to give specific help on that software too. That being said, you're welcome to ask questions here! My apologies again for sounding exclusive in my last email. I was trying to express the idea that Tutor might not be the best place to ask MySQL driver installation questions. I was trying to direct you to folks that should be better equipped to answer your questions based on their direct experience. But thankfully, it does sound like we do have a few MySQL-familiar folks on the list after all, so my concerns aren't as valid as I had thought. From bw_dw at fastmail.fm Wed Feb 18 17:18:11 2015 From: bw_dw at fastmail.fm (dw) Date: Wed, 18 Feb 2015 08:18:11 -0800 Subject: [Tutor] Suggestions on pyserial for RS232 com monitor? Message-ID: <1424276291.1416945.229270625.766B8D2E@webmail.messagingengine.com> Hi Python Gang. I have a project where I'm sending serial data to a Ten-Tec RX320 radio receiver. I'm using COM2 @1200 baud....(standard N,8,1 parameters). I have a need to verify the data that I'm sending to the device. It occurred to me that python installed on a laptop might be a great idea. I can send the commands to the laptop instead of the radio and monitor the commands. Does anyone have any suggestions on a python script that would wait for incoming data on a select com and display the data once sent? I would probably install python 2.7 in the laptop for this project, since the laptop has Ubuntu 12.04 OS. Any suggestions, script, or point me in a direction would be greatly appreciated. Sincere thanks! dw :-] -- Bw_dw at fastmail.net From raulcumplido at gmail.com Wed Feb 18 23:10:57 2015 From: raulcumplido at gmail.com (=?utf-8?Q?Ra=C3=BAl?=) Date: Wed, 18 Feb 2015 22:10:57 +0000 Subject: [Tutor] Suggestions on pyserial for RS232 com monitor? In-Reply-To: <1424276291.1416945.229270625.766B8D2E@webmail.messagingengine.com> References: <1424276291.1416945.229270625.766B8D2E@webmail.messagingengine.com> Message-ID: <22817EDA-90EE-48BC-B529-5492820A0C8C@gmail.com> I have never worked with serial ports on python, but have you taken a look on http://pyserial.sourceforge.net Regards, Ra?l > On 18 Feb 2015, at 16:18, dw wrote: > > Hi Python Gang. > I have a project where I'm sending serial data to a Ten-Tec RX320 radio > receiver. > I'm using COM2 @1200 baud....(standard N,8,1 parameters). > I have a need to verify the data that I'm sending to the device. > It occurred to me that python installed on a laptop might be a great > idea. > I can send the commands to the laptop instead of the radio and monitor > the commands. > Does anyone have any suggestions on a python script that would wait for > incoming data on a select com and display the data once sent? > I would probably install python 2.7 in the laptop for this project, > since the laptop has Ubuntu 12.04 OS. > Any suggestions, script, or point me in a direction would be greatly > appreciated. > > Sincere thanks! > dw :-] > -- > Bw_dw at fastmail.net > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Wed Feb 18 23:26:34 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Feb 2015 22:26:34 +0000 Subject: [Tutor] mySQL and Python In-Reply-To: References: Message-ID: On 18/02/15 15:24, James Chapman wrote: > One of my pet hates about this list... "This is a tutor list, your question > is out of scope". Sure there might be better places to seek answers, and > sure maybe the first responder doesn't know the answer, but that's not a > reason to respond with that phrase. The point of these responses is two fold: 1) It guides the poster to a more appropriate place to get the answers they need. This list is populated by a large number of beginners who probably can't answer specialised topics and a smaller number of more expert volunteers who are here to answer beginner type questions. It is pot luck whether within that community there exists anyone with the specialised skills needed for any given question. So asking on a specialised forum (or a general forum with more experts) makes sense. 2) Asking too many specialised or deeply technical questions scares off the beginners and newbies that this list is designed to cater for. If they can't understand the content of much of the mails then they assume they must be too stupid to participate or learn. We don't want that to happen. After all the official description of the group says in the very first line: " This list is for folks who want to ask questions regarding how to learn computer programming with the Python language and its standard library." It goes on: " Folks interested in learning about programming with Python are encouraged to join, as are folks interested in helping others learn. While the list is called tutor, anyone, whether novice or expert, can answer questions." We already have a general interest Python list, the reason for spinning off a separate tutor list some 18(?) years ago was specifically to remove some of the techno-fear that the main list generated for beginners. But we very rarely flat out refuse to answer, we usually just say you'll likely get a better response elsewhere. Which is a simple statement of the facts. -- Alan G List moderator From ben+python at benfinney.id.au Thu Feb 19 01:11:39 2015 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 19 Feb 2015 11:11:39 +1100 Subject: [Tutor] Suggestions on pyserial for RS232 com monitor? References: <1424276291.1416945.229270625.766B8D2E@webmail.messagingengine.com> Message-ID: <85d256ahfo.fsf@benfinney.id.au> dw writes: > I have a project where I'm sending serial data to a Ten-Tec RX320 radio > receiver. You will likely get a better response on our general Python discussion forum . This forum is focussed on tutoring newcomers in programming Python. -- \ ?For fast acting relief, try slowing down.? ?Jane Wagner, via | `\ Lily Tomlin | _o__) | Ben Finney From b.perezmila at gmail.com Thu Feb 19 00:43:59 2015 From: b.perezmila at gmail.com (Beatrice Perez) Date: Wed, 18 Feb 2015 23:43:59 +0000 Subject: [Tutor] mySQL and Python In-Reply-To: References: Message-ID: Don't worry, thanks everyone for the reply. I realize that the question was very general but I was looking for pointers which is exactly what you guys have given me. Now I know what to read, where to start. --Beatrice On Wed, Feb 18, 2015 at 9:14 PM, Danny Yoo wrote: > >> I recommend using the official MySQL connector because it's supported by > >> MySQL and it's continuously developed, which means it won't stop working > >> when you change Python versions, or MySQL versions, and it's documented. > >> I've tried some other MySQL libs in the past that worked OK but were a > >> nightmare when it came to supporting them due to changes in the > environment. > > > > Ah, I missed this one. Thanks. > > > Hi Beatrice, > > Following up on James's recommendation, it does look like MySQL > Connector should support the latest versions of Python, according to: > > > http://dev.mysql.com/doc/connector-python/en/connector-python-versions.html > > where it says "Python 3.3 and later" are supported. So try using the > 2.0 version of the Connector. > > > Also, there appears to be a forum specific to MySQL Connector > questions hosted by the MySQL folks at: > > http://forums.mysql.com/list.php?50 > > and they should be able to give specific help on that software too. > > > That being said, you're welcome to ask questions here! > > My apologies again for sounding exclusive in my last email. I was > trying to express the idea that Tutor might not be the best place to > ask MySQL driver installation questions. I was trying to direct you > to folks that should be better equipped to answer your questions based > on their direct experience. But thankfully, it does sound like we do > have a few MySQL-familiar folks on the list after all, so my concerns > aren't as valid as I had thought. > From breamoreboy at yahoo.co.uk Thu Feb 19 04:56:04 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 19 Feb 2015 03:56:04 +0000 Subject: [Tutor] mySQL and Python In-Reply-To: References: Message-ID: On 18/02/2015 23:43, Beatrice Perez wrote: > Don't worry, thanks everyone for the reply. I realize that the question was > very general but I was looking for pointers which is exactly what you guys > have given me. Now I know what to read, where to start. > > --Beatrice > > On Wed, Feb 18, 2015 at 9:14 PM, Danny Yoo wrote: > >>>> I recommend using the official MySQL connector because it's supported by >>>> MySQL and it's continuously developed, which means it won't stop working >>>> when you change Python versions, or MySQL versions, and it's documented. >>>> I've tried some other MySQL libs in the past that worked OK but were a >>>> nightmare when it came to supporting them due to changes in the >> environment. >>> >>> Ah, I missed this one. Thanks. >> >> >> Hi Beatrice, >> >> Following up on James's recommendation, it does look like MySQL >> Connector should support the latest versions of Python, according to: >> >> >> http://dev.mysql.com/doc/connector-python/en/connector-python-versions.html >> >> where it says "Python 3.3 and later" are supported. So try using the >> 2.0 version of the Connector. >> >> >> Also, there appears to be a forum specific to MySQL Connector >> questions hosted by the MySQL folks at: >> >> http://forums.mysql.com/list.php?50 >> >> and they should be able to give specific help on that software too. >> >> >> That being said, you're welcome to ask questions here! >> >> My apologies again for sounding exclusive in my last email. I was >> trying to express the idea that Tutor might not be the best place to >> ask MySQL driver installation questions. I was trying to direct you >> to folks that should be better equipped to answer your questions based >> on their direct experience. But thankfully, it does sound like we do >> have a few MySQL-familiar folks on the list after all, so my concerns >> aren't as valid as I had thought. >> My pet hate on this list is top posting as it makes following a thread so difficult. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From james at uplinkzero.com Thu Feb 19 10:51:42 2015 From: james at uplinkzero.com (James Chapman) Date: Thu, 19 Feb 2015 09:51:42 +0000 Subject: [Tutor] =?utf-8?q?Topic_focus_of_=E2=80=98python-tutor=E2=80=99_?= =?utf-8?q?=28was=3A_mySQL_and_Python=29?= In-Reply-To: <85y4nv9dg8.fsf_-_@benfinney.id.au> References: <85y4nv9dg8.fsf_-_@benfinney.id.au> Message-ID: Long-ish reply, but please bear with me. To quote the list description "This list is for folks who want to ask questions regarding how to learn computer programming with the Python language and its standard library." While MySQL modules are not part of the standard library, consider the following scenario. A person, let's call him Xerxes, is interesting in learning to program in Python. So he does a whole lot of reading, asks a load of questions on this list, he learns the basics. He now thinks to himself, wow, it would be really cool if I could actually do something really useful with my new skill set, maybe he has a job where building an interface to a database would save him and his company a lot of effort, but as MySQL is not part of the standard library he's not really sure how to go about it. Since people on the tutor list have always been willing to help and offer assistance, he thinks, I'll ask there. He asks his question and almost immediately gets told that what he's asking is off topic for the list. Let's jump back to the list description for a minute there. "This list is for folks who want to *ask questions regarding how to learn computer programming with the Python language* and its standard library." Is the installation and usage of 3rd party modules not related to learning to program with python? By responding in that manner, you're discouraging the asking of questions. No one should *_EVER_ *be discouraged to ask a question they do not know the answer to. That response that I referred to in my initial response is very common on this list and I think we (collectively) could and should come up with a better way of pointing people in the direction of satisfactory resolution. I also don't think we should immediately point people else where when the question is outside our comfort zone. OO, inheritance and multi-byte string processing, to name a few, are part of learning to program but are easily more advanced topics than which MySQL module to use. Creating C data structures in python, while part of the standard library, is an example of a topic that is probably too advanced for this list, and even then, I managed to find someone on this list able to help with that topic. If we discourage people from asking more interesting questions then I suspect that many subscribers will stop subscribing and that knowledge will be lost. I subscribe to quite a few programming related mailing lists and let me tell you, this one is _BY_FAR_ the most willing to help. That question would very likely have been ignored on other "more advanced" lists. Finally, I realise I've offered some criticism but not a suggestion for an alternative, so here is an example of a response to a question that would be considered "outside the scope" of this list: Hi Xerxes Great question. I know there are many options when it comes to MySQL but I've not had any experience with any. Someone else on this list might be able to provide a satisfactory answer, but, as the main focus of this list is learning to program in python using the standard library you might not get an answer, and if you do, the answer might not be very knowledgeable. You could try asking your question on forum X or mailing list Y as these types of topics are often covered there. James From johnrim20 at gmail.com Thu Feb 19 10:54:58 2015 From: johnrim20 at gmail.com (John R) Date: Thu, 19 Feb 2015 15:24:58 +0530 Subject: [Tutor] How to do a PyQt VTK application in Python26 Message-ID: Is it possible to make a PyQt VTK application using Python26? My first sample Qt VTK application is not running!! And my VTK compiled Bin folder is python 26 compiled dll files and Win32 bit The error is Traceback (most recent call last): File "EmbedInPyQt.py", line 5, in from PyQt4 import QtCore, QtGui ImportError: DLL load failed: %1 is not a valid Win32 application. Due to this bug I searched in internet for PyQt4 Installer downloading versions and those are supporting Python34 and higher as PyQt4 exe (http://www.riverbankcomputing.com/software/pyqt/download) Is there any way can I run my sample QT-VTK application using python 26? OR should I go after python 34?? could anyone please help me soon? From breamoreboy at yahoo.co.uk Thu Feb 19 11:35:11 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 19 Feb 2015 10:35:11 +0000 Subject: [Tutor] =?windows-1252?q?Topic_focus_of_=91python-tutor=92?= In-Reply-To: References: <85y4nv9dg8.fsf_-_@benfinney.id.au> Message-ID: On 19/02/2015 09:51, James Chapman wrote: > Long-ish reply, but please bear with me. > > To quote the list description "This list is for folks who want to ask > questions regarding how to learn computer programming with the Python > language and its standard library." > > While MySQL modules are not part of the standard library, consider the > following scenario. > > A person, let's call him Xerxes, is interesting in learning to program in > Python. So he does a whole lot of reading, asks a load of questions on this > list, he learns the basics. He now thinks to himself, wow, it would be > really cool if I could actually do something really useful with my new > skill set, maybe he has a job where building an interface to a database > would save him and his company a lot of effort, but as MySQL is not part of > the standard library he's not really sure how to go about it. Since people > on the tutor list have always been willing to help and offer assistance, he > thinks, I'll ask there. He asks his question and almost immediately gets > told that what he's asking is off topic for the list. Let's jump back to > the list description for a minute there. "This list is for folks who want > to *ask questions regarding how to learn computer programming with the > Python language* and its standard library." Is the installation and usage > of 3rd party modules not related to learning to program with python? > > By responding in that manner, you're discouraging the asking of questions. > No one should *_EVER_ *be discouraged to ask a question they do not know > the answer to. That response that I referred to in my initial response is > very common on this list and I think we (collectively) could and should > come up with a better way of pointing people in the direction of > satisfactory resolution. I also don't think we should immediately point > people else where when the question is outside our comfort zone. OO, > inheritance and multi-byte string processing, to name a few, are part of > learning to program but are easily more advanced topics than which MySQL > module to use. Creating C data structures in python, while part of the > standard library, is an example of a topic that is probably too advanced > for this list, and even then, I managed to find someone on this list able > to help with that topic. > > If we discourage people from asking more interesting questions then I > suspect that many subscribers will stop subscribing and that knowledge will > be lost. > > I subscribe to quite a few programming related mailing lists and let me > tell you, this one is _BY_FAR_ the most willing to help. That question > would very likely have been ignored on other "more advanced" lists. > > Finally, I realise I've offered some criticism but not a suggestion for an > alternative, so here is an example of a response to a question that would > be considered "outside the scope" of this list: > > > Hi Xerxes > > Great question. I know there are many options when it comes to MySQL but > I've not had any experience with any. Someone else on this list might be > able to provide a satisfactory answer, but, as the main focus of this list > is learning to program in python using the standard library you might not > get an answer, and if you do, the answer might not be very knowledgeable. > You could try asking your question on forum X or mailing list Y as these > types of topics are often covered there. > > James > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > IMHO you're talking crap, now can we please move on? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at btinternet.com Thu Feb 19 11:44:39 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Feb 2015 10:44:39 +0000 Subject: [Tutor] =?windows-1252?q?Topic_focus_of_=91python-tutor=92?= In-Reply-To: References: <85y4nv9dg8.fsf_-_@benfinney.id.au> Message-ID: On 19/02/15 09:51, James Chapman wrote: > While MySQL modules are not part of the standard library, consider the > following scenario. > skill set, maybe he has a job where building an interface to a database > would save him and his company a lot of effort, but as MySQL is not part of > the standard library he's not really sure how to go about it. If it were a new database he could use Sqlite which is part of the standard library... But that's not really the point :-) > on the tutor list have always been willing to help and offer assistance, he > thinks, I'll ask there. He asks his question and almost immediately gets > told that what he's asking is off topic for the list. Which is exactly the right answer. as a beginner he needs to learn to find the most appropriate forum and ask there. Its part of learning to program. It should be done politely and ideally we should tell him what that other forum is. But any programmer is going to need to learn how to research and locate appropriate information resources. It's just as important as learning a language, and in that sense it's part of this list's remit. One of the things that gives me greatest satisfaction is when I see someone who started out on the tutor list migrate to the main python list and eventually stop participating on this one. It means they have progressed as a programmer. Ideally everyone who starts using this list should, within a couple of years, have stopped asking questions here and moved on to another forum (or become one of the participating 'tutors' perhaps). > the list description for a minute there. "This list is for folks who want > to *ask questions regarding how to learn computer programming with the > Python language* and its standard library." Is the installation and usage > of 3rd party modules not related to learning to program with python? Not really. You can learn to program with Python effectively without ever using a third party package. In fact in my 20 years of Python I've only really used 4 third party packages - PyWin32, wxPython, BeautifulSoup and Pil/Pillow. Of these I only really use PyWin32 regularly. But it depends on what kind of programming you do. > By responding in that manner, you're discouraging the asking of questions. No, you are encouraging the asking of appropriate questions, and the searching for appropriate groups. A new and important skill for the programmer. > No one should *_EVER_ *be discouraged to ask a question they do not know > the answer to. That's true, but the answer may well be, "this is the wrong place to get the answer" > very common on this list and I think we (collectively) could and should > come up with a better way of pointing people in the direction of > satisfactory resolution. If the phrasing can be improved then lets have a go. Pointing them to a more effective solution should be the aim. > people else where when the question is outside our comfort zone. OO, > inheritance and multi-byte string processing, to name a few, are part of > learning to program but are easily more advanced topics than which MySQL > module to use. But they are appropriate to the tutor list because they are about learning to program. Specific database modules are not. Generic SQL or specific SQLite queries are appropriate because SQL is general programming and SQLite is in the standard library. However, if someone wants to delve into deep detail of how a feature is implemented in Python we would probably point them to the main list too, since it's not about learning how to program at that point. > Creating C data structures in python, while part of the > standard library, is an example of a topic that is probably too advanced > for this list, and even then, I managed to find someone on this list able > to help with that topic. Yes, that is probably borderline, since it is arguably part of using ctypes. And its true that we do have several people who can answer wider questions, depending on the question. But it is still better to ask a pool of 100 experts than ask a pool of perhaps 10. And in particular asking a beginner group about any topic can be risky since you often get answers which might work but are not the best way to do it. (This is a big issue on forums like stack overflow where you often see horrible hacks presented when a much better solution is available.) > If we discourage people from asking more interesting questions then I > suspect that many subscribers will stop subscribing and that knowledge will > be lost. The knowledge will be on the forums that specialise in those topics. That's where it should be. As I said above this list is not in the business of acquiring lifetime members, we want people to outgrow it and move on. It's a good sign. A bit like children leaving home. > I subscribe to quite a few programming related mailing lists and let me > tell you, this one is _BY_FAR_ the most willing to help. That question > would very likely have been ignored on other "more advanced" lists. And that's true and we should never just ignore a question. But it is quite legitimate to say "ask over there instead" > Finally, I realise I've offered some criticism but not a suggestion for an > alternative, so here is an example of a response to a question that would > be considered "outside the scope" of this list: > Great question. I know there are many options when it comes to MySQL but > I've not had any experience with any. Someone else on this list might be > able to provide a satisfactory answer, but, as the main focus of this list > is learning to program in python using the standard library you might not > get an answer, and if you do, the answer might not be very knowledgeable. > You could try asking your question on forum X or mailing list Y as these > types of topics are often covered there. Yes, that's fine, and in line with how I hope we answer most of the OT queries we get. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From s.shall at virginmedia.com Thu Feb 19 11:50:01 2015 From: s.shall at virginmedia.com (Sydney Shall) Date: Thu, 19 Feb 2015 10:50:01 +0000 Subject: [Tutor] unittest for: Raises an exception In-Reply-To: <85twyj9cmg.fsf@benfinney.id.au> References: <54E4D6A9.7090703@virginmedia.com> <85twyj9cmg.fsf@benfinney.id.au> Message-ID: <54E5BFD9.5070801@virginmedia.com> On 18/02/2015 20:40, Ben Finney wrote: > Sydney Shall writes: > >> My test code is the following: >> >> def test_func_getSurplusLabourTime_Exc(self): >> >> self.assertRaises(ValueError,self.cwp.getSurplusLabourTime(self.cwp.ww,self.cwp.uvc)) >> >> [This last line should indented, but it refuses to do so!] > > What is ?it? which refuses to indent your text? You might need to use a > better message composition tool. > > If you're typing into a Web application, please see the discussion > happening in this forum about appropriate email clients for posting > program code. > > So I'll reformat that code for readability:: > > def test_func_getSurplusLabourTime_Exc(self): > self.assertRaises( > ValueError, > self.cwp.getSurplusLabourTime(self.cwp.ww, self.cwp.uvc)) > >> The traceback is as follows: >> >> ====================================================================== >> ERROR: test_func_getSurplusLabourTime_Exc (__main__.Testcwp) >> ---------------------------------------------------------------------- >> Traceback (most recent call last): > [?] >> "/Applications/Canopy.app/appdata/canopy-1.5.1.2730.macosx-x86_64/Canopy.app/Contents/lib/python2.7/unittest/case.py", line 475, in assertRaises >> callableObj(*args, **kwargs) >> TypeError: 'float' object is not callable > > The error message is correct: the ?assertRaises? method expects a > callable object in the second parameter, but you've supplied an object > which is not callable (a float). > > Have a closer look at the documentation for ?TestCase.assertRaises?:: > > assertRaises(exception, callable, *args, **kwds) > > Test that an exception is raised when callable is called with any > positional or keyword arguments that are also passed to assertRaises(). > > > > It's unfortunate the documentation doesn't give an example. But note > that clause ?when `callable` is called with any [?] arguments that *are > also passed to assertRaises*?. > > So you don't call the function yourself; if you do, you get back its > return value (in your case, a float object) and *that's* your argument > to ?assertRaises? ? not the function you're trying to test! > > Instead of calling the function and getting its return value, you pass > *the function itself* to ?assertRaises?, along with any arguments you > want *the test method* to call it with. > > This indirection is a little confusing, and again I'm unhappy the > documentation doesn't show an example. Here's one:: > > def test_func_getSurplusLabourTime_Exc(self): > self.assertRaises( > ValueError, > self.cwp.getSurplusLabourTime, > self.cwp.ww, self.cwp.uvc) > > What the documentation does show as an example, though, is a new-ish > feature that might suit you better. > > You can now make your test code more comprehensible by instead using the > ?assertRaises? method as a context manager, and then you just call your > function normally. Like this:: > > def test_func_getSurplusLabourTime_Exc(self): > with self.assertRaises(ValueError): > self.cwp.getSurplusLabourTime(self.cwp.ww, self.cwp.uvc) > > Context managers are a very helpful feature that can make code more > elegant and readable. They might seem a little magic for now if you > haven't learned about them yet, but this is a good demonstration of > the improvement they can make. > Raul and Ben, Many thanks for the advice. The use of this test is much clearer to me now, and I think it is now working with your help. But I will practice my use of it. As for my formatting, this problem of indentation has not occurred before. I use Thunderbird and Firefox and I have not had this problem up to now. I shall examine the problem and see what is wrong and correct it. Thanks, Sydney -- Sydney From alan.gauld at btinternet.com Thu Feb 19 12:06:47 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Feb 2015 11:06:47 +0000 Subject: [Tutor] How to do a PyQt VTK application in Python26 In-Reply-To: References: Message-ID: On 19/02/15 09:54, John R wrote: > Is it possible to make a PyQt VTK application using Python26? No idea. What is a PyQt VTK application? I know what PyQt is but never heard of VTK Is there a web site? Does it have a support area? Perhaps they can help? > The error is > > Traceback (most recent call last): > File "EmbedInPyQt.py", line 5, in > from PyQt4 import QtCore, QtGui > ImportError: DLL load failed: %1 is not a valid Win32 application. It sounds like you may have a dependency issue and need to install something. But since its not Python or its standard library I can't guess what. The best place to ask will be a PyQt and/or a VTK forum. > Due to this bug I searched in internet for PyQt4 Installer downloading > versions and those are supporting > Python34 and higher as PyQt4 exe > (http://www.riverbankcomputing.com/software/pyqt/download) > > Is there any way can I run my sample QT-VTK application using python 26? > OR should I go after python 34?? Its unlikely that a version for 3.4 will work on 2.6. There are too many incompatible differences. Try using Python 3.4. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Thu Feb 19 13:21:19 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Feb 2015 12:21:19 +0000 Subject: [Tutor] text file help In-Reply-To: References: Message-ID: <54E5D53F.6050308@btinternet.com> Forwarding to tutor, please use Reply All when responding to tutor emails. On 19/02/15 11:17, Tihomir Zjajic wrote: > formular doznake.txt >> red_broj = 1 >> vrs_drv = 21 >> prs_prec = 20 >> teh_kl = 2 >> red_broj = 2 >> vrs_drv = 21 >> prs_prec = 40 >> teh_kl = 3 > > I assume red_broj indicates the start of a new record? > So you can read three lines from the file after you > find a red_broj entry? > > Something like this? (untested) > > kl_numbers = [] > with open('doznake.txt') as doznake > for line in doznake: > if line.startswith('red_broj') > num = makeNumber(next(doznake),next(doznake),next(doznake)) > kl_numbers.append(num) > > def makeNumber(l1,l2,l3): > nums = [] > for line in (s1,s2,s3): > nums.append(line.rstrip().split()[-1]) > return ''.join(nums) > def makeNumber(l1, l2, l3): > nums = [] > for lines in (s1, s2, s3): > nums.append(line.rstrip().split() [-1]) > return ".join(nums) " > > kl_number = [] > open("formular_doznake.txt") You need to either assign the open result to a variable or use the 'with' style (as in my example above). > for line in "formular_doznake.txt": > line startswith("red_broj") startswith is a method of string so you need a dot between line and startswith > num = makeNumber(next("formular_doznake"), next("formular_doznake"), next("formular_doznake")) next takes an iterator as an argument not a file name. This needs to be the alias from the with statement or the variable you assign if using open. example: >>> myfile = open("formular_doznake.txt") >>> print(next(myfile)) > kl_number.append(num) > > lpthw> python answer2.py formular_doznake.txt > File "answer2.py" line 13 > kl_number.append(num) > SyntaxError: invalid sintax You should copy and paste the code and errors not re-type them. its easier and more reliable. BTW If using the open styule above you should close the file at the end: myfile.close() One of the advantages of the with... style is that it auto-closes the file for you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From akleider at sonic.net Thu Feb 19 15:16:55 2015 From: akleider at sonic.net (Alex Kleider) Date: Thu, 19 Feb 2015 06:16:55 -0800 Subject: [Tutor] =?utf-8?b?VG9waWMgZm9jdXMgb2Yg4oCYcHl0aG9uLXR1dG9y4oCZ?= Message-ID: <201502191416.t1JEGxfh020792@d.mail.sonic.net> On Feb 19, 2015 2:35 AM, Mark Lawrence wrote: > IMHO you're talking crap, now can we please move on Agree with second part, Disagree with first From akleider at sonic.net Thu Feb 19 15:05:45 2015 From: akleider at sonic.net (Alex Kleider) Date: Thu, 19 Feb 2015 06:05:45 -0800 Subject: [Tutor] =?utf-8?q?Topic_focus_of_=E2=80=98python-tutor=E2=80=99_?= =?utf-8?q?=28was=3A_mySQL_and_Python=29?= Message-ID: <201502191405.t1JE5nU9015218@d.mail.sonic.net> On Feb 19, 2015 1:51 AM, James Chapman wrote: > > ...... this one is _BY_FAR_ the most willing to help. That question > Here, here! ak From emile at fenx.com Thu Feb 19 15:50:33 2015 From: emile at fenx.com (Emile van Sebille) Date: Thu, 19 Feb 2015 06:50:33 -0800 Subject: [Tutor] =?windows-1252?q?Topic_focus_of_=91python-tutor=92?= In-Reply-To: References: <85y4nv9dg8.fsf_-_@benfinney.id.au> Message-ID: On 2/19/2015 1:51 AM, James Chapman wrote: > No one should *_EVER_ *be discouraged to ask a question they > do not know have not found > the answer to. Learning where to look and how to ask are likely more important skills for a programmer than learning any one specific language. Emile From johnrim20 at gmail.com Thu Feb 19 14:44:33 2015 From: johnrim20 at gmail.com (John R) Date: Thu, 19 Feb 2015 19:14:33 +0530 Subject: [Tutor] How to do a PyQt VTK application in Python26 In-Reply-To: References: Message-ID: Thanks Alan for suggesting Python 3.4, that seems to be correct but I am searching for any possibilities with python 2.6 Thank you guys for responding, I should try some other forum. On 19 Feb 2015 16:37, "Alan Gauld" wrote: > On 19/02/15 09:54, John R wrote: > >> Is it possible to make a PyQt VTK application using Python26? >> > > No idea. What is a PyQt VTK application? > I know what PyQt is but never heard of VTK > > Is there a web site? Does it have a support area? > Perhaps they can help? > > The error is >> >> Traceback (most recent call last): >> File "EmbedInPyQt.py", line 5, in >> from PyQt4 import QtCore, QtGui >> ImportError: DLL load failed: %1 is not a valid Win32 application. >> > > It sounds like you may have a dependency issue and need to > install something. But since its not Python or its standard > library I can't guess what. The best place to ask will be > a PyQt and/or a VTK forum. > > Due to this bug I searched in internet for PyQt4 Installer downloading >> versions and those are supporting >> Python34 and higher as PyQt4 exe >> (http://www.riverbankcomputing.com/software/pyqt/download) >> >> Is there any way can I run my sample QT-VTK application using python 26? >> OR should I go after python 34?? >> > > Its unlikely that a version for 3.4 will work on 2.6. There are too many > incompatible differences. Try using Python 3.4. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From rakeshsharma14 at hotmail.com Thu Feb 19 18:23:56 2015 From: rakeshsharma14 at hotmail.com (rakesh sharma) Date: Thu, 19 Feb 2015 22:53:56 +0530 Subject: [Tutor] (no subject) Message-ID: Greetings !! Hi all, what the meaning of the line at the start of the python file __author__ = "user" thanks in advancerakesh From emile at fenx.com Thu Feb 19 18:53:02 2015 From: emile at fenx.com (Emile van Sebille) Date: Thu, 19 Feb 2015 09:53:02 -0800 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 2/19/2015 9:23 AM, rakesh sharma wrote: > Greetings !! > Hi all, > what the meaning of the line at the start of the python file > __author__ = "user" > Googling __author__ provides lots of relevant info. Emile From dyoo at hashcollision.org Thu Feb 19 19:06:45 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 19 Feb 2015 10:06:45 -0800 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On Thu, Feb 19, 2015 at 9:23 AM, rakesh sharma wrote: > Greetings !! > Hi all, > what the meaning of the line at the start of the python file > __author__ = "user" Hi Rakesh, It's assigning a variable '__author__' with the value "user". Python libraries typically have some kind of "metadata" that talks about the library, and one way to express this metadata is to assign to certain variables like what you're seeing here. I can look at a particular module, and see if it has an '__author__': ######################################## >>> import tarfile >>> tarfile.__author__ 'Lars Gust\xe4bel (lars at gustaebel.de)' >>> import io >>> io.__author__ "Guido van Rossum , Mike Verdone , Mark Russell , Antoine Pitrou , Amaury Forgeot d'Arc , Benjamin Peterson " ######################################## That being said, it's not a requirement, so not all library modules have this. ######################################## >>> import xml >>> xml.__author__ Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '__author__' ######################################## And as a beginner, you probably don't need to worry about assigning authorship to your own programs: you should know that you wrote them. :P When you start working with larger teams of people, it's helpful because you want to direct development questions to the folks who own those files. Authorship is a rough approximation to find the right person in charge. From dyoo at hashcollision.org Thu Feb 19 19:21:24 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 19 Feb 2015 10:21:24 -0800 Subject: [Tutor] Fwd: Re: Fwd: Need help with find error Message-ID: > 2015-02-18 8:25 GMT+02:00 Danny Yoo : >> >> I do not have time to help you right now. Please continue correspondence with the main tutor list. On Wed, Feb 18, 2015 at 11:34 AM, ?????? ??????? wrote: > ok, thanks, I will Following up: have you been helped? I was watching the mailing list, and it looks like you might have gotten skipped on accident. Unfortunately, I am still overloaded, and can not help much at the moment. I would recommend asking your question again. But please summarize what you've learned so far, what parts worked, and what parts aren't working yet. Write the question so that someone can read just your new message without having to remember what you wrote earlier. The issue, I think, is that it's been such a long time that it's possible that people do not remember your question. Other tips: If people have asked you questions, try to reply back to those questions. Make sure to Reply All so that it's a conversation with the group. Also, avoid email attachments if possible. If I remember rightly, your programs were short enough that they could be inlined into the email message. You'll get more eyes to see your program if you reduce the friction for people to inspect and help. Good luck to you! From chrisstinemetz at gmail.com Thu Feb 19 22:19:14 2015 From: chrisstinemetz at gmail.com (Chris Stinemetz) Date: Thu, 19 Feb 2015 15:19:14 -0600 Subject: [Tutor] updating a dictionary Message-ID: Hello List, I have a dictionary that I would like to update/add rows to it as I read a file line by line. The dictionary format looks like: format = {'Cell': '','7':'','8':'','9':'','2':''} For each line read in I would simply like to check to see if a Cell key;value exists and if it does update the correct key==band(7,8,9,2) within the dictionary. If the Cell doesn't exist do the same thing as above only make sure to update the Cell key:value with it's value form the file so it can check to see if it exists later. There are duplicate Cell:values in the file so when there is a duplicate it will need to look at band to see what key:value to update. Below is what I have attempted thus far. I can provide sample data if needed. Thank you in advance. import datetime import string import pprint from datetime import datetime # Open a files for reading inFileOne = open('PRB_utilization.txt', "r") iDas = "DB" oDas = "D" suffix = (iDas,oDas) dict = {'Cell': '','7':'','8':'','9':'','2':''} for line in inFileOne.readlines(): index = line.rstrip("\n").split("\t") cell = index[1] if cell.endswith(suffix, 14, 16) is False: eNb = cell[0:8] sector = cell[10:11] band = cell[9:10] dl_prb_utl = index[60] site = eNb + "_" + sector if site in dict: dict['Cell'] = site dict[band] = dl_prb_utl else: dict['Cell'] = site dict[band] = dl_prb_utl inFileOne.close(); From emile at fenx.com Thu Feb 19 23:50:02 2015 From: emile at fenx.com (Emile van Sebille) Date: Thu, 19 Feb 2015 14:50:02 -0800 Subject: [Tutor] updating a dictionary In-Reply-To: References: Message-ID: On 2/19/2015 1:19 PM, Chris Stinemetz wrote: > Hello List, > > I have a dictionary that I would like to update/add rows to it as I read a > file line by line. > > The dictionary format looks like: > > format = {'Cell': '','7':'','8':'','9':'','2':''} > > For each line read in I would simply like to check to see if a Cell > key;value exists and if it does update the correct key==band(7,8,9,2) > within the dictionary. > > If the Cell doesn't exist do the same thing as above only make sure to > update the Cell key:value with it's value form the file so it can check to > see if it exists later. There are duplicate Cell:values in the file so when > there is a duplicate it will need to look at band to see what key:value to > update. > > Below is what I have attempted thus far. I can provide sample data if > needed. > > Thank you in advance. I've added comments interspersed below as I try to grok what you've got here... > > import datetime don't need this as you replace the value below... > import string > import pprint > from datetime import datetime ''' here. > > # Open a files for reading > inFileOne = open('PRB_utilization.txt', "r") > > iDas = "DB" > oDas = "D" > > suffix = (iDas,oDas) > > dict = {'Cell': '','7':'','8':'','9':'','2':''} it's not good form to shadow python types > for line in inFileOne.readlines(): > index = line.rstrip("\n").split("\t") you now have a list of string values... > > cell = index[1] > > if cell.endswith(suffix, 14, 16) is False: ... so they'll never end with numeric values. Further, "".endswith() accepts only one argument so you ought to get an error on this line. > eNb = cell[0:8] > sector = cell[10:11] > band = cell[9:10] > dl_prb_utl = index[60] > site = eNb + "_" + sector > > if site in dict: this tests if site is a valid key in dict -- but the only key value you've assigned to if 'Cell' so this will always be False... > dict['Cell'] = site > dict[band] = dl_prb_utl > else: ... and the following will always execute. > dict['Cell'] = site > dict[band] = dl_prb_utl > > inFileOne.close(); Perhaps if you provide a sample of what the contents of inFileOne look like and what you want dict to look like after each iteration we'd get a better idea of what you're trying to accomplish. As it is, it'd likely take someone who recognizes the problem domain to shed light on this. Emile From alan.gauld at btinternet.com Thu Feb 19 23:56:51 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Feb 2015 22:56:51 +0000 Subject: [Tutor] updating a dictionary In-Reply-To: References: Message-ID: On 19/02/15 21:19, Chris Stinemetz wrote: > The dictionary format looks like: > > format = {'Cell': '','7':'','8':'','9':'','2':''} > > For each line read in I would simply like to check to see if a Cell > key;value exists and if it does update the correct key==band(7,8,9,2) > within the dictionary. > > If the Cell doesn't exist do the same thing as above only make sure to > update the Cell key:value with it's value form the file so it can check to > see if it exists later. I'm not sure what the difference is here? If you update the dictionary or add a new key it will automatically have that key going forward. > There are duplicate Cell:values in the file so when > there is a duplicate it will need to look at band to see what key:value to > update. I'm not sure what 'band' is? You have not mentioned it up until now. > Below is what I have attempted thus far. I can provide sample data if > needed. I think a short same of your data would be useful, both input and output. > import datetime > import string > import pprint You don't use string. Do you really need it? It's quite rarely used these days. And you don't use pprint either. Do you plan on having a use for it later? > from datetime import datetime > > # Open a files for reading > inFileOne = open('PRB_utilization.txt', "r") You should get used to using the 'with' construct for file handling, it's usually shorter and much more reliable. > iDas = "DB" > oDas = "D" > > suffix = (iDas,oDas) suffix = ("DB","D") would be shorter and more obvious, since you don't use the single value variables anywhere in the code.. > dict = {'Cell': '','7':'','8':'','9':'','2':''} Using dict as a name is a bad idea because it hides the built in dict type conversion function. > for line in inFileOne.readlines(): You don't need readlines() any more you can just do: for line in inFileOne: > index = line.rstrip("\n").split("\t") > > cell = index[1] > > if cell.endswith(suffix, 14, 16) is False: > eNb = cell[0:8] > sector = cell[10:11] > band = cell[9:10] > dl_prb_utl = index[60] > site = eNb + "_" + sector I'll assume that's all OK since we can't see the data format. > if site in dict: > dict['Cell'] = site > dict[band] = dl_prb_utl > else: > dict['Cell'] = site > dict[band] = dl_prb_utl Both 'if' and 'else' clauses do the same thing so there is no point in doing a test. Just use: dict['Cell'] = site dict[band] = dl_prb_utl > inFileOne.close(); You don't need this if you use the with... form. Other than the minor tweaks I've suggested I'm not sure what your problem is? I think we need to see the data to understand the issue. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Fri Feb 20 00:10:06 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Feb 2015 23:10:06 +0000 Subject: [Tutor] updating a dictionary In-Reply-To: References: Message-ID: On 19/02/15 22:50, Emile van Sebille wrote: >> if cell.endswith(suffix, 14, 16) is False: > > ... so they'll never end with numeric values. Further, "".endswith() > accepts only one argument so you ought to get an error on this line. Sorry Emile, The OP is correct. ###################### >>> help(''.endswith) endswith(...) method of builtins.str instance S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. ####################### The tuple is the set of suffices and the numbers are the start/end points. Its not often seen like that but the OP is quite correct. The test against False is unusual it woyuld normally look like if not cell.endswith(suffix, 14, 16): but that is just a style issue. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From emile at fenx.com Fri Feb 20 00:26:40 2015 From: emile at fenx.com (Emile van Sebille) Date: Thu, 19 Feb 2015 15:26:40 -0800 Subject: [Tutor] updating a dictionary In-Reply-To: References: Message-ID: On 2/19/2015 3:10 PM, Alan Gauld wrote: > On 19/02/15 22:50, Emile van Sebille wrote: > >>> if cell.endswith(suffix, 14, 16) is False: >> >> ... so they'll never end with numeric values. Further, "".endswith() >> accepts only one argument so you ought to get an error on this line. > > Sorry Emile, The OP is correct. > > ###################### > >>> help(''.endswith) > endswith(...) method of builtins.str instance > S.endswith(suffix[, start[, end]]) -> bool You're right of course. That should teach me to read closer: TypeError: endswith() takes at least 1 argument (0 given) I skipped the 'at least' part of that. the-deeper-the-corners-the-thicker-the-cobwebs-ly y'rs, Emile From chrisstinemetz at gmail.com Fri Feb 20 01:55:33 2015 From: chrisstinemetz at gmail.com (Chris Stinemetz) Date: Thu, 19 Feb 2015 18:55:33 -0600 Subject: [Tutor] updating a dictionary In-Reply-To: References: Message-ID: > > > > > Other than the minor tweaks I've suggested I'm not sure what your problem > is? I think we need to see the data to understand the issue. ?Here is a sample of the input data, it is tab delimited and I chopped it down for example purposes: ? KSL03502_7A_1 11.5921 KSL03502_7B_1 46.4997 KSL03502_7C_1 13.5839 KSL03505_7A_1 12.8684 KSL03505_7B_1 16.5311 KSL03505_7C_1 18.9926 KSL03509_7A_1 3.4104 KSL03509_7B_1 40.6244 KSL03509_7C_1 51.0597 KSL03511_7A_1 7.128 KSL03511_7B_1 53.4401 KSL03511_7C_1 66.2584 KSL03514_2A_1 25.6476 KSL03514_2B_1 53.17 KSL03514_2C_1 11.6469 KSL03514_7A_1 39.2292 KSL03514_7B_1 65.675 KSL03514_7C_1 3.4937 ?I would like to parse it buy using a dictionary structure. Where each row would be something like: name 7,8,9,2 KSL03514_C,3.4937,,,11.6469 KSL03514_B,65.675,,,53.17 I am just showing an example of what KSL03514_7C_1, KSL03514_2C_1, KSL03514_7B_1, KSL03514_2B_1 would parse. Hope this helps explain what I am trying to accomplish. Thank you in advance. From breamoreboy at yahoo.co.uk Fri Feb 20 08:17:31 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 20 Feb 2015 07:17:31 +0000 Subject: [Tutor] updating a dictionary In-Reply-To: References: Message-ID: On 20/02/2015 00:55, Chris Stinemetz wrote: >> >> >> >> >> Other than the minor tweaks I've suggested I'm not sure what your problem >> is? I think we need to see the data to understand the issue. > > > ?Here is a sample of the input data, it is tab delimited and I chopped it > down for example purposes: > ? > > KSL03502_7A_1 11.5921 > KSL03502_7B_1 46.4997 > KSL03502_7C_1 13.5839 > KSL03505_7A_1 12.8684 > KSL03505_7B_1 16.5311 > KSL03505_7C_1 18.9926 > KSL03509_7A_1 3.4104 > KSL03509_7B_1 40.6244 > KSL03509_7C_1 51.0597 > KSL03511_7A_1 7.128 > KSL03511_7B_1 53.4401 > KSL03511_7C_1 66.2584 > KSL03514_2A_1 25.6476 > KSL03514_2B_1 53.17 > KSL03514_2C_1 11.6469 > KSL03514_7A_1 39.2292 > KSL03514_7B_1 65.675 > KSL03514_7C_1 3.4937 > > > ?I would like to parse it buy using a dictionary structure. Where each row > would be something like: > > name 7,8,9,2 > KSL03514_C,3.4937,,,11.6469 > KSL03514_B,65.675,,,53.17 > > I am just showing an example of what KSL03514_7C_1, KSL03514_2C_1, > KSL03514_7B_1, KSL03514_2B_1 would parse. > > Hope this helps explain what I am trying to accomplish. > > Thank you in advance. > I think you need a defaultdict rather than a plain dict, otherwise you'll always be overwriting your values with new data. I believe this https://docs.python.org/3/library/collections.html#defaultdict-examples is exactly what you need. Am I close? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From rohit.poddaturi at gmail.com Fri Feb 20 04:56:59 2015 From: rohit.poddaturi at gmail.com (rohit poddaturi) Date: Thu, 19 Feb 2015 22:56:59 -0500 Subject: [Tutor] python script Message-ID: <09965EF3-723E-4F54-837E-632C887FAA8A@gmail.com> Hi I am really new to python and have been given a assignment which is quite complex for my standard.The following is the assignment The program runs through the word document and when it sees a date ( the date might be in a variety of forms, but will always list the particular month) it goes to a new row in the excel sheet and lists that date. Then it searches for a key word. If that key word appears before the next date in the document, then it lists it as a '1' in the excel sheet. If that key word does not appear before the next date listed then it writes down a '0?. I am attaching a sample document and excel output for reference. Kindly look into it Regards Rohit Poddaturi From alan.gauld at btinternet.com Fri Feb 20 09:50:47 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Feb 2015 08:50:47 +0000 Subject: [Tutor] python script In-Reply-To: <09965EF3-723E-4F54-837E-632C887FAA8A@gmail.com> References: <09965EF3-723E-4F54-837E-632C887FAA8A@gmail.com> Message-ID: On 20/02/15 03:56, rohit poddaturi wrote: > The program runs through the word document and when it sees a date > ( the date might be in a variety of forms, but will always list the particular month) > it goes to a new row in the excel sheet and lists that date. OK, The first question that springs to mind is "How are you accessing the Word and Excel files? They are not a native format that Python can easily read so you need some kind of library to work with them. Do you already have such a library or do you need to find one? > Then it searches for a key word. If that key word appears before > the next date in the document, then it lists it as a '1' in > the excel sheet.If that key word does not appear before the > next date listed then it writes down a '0?. The same applies for writing to Excel, you need a library to do that. Do you have one already? Also which Python version are you using? I'll assume you are running Windows since it is Word and Excel based? > I am attaching a sample document and excel output for reference. Kindly look into it Your attachments didn't show up. Can you put them on a web site somewhere? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Fri Feb 20 09:54:12 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 20 Feb 2015 08:54:12 +0000 Subject: [Tutor] python script In-Reply-To: <09965EF3-723E-4F54-837E-632C887FAA8A@gmail.com> References: <09965EF3-723E-4F54-837E-632C887FAA8A@gmail.com> Message-ID: On 20/02/2015 03:56, rohit poddaturi wrote: > Hi > > I am really new to python and have been given a assignment which is quite complex for my standard.The following is the assignment > > The program runs through the word document and when it sees a date ( the date might be in a variety of forms, but will always list the particular month) it goes to a new row in the excel sheet and lists that date. Then it searches for a key word. If that key word appears before the next date in the document, then it lists it as a '1' in the excel sheet. If that key word does not appear before the next date listed then it writes down a '0?. > > I am attaching a sample document and excel output for reference. Kindly look into it > > Regards > Rohit Poddaturi > The attachments have not arrived so please put your code and a data sample inline for us to view. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From __peter__ at web.de Fri Feb 20 11:59:36 2015 From: __peter__ at web.de (Peter Otten) Date: Fri, 20 Feb 2015 11:59:36 +0100 Subject: [Tutor] updating a dictionary References: Message-ID: Chris Stinemetz wrote: > ?Here is a sample of the input data, it is tab delimited and I chopped it > down for example purposes: > ? > > KSL03502_7A_1 11.5921 > KSL03502_7B_1 46.4997 > KSL03502_7C_1 13.5839 > KSL03505_7A_1 12.8684 > KSL03505_7B_1 16.5311 > KSL03505_7C_1 18.9926 > KSL03509_7A_1 3.4104 > KSL03509_7B_1 40.6244 > KSL03509_7C_1 51.0597 > KSL03511_7A_1 7.128 > KSL03511_7B_1 53.4401 > KSL03511_7C_1 66.2584 > KSL03514_2A_1 25.6476 > KSL03514_2B_1 53.17 > KSL03514_2C_1 11.6469 > KSL03514_7A_1 39.2292 > KSL03514_7B_1 65.675 > KSL03514_7C_1 3.4937 > > > ?I would like to parse it buy using a dictionary structure. Where each row > would be something like: > > name 7,8,9,2 > KSL03514_C,3.4937,,,11.6469 > KSL03514_B,65.675,,,53.17 > > I am just showing an example of what KSL03514_7C_1, KSL03514_2C_1, > KSL03514_7B_1, KSL03514_2B_1 would parse. > > Hope this helps explain what I am trying to accomplish. You need to merge multiple lines into one row dict and you'll end up with multiple such rowdicts. The easiest way to keep them around is to put them into an outer dict that maps keys like "KSL03514_B" to the corresponding rowdict. This will start with {'2': '53.17', 'name': 'KSL03514_B'} in line > KSL03514_2B_1 53.17 and be updated to {'7': '65.675', '2': '53.17', 'name': 'KSL03514_B'} when line > KSL03514_7B_1 65.675 is encountered. The "name" item is redundant because it's the same as the key in the outer dict {'KSL03502_A': {'7': '11.5921', 'name': 'KSL03502_A'}, 'KSL03502_B': {'7': '46.4997', 'name': 'KSL03502_B'}, ... 'KSL03514_B': {'2': '53.17', '7': '65.675', 'name': 'KSL03514_B'}, 'KSL03514_C': {'2': '11.6469', '7': '3.4937', 'name': 'KSL03514_C'}} but it simplifies generating the resulting file. If you want to cheat, here's the code I came up with: import csv import operator import sys import logging logger = logging.getLogger() def read_data(infile): """Combine lines in infile with same into one dict. Returns a sorted list of such dicts. Expected line format: __ where digits only non-digit followed by any non-"_" Then = _ """ # map to rowdict # rowdict maps to and "name" to rows_by_name = {} for line in infile: # key format: # __ key, value = line.split() basename, both, dummy = key.split("_") suffix = both.lstrip("0123456789") prefix = both[:len(both)-len(suffix)] name = basename + "_" + suffix rowdict = rows_by_name.setdefault(name, {"name": name}) if prefix in rowdict: # we are going to overwrite a column value # may raise an exception instead logger.warn("duplicate column %s=%r for %s", prefix, value, name) rowdict[prefix] = value return sorted(rows_by_name.values(), key=operator.itemgetter("name")) def main(): logging.basicConfig() with open("PRB_utilization.txt") as infile: rows = read_data(infile) writer = csv.DictWriter( sys.stdout, # may replace stdout with any writable file object fieldnames=["name", "7", "8", "9", "2"] ) writer.writeheader() writer.writerows(rows) if __name__ == "__main__": main() From puruganti.ramesh at gmail.com Fri Feb 20 10:28:56 2015 From: puruganti.ramesh at gmail.com (Puruganti Ramesh) Date: Fri, 20 Feb 2015 14:58:56 +0530 Subject: [Tutor] Issue in date difference in Python 2.7.8 Message-ID: Hi Friends, I have an issue in comparing dates in python 2.7.8 I have written code as below but i am getting error Code is : import datetime as dt from datetime import datetime from datetime import datetime, timedelta, date dt_str='2014-5-11' dt_strq='2014-9-11' dt_datea = datetime.strptime(dt_str, '%Y-%m-%d').date() dt_dateb = datetime.strptime(dt_strq, '%Y-%m-%d').date() dt_diff = dt_dateb - dt_datea print dt_diff.days I am getting below excption Traceback (most recent call last): File "FunctionUpdate.py", line 204, in dt_dateb = datetime.strptime(dt_strq, '%Y-%m-%d').date() File "/usr/local/lib/python2.7/_strptime.py", line 328, in _strptime data_string[found.end():]) ValueError: unconverted data remains: Kindly solve my issue Regards, Ramesh From __peter__ at web.de Fri Feb 20 13:02:57 2015 From: __peter__ at web.de (Peter Otten) Date: Fri, 20 Feb 2015 13:02:57 +0100 Subject: [Tutor] Issue in date difference in Python 2.7.8 References: Message-ID: Puruganti Ramesh wrote: > Hi Friends, > > I have an issue in comparing dates in python 2.7.8 > I have written code as below but i am getting error > Code is : > import datetime as dt > from datetime import datetime > from datetime import datetime, timedelta, date > > dt_str='2014-5-11' > dt_strq='2014-9-11' > > dt_datea = datetime.strptime(dt_str, '%Y-%m-%d').date() > dt_dateb = datetime.strptime(dt_strq, '%Y-%m-%d').date() > dt_diff = dt_dateb - dt_datea > print dt_diff.days No, the above does not trigger the ValueError. > I am getting below excption > Traceback (most recent call last): > File "FunctionUpdate.py", line 204, in > dt_dateb = datetime.strptime(dt_strq, '%Y-%m-%d').date() > File "/usr/local/lib/python2.7/_strptime.py", line 328, in _strptime > data_string[found.end():]) > ValueError: unconverted data remains: > > Kindly solve my issue See my answer on comp.lang.python: From davea at davea.name Fri Feb 20 14:34:17 2015 From: davea at davea.name (Dave Angel) Date: Fri, 20 Feb 2015 08:34:17 -0500 Subject: [Tutor] Issue in date difference in Python 2.7.8 In-Reply-To: References: Message-ID: <54E737D9.7090704@davea.name> On 02/20/2015 04:28 AM, Puruganti Ramesh wrote: > Hi Friends, > > I have an issue in comparing dates in python 2.7.8 > I have written code as below but i am getting error > Code is : > import datetime as dt > from datetime import datetime > from datetime import datetime, timedelta, date > > dt_str='2014-5-11' > dt_strq='2014-9-11' > > dt_datea = datetime.strptime(dt_str, '%Y-%m-%d').date() > dt_dateb = datetime.strptime(dt_strq, '%Y-%m-%d').date() > dt_diff = dt_dateb - dt_datea > print dt_diff.days > > I am getting below excption > Traceback (most recent call last): > File "FunctionUpdate.py", line 204, in > dt_dateb = datetime.strptime(dt_strq, '%Y-%m-%d').date() > File "/usr/local/lib/python2.7/_strptime.py", line 328, in _strptime > data_string[found.end():]) > ValueError: unconverted data remains: > I think it's great that you reduced a 200+ line program into a 9 line simple case. that's always a good idea, and frequently it helps you solve your own problem, reducing it for public comment. But the other requirement is that you actually test that the code you show produces the error you show. It does not, probably because those strings in the literals are not exactly what you had in the original. -- DaveA From chrisstinemetz at gmail.com Fri Feb 20 18:56:53 2015 From: chrisstinemetz at gmail.com (Chris Stinemetz) Date: Fri, 20 Feb 2015 11:56:53 -0600 Subject: [Tutor] updating a dictionary In-Reply-To: References: Message-ID: I am getting closer. I think I have figured out the logic. I just have a quick question. How do you access key:values in a nested dictionary? MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]} say I want to access the key:value 8:0 print dict['MOL02997_C']['8'] doesn't seem to work. Thanks in advance. On Thu, Feb 19, 2015 at 5:10 PM, Alan Gauld wrote: > On 19/02/15 22:50, Emile van Sebille wrote: > > if cell.endswith(suffix, 14, 16) is False: >>> >> >> ... so they'll never end with numeric values. Further, "".endswith() >> accepts only one argument so you ought to get an error on this line. >> > > Sorry Emile, The OP is correct. > > ###################### > >>> help(''.endswith) > endswith(...) method of builtins.str instance > S.endswith(suffix[, start[, end]]) -> bool > > Return True if S ends with the specified suffix, False otherwise. > With optional start, test S beginning at that position. > With optional end, stop comparing S at that position. > suffix can also be a tuple of strings to try. > ####################### > > The tuple is the set of suffices and the numbers are the > start/end points. Its not often seen like that but the > OP is quite correct. > > > The test against False is unusual it woyuld normally look like > > if not cell.endswith(suffix, 14, 16): > > but that is just a style issue. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Fri Feb 20 23:30:24 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Feb 2015 22:30:24 +0000 Subject: [Tutor] updating a dictionary In-Reply-To: References: Message-ID: On 20/02/15 17:56, Chris Stinemetz wrote: > I am getting closer. I think I have figured out the logic. I just have a > quick question. How do you access key:values in a nested dictionary? > > MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]} > > say I want to access the key:value 8:0 > > print dict['MOL02997_C']['8'] doesn't seem to work. Look closer. The inner dictionary is inside a list [...]. try print dict['MOL02997_C'][0]['8'] If that works then try to figure out where the extra list is coming from and eliminate it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Fri Feb 20 23:51:06 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 20 Feb 2015 22:51:06 +0000 Subject: [Tutor] updating a dictionary In-Reply-To: References: Message-ID: On 20/02/2015 17:56, Chris Stinemetz wrote: Please don't top post as it makes long threads difficult if not impossible to follow, thanks. > I am getting closer. I think I have figured out the logic. I just have a > quick question. How do you access key:values in a nested dictionary? > > MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]} > > say I want to access the key:value 8:0 > > print dict['MOL02997_C']['8'] doesn't seem to work. "doesn't seem to work" doesn't tell us much, so normally you would post your code and the full traceback that you get. However what you have seems to be a dictionary that you've called dict, hence overriding the Python built-in name. This isn't illegal but it's certainly frowned upon. For the key 'MOL02997_C' you have a list which holds one dict which contains a value '8' amongst others. Hence:- >>> mystruct = {'MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]} >>> mystruct {'MOL02997_C': [{'7': '0', '8': '0', '2': '0', '9': '0'}]} >>> mystruct['MOL02997_C'] [{'7': '0', '8': '0', '2': '0', '9': '0'}] >>> mystruct['MOL02997_C'][0] {'7': '0', '8': '0', '2': '0', '9': '0'} >>> mystruct['MOL02997_C'][0]['8'] '0' Got that? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From brads at nyctelecomm.com Sat Feb 21 00:58:17 2015 From: brads at nyctelecomm.com (brads) Date: Fri, 20 Feb 2015 18:58:17 -0500 Subject: [Tutor] subprocess outputing wrong info to command line Message-ID: <006d01d04d69$1a7a4570$4f6ed050$@nyctelecomm.com> My subprocess is in error but the same command at the command line works fine. # cat makekeys.py #!/usr/bin/python3.4 import subprocess import sys import string import os.path import datetime import shlex from time import gmtime, strftime from subprocess import Popen, PIPE, STDOUT pretime = strftime("%Y%m%d%H", gmtime()) time = datetime.datetime.strptime(pretime,'%Y%m%d%H') print (time) plustime = datetime.timedelta(days=730) timeadd = (time + plustime) str(timeadd) #ndate = datetime.strptime(timeadd, '%Y%m%d%H') #timeadd = timeadd.replace(tzinfo=UTC()) print (timeadd) dname = input("Enter the domain to configure keys for? ") if os.path.exists(dname+".external.signed"): os.remove(dname+".external.signed") #os.remove(dname+".external") os.remove(dname+".ksk.key") os.remove(dname+".zsk.key") os.remove(dname+".ksk.private") os.remove(dname+".zsk.private") fd = open( dname+".external", 'w') fd.write("$TTL 86400\n") fd.write("$ORIGIN "+dname+".\n") fd.write("@ 1D IN SOA yoda.ex-mailer.com. admin@"+dname+".(\n") fd.write(" "+strftime("%Y%m%d%H", gmtime())+"\n") #fd.write(" "+repr(timeadd)+"\n") fd.write(" 3h\n") fd.write(" 1h\n") fd.write(" 1w\n") fd.write(" 1h)\n") fd.write(" IN NS yoda.ex-mailer.com.\n") fd.write(" IN NS r2d2.ex-mailer.com.\n") fd.write(dname+". IN TXT v=spf1 mx a:r2d2.ex-mailer.com -all\n") fd.write(dname+". MX 0 r2d2.ex-mailer.com.\n") fd.write("mail."+dname+". IN A 107.191.60.48\n") fd.write("$include /usr/local/etc/namedb/K"+dname+".zsk.key ; ZSK\n") fd.write("$include /usr/local/etc/namedb/K"+dname+".ksk.key ; KSK\n") fd.close() result = subprocess.check_output(["dnssec-keygen", "-f", "KSK", "-r", "/dev/urandom", "-a", "RSASHA256", "-b", "2048", "-n", "ZONE", dname]) result_utf8 = result.decode("utf-8").strip() mylist = list(result_utf8) print (mylist[0]) listlen= len(mylist) array = list() listlen -= 11 i = 0 while( i < listlen ): #if mylist != '\n' ^ mylist != '': array.insert(i, mylist[i]) i = i + 1 combined = "".join(array) print ('combined') print (combined) fmove = subprocess.call(["mv", result_utf8+".key",combined +".ksk.key"]) fmove = subprocess.call(["mv", result_utf8+".private",combined +".ksk.private"]) zresult = subprocess.check_output(["dnssec-keygen","-r","/dev/urandom","-a","RSASHA256 ","-b","2048","-n","ZONE", dname]) zresult_utf8 = zresult.decode("utf-8").strip() myzlist = list(zresult_utf8) print (myzlist[0]) zlistlen= len(myzlist) zarray = list() zlistlen -= 11 zi = 0 while( zi References: Message-ID: On Fri, Feb 20, 2015 at 4:51 PM, Mark Lawrence wrote: > On 20/02/2015 17:56, Chris Stinemetz wrote: > > Please don't top post as it makes long threads difficult if not impossible > to follow, thanks. > > I am getting closer. I think I have figured out the logic. I just have a >> quick question. How do you access key:values in a nested dictionary? >> >> MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]} >> > > >> say I want to access the key:value 8:0 >> >> print dict['MOL02997_C']['8'] doesn't seem to work. >> > > "doesn't seem to work" doesn't tell us much, so normally you would post > your code and the full traceback that you get. However what you have seems > to be a dictionary that you've called dict, hence overriding the Python > built-in name. This isn't illegal but it's certainly frowned upon. For > the key 'MOL02997_C' you have a list which holds one dict which contains a > value '8' amongst others. Hence:- > > >>> mystruct = {'MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]} > >>> mystruct > {'MOL02997_C': [{'7': '0', '8': '0', '2': '0', '9': '0'}]} > >>> mystruct['MOL02997_C'] > [{'7': '0', '8': '0', '2': '0', '9': '0'}] > >>> mystruct['MOL02997_C'][0] > {'7': '0', '8': '0', '2': '0', '9': '0'} > >>> mystruct['MOL02997_C'][0]['8'] > '0' > > Got that? > > > ? Thank you Mark. I understand what you are explaining to me but I am not sure why every instance of the key 8:value changes when I assign a new value to it. I am expecting only vals['KSL04523_A'][0]['8'] value to change to 55.55 but as you can see bellow all rows in the dictionary are changes for key 8: Thank you in advance >>> vals['KSL04523_A'] [{'7': '0', '9': '0', '8': '0', '2': '0'}] >>> vals['KSL04523_A'][0] {'7': '0', '9': '0', '8': '0', '2': '0'} >>> vals['KSL04523_A'][0]['8'] '0' >>> vals['KSL04523_A'][0]['8'] = 55.55 >>> pprint.pprint(vals) {'CELL_': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04514_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04514_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04515_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04515_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04515_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04516_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04516_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04516_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04517_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04517_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04517_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04519_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04519_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04519_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04520_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04520_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04520_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04521_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04521_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04521_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], 'KSL04523_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}]}? From dyoo at hashcollision.org Sat Feb 21 02:43:23 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 20 Feb 2015 17:43:23 -0800 Subject: [Tutor] updating a dictionary In-Reply-To: References: Message-ID: On Fri, Feb 20, 2015 at 3:47 PM, Chris Stinemetz wrote: > > I understand what you are explaining to me but I am not sure why every > instance of the key 8:value changes when I assign a new value to it. Ah. Be wary of structure sharing when the values being shared are mutable. A textbook example of this would be: ########################################### message = ['hello', 'world'] copy = message copy.append('!') print copy print message ## What do we expect to see here? What do we see? ########################################### The code above here is wrong to use the word "copy" here, because it's not copying the structure at all. copy refers to the *same* list value. Mutations to the value will be observable when we access that list through either 'message' or 'copy', since fundamentally they're both referring to the same list value. To copy a list, we can use a whole slice: ##################### message = ['hello', 'world'] copy = message[:] copy.append('!') print copy print message ##################### I don't know what your program looks like at this point, so I can't pinpoint exactly where this is happening, but at the very least, this should help you figure out what's going on. Feel free to ask if you'd like more explanation. If you'd like a visualization, also see: http://pythontutor.com/visualize.html#code=message+%3D+%5B'hello',+'world'%5D%0Acopy+%3D+message%0Acopy.append('!')&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=2&rawInputLstJSON=%5B%5D&curInstr=0 and compare vs: http://pythontutor.com/visualize.html#code=message+%3D+%5B'hello',+'world'%5D%0Acopy+%3D+message%5B%3A%5D%0Acopy.append('!')&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=2&rawInputLstJSON=%5B%5D&curInstr=0 Good luck! From steve at pearwood.info Sat Feb 21 03:58:20 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 21 Feb 2015 13:58:20 +1100 Subject: [Tutor] subprocess outputing wrong info to command line In-Reply-To: <006d01d04d69$1a7a4570$4f6ed050$@nyctelecomm.com> References: <006d01d04d69$1a7a4570$4f6ed050$@nyctelecomm.com> Message-ID: <20150221025815.GG7655@ando.pearwood.info> On Fri, Feb 20, 2015 at 06:58:17PM -0500, brads wrote: > My subprocess is in error but the same command at the command line works > fine. Are you running the Python script as the same user and from the same location as the command line? If you are running the Python script as an unprivileged user from your home directory, and the command line as root from the directory holding the key, then it is not surprising that they will get different results. Does the dnssec-signzone command use any environment variables? Perhaps they are not being inherited by the Python subprocess. Also, a note about sending code to the list. For some reason, every line in your code is separated by blank lines: > # cat makekeys.py > > #!/usr/bin/python3.4 > > import subprocess > > import sys etc. That makes it very hard to read. Please fix that. Secondly, you have a huge amount of extraneous code which is irrelevant to your problem with subprocess. You calculate dates, ask the user for input, delete files, and write new files, calculate arrays and more. None of that has anything to do with subprocess. Take it out. Reduce your problem to the smallest possible code which shows the problem. 9 times out of 10, the process of cutting your code down to manageable size will actually help you to solve your own problem, and the other 1 time out of 10 we have a smaller and less confusing piece of code to try to understand. You also have dead, obsolete code commented out. Comments should not be used for keeping history in the file, comments should be used for commenting about the code. Best practice is to use a revision control system like hg, but if you're not up to that at least delete the dead code before posting. When running into a problem with subprocess, your first step should be to *exactly* duplicate the successful command: dnssec-signzone -e20180330000000 -p -t -g -k Ktest123.com.ksk.key -o test123.com test123.com.external Ktest123.com.zsk.key So you should try running that from subprocess: subprocess.call([ 'dnssec-signzone', '-e20180330000000', '-p', '-t', '-g', '-k', 'Ktest123.com.ksk.key', '-o', 'test123.com', 'test123.com.external', 'Ktest123.com.zsk.key', ]) and see if it still works. If it still does not work, that strongly suggests a problem with the environment: you are running it as the wrong user, in the wrong location, missing enviromnent variables or permissions. If it works in Python, then you can start replacing each constant argument with a calculated argument, *one argument at a time*, and see where you introduce the bug. -- Steve From pavementii at gmail.com Sat Feb 21 17:48:51 2015 From: pavementii at gmail.com (Tim Johnson) Date: Sat, 21 Feb 2015 10:48:51 -0600 Subject: [Tutor] Tutor Digest, Vol 132, Issue 51 In-Reply-To: References: Message-ID: Hi Guys, Very simple question, I imagine. this code throws of off a "counter not defined error". Can you help? *def word_counter(word, string):* * counter = 0* * for item in string:* * if item == word:* * counter = counter + 1* *print counter* Thanks, Tim -- Tim Johnson pavementii at gmail.com c. (267) 630-0369 (text is okay) f. (267) 352-6298 On Sat, Feb 21, 2015 at 5:00 AM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: updating a dictionary (Chris Stinemetz) > 2. Re: updating a dictionary (Danny Yoo) > 3. Re: subprocess outputing wrong info to command line > (Steven D'Aprano) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 20 Feb 2015 17:47:29 -0600 > From: Chris Stinemetz > To: Mark Lawrence > Cc: tutor at python.org > Subject: Re: [Tutor] updating a dictionary > Message-ID: > < > CA+HbpzjJe-QZTVL0hdRT_UmATam7c8fWSWHkOd6GwEeTvfmahg at mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > On Fri, Feb 20, 2015 at 4:51 PM, Mark Lawrence > wrote: > > > On 20/02/2015 17:56, Chris Stinemetz wrote: > > > > Please don't top post as it makes long threads difficult if not > impossible > > to follow, thanks. > > > > I am getting closer. I think I have figured out the logic. I just have a > >> quick question. How do you access key:values in a nested dictionary? > >> > >> MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]} > >> > > > > > >> say I want to access the key:value 8:0 > >> > >> print dict['MOL02997_C']['8'] doesn't seem to work. > >> > > > > "doesn't seem to work" doesn't tell us much, so normally you would post > > your code and the full traceback that you get. However what you have > seems > > to be a dictionary that you've called dict, hence overriding the Python > > built-in name. This isn't illegal but it's certainly frowned upon. For > > the key 'MOL02997_C' you have a list which holds one dict which contains > a > > value '8' amongst others. Hence:- > > > > >>> mystruct = {'MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]} > > >>> mystruct > > {'MOL02997_C': [{'7': '0', '8': '0', '2': '0', '9': '0'}]} > > >>> mystruct['MOL02997_C'] > > [{'7': '0', '8': '0', '2': '0', '9': '0'}] > > >>> mystruct['MOL02997_C'][0] > > {'7': '0', '8': '0', '2': '0', '9': '0'} > > >>> mystruct['MOL02997_C'][0]['8'] > > '0' > > > > Got that? > > > > > > > ? > Thank you Mark. > > I understand what you are explaining to me but I am not sure why every > instance of the key 8:value changes when I assign a new value to it. > > I am expecting only vals['KSL04523_A'][0]['8'] value to change to 55.55 but > as you can see bellow all rows in the dictionary are changes for key 8: > > Thank you in advance > > >>> vals['KSL04523_A'] > [{'7': '0', '9': '0', '8': '0', '2': '0'}] > >>> vals['KSL04523_A'][0] > {'7': '0', '9': '0', '8': '0', '2': '0'} > > > >>> vals['KSL04523_A'][0]['8'] > '0' > > > >>> vals['KSL04523_A'][0]['8'] = 55.55 > >>> pprint.pprint(vals) > {'CELL_': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04514_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04514_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04515_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04515_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04515_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04516_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04516_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04516_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04517_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04517_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04517_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04519_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04519_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04519_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04520_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04520_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04520_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04521_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04521_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04521_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}], > 'KSL04523_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}]}? > > > ------------------------------ > > Message: 2 > Date: Fri, 20 Feb 2015 17:43:23 -0800 > From: Danny Yoo > To: Chris Stinemetz > Cc: Mark Lawrence , Python Tutor Mailing List > > Subject: Re: [Tutor] updating a dictionary > Message-ID: > egnYR4KTqMWg-xfWW0rMSEEZppBdnww at mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > On Fri, Feb 20, 2015 at 3:47 PM, Chris Stinemetz > wrote: > > > > I understand what you are explaining to me but I am not sure why every > > instance of the key 8:value changes when I assign a new value to it. > > > Ah. Be wary of structure sharing when the values being shared are mutable. > > > A textbook example of this would be: > > ########################################### > message = ['hello', 'world'] > copy = message > copy.append('!') > print copy > print message > ## What do we expect to see here? What do we see? > ########################################### > > The code above here is wrong to use the word "copy" here, because it's > not copying the structure at all. copy refers to the *same* list > value. Mutations to the value will be observable when we access that > list through either 'message' or 'copy', since fundamentally they're > both referring to the same list value. > > To copy a list, we can use a whole slice: > > ##################### > message = ['hello', 'world'] > copy = message[:] > copy.append('!') > print copy > print message > ##################### > > > I don't know what your program looks like at this point, so I can't > pinpoint exactly where this is happening, but at the very least, this > should help you figure out what's going on. > > Feel free to ask if you'd like more explanation. If you'd like a > visualization, also see: > > http://pythontutor.com/visualize.html#code=message+%3D+%5B'hello > ',+'world'%5D%0Acopy+%3D+message%0Acopy.append('!')&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=2&rawInputLstJSON=%5B%5D&curInstr=0 > > and compare vs: > > http://pythontutor.com/visualize.html#code=message+%3D+%5B'hello > ',+'world'%5D%0Acopy+%3D+message%5B%3A%5D%0Acopy.append('!')&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=2&rawInputLstJSON=%5B%5D&curInstr=0 > > > Good luck! > > > ------------------------------ > > Message: 3 > Date: Sat, 21 Feb 2015 13:58:20 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] subprocess outputing wrong info to command line > Message-ID: <20150221025815.GG7655 at ando.pearwood.info> > Content-Type: text/plain; charset=us-ascii > > On Fri, Feb 20, 2015 at 06:58:17PM -0500, brads wrote: > > > My subprocess is in error but the same command at the command line works > > fine. > > Are you running the Python script as the same user and from the same > location as the command line? If you are running the Python script as an > unprivileged user from your home directory, and the command line as root > from the directory holding the key, then it is not surprising that they > will get different results. > > Does the dnssec-signzone command use any environment variables? Perhaps > they are not being inherited by the Python subprocess. > > Also, a note about sending code to the list. For some reason, every line > in your code is separated by blank lines: > > > # cat makekeys.py > > > > #!/usr/bin/python3.4 > > > > import subprocess > > > > import sys > > etc. That makes it very hard to read. Please fix that. > > Secondly, you have a huge amount of extraneous code which is irrelevant > to your problem with subprocess. You calculate dates, ask the user for > input, delete files, and write new files, calculate arrays and more. > None of that has anything to do with subprocess. Take it out. Reduce > your problem to the smallest possible code which shows the problem. 9 > times out of 10, the process of cutting your code down to manageable > size will actually help you to solve your own problem, and the other 1 > time out of 10 we have a smaller and less confusing piece of code to try > to understand. > > You also have dead, obsolete code commented out. Comments should not be > used for keeping history in the file, comments should be used for > commenting about the code. Best practice is to use a revision control > system like hg, but if you're not up to that at least delete the dead > code before posting. > > When running into a problem with subprocess, your first step should be > to *exactly* duplicate the successful command: > > dnssec-signzone -e20180330000000 -p -t -g -k Ktest123.com.ksk.key -o > test123.com test123.com.external Ktest123.com.zsk.key > > > So you should try running that from subprocess: > > subprocess.call([ > 'dnssec-signzone', '-e20180330000000', '-p', '-t', '-g', > '-k', 'Ktest123.com.ksk.key', '-o', 'test123.com', > 'test123.com.external', 'Ktest123.com.zsk.key', > ]) > > > and see if it still works. If it still does not work, that strongly > suggests a problem with the environment: you are running it as the wrong > user, in the wrong location, missing enviromnent variables or > permissions. If it works in Python, then you can start replacing each > constant argument with a calculated argument, *one argument at a time*, > and see where you introduce the bug. > > > > -- > Steve > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 132, Issue 51 > ************************************** > From danny.yoo at gmail.com Sat Feb 21 18:04:26 2015 From: danny.yoo at gmail.com (Danny Yoo) Date: Sat, 21 Feb 2015 09:04:26 -0800 Subject: [Tutor] Tutor Digest, Vol 132, Issue 51 In-Reply-To: References: Message-ID: On Feb 21, 2015 8:49 AM, "Tim Johnson" wrote: > > Hi Guys, > Very simple question, I imagine. > > this code throws of off a "counter not defined error". > Can you help? > > *def word_counter(word, string):* > * counter = 0* > * for item in string:* > * if item == word:* > * counter = counter + 1* > *print counter* Hmmm... I don't understand what the intent of the last line of the program is. Can you explain what you're trying to do there? Do you intend to do this print after the for loop? If so, it should still be scoped to the function though. At the moment, it is a statement that's entirely separate from the function definition. Good luck! From alan.gauld at btinternet.com Sat Feb 21 18:05:01 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 Feb 2015 17:05:01 +0000 Subject: [Tutor] Tutor Digest, Vol 132, Issue 51 In-Reply-To: References: Message-ID: On 21/02/15 16:48, Tim Johnson wrote: > Hi Guys, Hi, please don't send the entire digest, some folks pay by the byte. Ideally send a new mail to tutor at python.org instead of replying to an existing digest. Also change the subject to something meaningful so folks an find it in the archives. > *def word_counter(word, string):* > * counter = 0* > * for item in string:* > * if item == word:* > * counter = counter + 1* > *print counter* Your last line is outside the function so counter is invisible to it. You need to indent the line so it is in line with the for... line However I suspect this function is not going to do what you hope it will. item will iterate over the characters in the string not the words. You probably want something like def word)_counter(word, string): count = 0 for group in string.split(): if group == word: count += 1 return count hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Sat Feb 21 18:07:46 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 21 Feb 2015 17:07:46 +0000 Subject: [Tutor] Counter not defined error In-Reply-To: References: Message-ID: On 21/02/2015 16:48, Tim Johnson wrote: I've changed the subject line to reflect your question. Did you have to reply to the digest and include the lot of it, why couldn't you simply start a new thread? > Hi Guys, > Very simple question, I imagine. > > this code throws of off a "counter not defined error". > Can you help? > > *def word_counter(word, string):* > * counter = 0* > * for item in string:* > * if item == word:* > * counter = counter + 1* > *print counter* > > Tim Johnson > counter only exists within the scope of the word_counter function, the print statement is outside of that scope. Shifting the print statement right four spaces should do the trick. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From __peter__ at web.de Sat Feb 21 18:23:50 2015 From: __peter__ at web.de (Peter Otten) Date: Sat, 21 Feb 2015 18:23:50 +0100 Subject: [Tutor] NameError: name 'counter' is not defined, was Re: Tutor Digest, Vol 132, Issue 51 References: Message-ID: Tim Johnson wrote: > Hi Guys, Hi Tim! > Very simple question, I imagine. > > this code throws of off a "counter not defined error". Instead of retyping the error message it is better to cut and paste the traceback, e. g. Traceback (most recent call last): File "tmp.py", line 6, in print counter NameError: name 'counter' is not defined > Can you help? > > def word_counter(word, string): > counter = 0 > for item in string: > if item == word: > counter = counter + 1 > print counter When you assign a value to a variable inside a function that variable is only known inside that function and only during the execution of that function. When you move the print statement into the function it should work as the following session in the interactive interpreter demonstrates: >>> def word_counter(word, string): ... counter = 0 ... for item in string: ... if item == word: ... counter = counter + 1 ... print counter ... >>> word_counter("the", "the house by the sea") 0 Oops! by default a for loop iterates over the characters in a string, not the words. Let's try with a list of words: >>> word_counter("the", ["the", "house", "by", "the", "sea"]) 2 If you want to allow a string argument you can modify your function to iterate over for item in string.split(): ... Another improvement would be to have the function return the counter instead of printing it. That way you can do other things with it: >>> def word_counter(word, string): ... counter = 0 ... for item in string.split(): ... if item == word: ... counter = counter + 1 ... return counter ... >>> phrase = "the house by the sea" >>> num_words = len(phrase.split()) >>> print 100.0 * word_counter("the", phrase) / num_words, "percent of all words are 'the'" 40.0 percent of all words are 'the' From mishal.619rulz at gmail.com Wed Feb 25 14:00:51 2015 From: mishal.619rulz at gmail.com (Mishal Chowdhury) Date: Wed, 25 Feb 2015 18:30:51 +0530 Subject: [Tutor] Questions Regarding ASPECT ORIENTED PROGRAMMING (AOP) Message-ID: 1. Is it Possible to call a function which is defined in a child class from a parent class through a web service? 2. Can I Create an Aspect Class and create a child class of the Aspect class and allow another class to access the child aspect class methods? Could I please get an example code to see whether the above situations are possible or not? Thanks in advance Cheers From alan.gauld at btinternet.com Wed Feb 25 20:16:53 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Feb 2015 19:16:53 +0000 Subject: [Tutor] Questions Regarding ASPECT ORIENTED PROGRAMMING (AOP) In-Reply-To: References: Message-ID: On 25/02/15 13:00, Mishal Chowdhury wrote: First, I'm not sure that either of these questions have to do with Aspect Oriented Programming per se. Note however that Python does not offer any specific support for AOP. (You can't explicitly define an 'Aspect' like you can a class for example) > 1. Is it Possible to call a function which is defined in a child class from > a parent class through a web service? Yes, if you write a suitable web service, otherwise no. And if you set up the classes such that a feature in the parent class knows about the child class function (do you mean method?) Remember that by default Python classes do not implement data hiding so it is very easy to peek inside a class. > 2. Can I Create an Aspect Class and create a child class of the Aspect > class and allow another class to access the child aspect class methods? Yes, but these would just be normal python classes being used to simulate AOP type features. There is nothing in Python to explicitly support that. And do you really mean classes here or are you really meaning instances? When you start mixing styles like that you need to be very precise with your terminology. > Could I please get an example code to see whether the above situations are > possible or not? You can try to write your own code and we will help you make it work. Python offers many ways to implement Aspects such that the users of the Aspects are minimally aware of them, such as decorators, and in some cases context managers, and even metaclasses. In other situations multiple inheritance can be used. But in each case you are faking real AOP style, and it will take some effort to write. Python is not AspectJ. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From kailashgkg at gmail.com Thu Feb 26 07:54:17 2015 From: kailashgkg at gmail.com (kailash ganesh) Date: Thu, 26 Feb 2015 12:24:17 +0530 Subject: [Tutor] How to save telnet output logs to a text file in python Message-ID: Hi All, Please someone help on the below request. I am learning python and trying to connect my satellite decoder using telnet. When I tried to connect my device through telnet python script, I could successfully connected to the device. But i want to capture/save as well as read the output and logs of device (connected thru telnet) from starting in a text file. Also, i want to send few commands to get the output of the command and store in the text file. Please kindly help on how to capture and write the output logs of device connected thru telnet connection in a local text file. Note: Once the password is successful, my device prints some set of logs and it has to capture in the local text file, also the output of commands should also record in the text file. 1. HOST = "192.131.244.100" 2. user = "user" 3. password = "user" 4. 5. tn = Telnet(HOST) 6. tn.read_until("Login: ") 7. tn.write(user + "\n") 8. tn.read_until("Password: ") 9. tn.write(password + "\n") 10. time.sleep(5) 11. tn.write("lr\n") # lr is command to pause logs 12. tn.write("version\n") # command to check running software version 13. tn.write("exit\n") 14. str_all = tn.read_all() 15. 16. f = open("C:\\temp\\Logs\\output.txt", 'w') 17. f.write(str_all) 18. tn.close() Not able to read and save all logs from starting. Also, pls. let me know any other way to save telnet output either in putty or teraterm. From kcberry07 at yahoo.com Thu Feb 26 05:30:38 2015 From: kcberry07 at yahoo.com (kcberry) Date: Wed, 25 Feb 2015 20:30:38 -0800 (PST) Subject: [Tutor] Don't Understand Problem Message-ID: <1424925038005-5087587.post@n6.nabble.com> So I am new to this, and I have a book call /Hello Python by Anthony Briggs/. It is a good book but it is using Python 2 I think and I can't get my code to work. I get an "AttributeError: 'range' object has no attribute 'remove'". I have tried to look it up on the web with no luck. Can someone help me understand this . ********** #Setting up the cave from random import choice cave_numbers = range(0,20) caves = [] for i in cave_numbers: caves.append([]) #Setting up cave network unvisited_caves = range(0,20) current = 0 visited_caves = [0] *unvisited_caves.remove(0)* #Main loop of linking cave network while unvisited_caves != []: #Picking a random visited cave i = choice(visited_caves) if len(caves[i]) >= 3: continue #link to unvisited caves next_cave = choice(unvisited_caves) caves[i].append(next_cave) caves[next_cave].append(i) #Marking cave as visited visited_caves.append(next_cave) *unvisited_caves.remove(next_cave)* #Progress report for number in cave_numbers: print( number, ":", caves[number]) print('----------') for i in cave_numbers: while len(caves[i]) < 3: passage_to = choice(cave_numbers) caves[i].append(passage_to) for number in cave_numbers: print(number, ":", caves[number]) print('---------') print(caves) -- View this message in context: http://python.6.x6.nabble.com/Don-t-Understand-Problem-tp5087587.html Sent from the Python - tutor mailing list archive at Nabble.com. From alan.gauld at btinternet.com Thu Feb 26 09:55:55 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Feb 2015 08:55:55 +0000 Subject: [Tutor] Don't Understand Problem In-Reply-To: <1424925038005-5087587.post@n6.nabble.com> References: <1424925038005-5087587.post@n6.nabble.com> Message-ID: On 26/02/15 04:30, kcberry wrote: > So I am new to this, and I have a book call /Hello Python by Anthony Briggs/. > It is a good book but it is using Python 2 I think and I can't get my code > to work. I get an "AttributeError: 'range' object has no attribute > 'remove'". I have tried to look it up on the web with no luck. Can someone > help me understand this . Please always send full error traces, they contain a lot of useful details. Meantime in this case we can figure it out... > #Setting up cave network > unvisited_caves = range(0,20) > current = 0 > visited_caves = [0] > *unvisited_caves.remove(0)* In Python 3 eange does not return a list. It returns something called a "range object" which helps save memory for large daya sets. If you need to use it as a list you need to explicitly convert it using list(): unvisited_caves = range(0,20) ... unvisited_caves.remove(0) However remove() may not do what you think. It removes the value zero from your list not the first element. I this case they are the same but in other cases they might not be. You may want to use del() instead del(unvisited_caves[0]) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From timomlists at gmail.com Thu Feb 26 12:06:52 2015 From: timomlists at gmail.com (Timo) Date: Thu, 26 Feb 2015 12:06:52 +0100 Subject: [Tutor] Don't Understand Problem In-Reply-To: References: <1424925038005-5087587.post@n6.nabble.com> Message-ID: <54EEFE4C.4060605@gmail.com> Op 26-02-15 om 09:55 schreef Alan Gauld: > On 26/02/15 04:30, kcberry wrote: >> So I am new to this, and I have a book call /Hello Python by Anthony >> Briggs/. >> It is a good book but it is using Python 2 I think and I can't get my >> code >> to work. I get an "AttributeError: 'range' object has no attribute >> 'remove'". I have tried to look it up on the web with no luck. Can >> someone >> help me understand this . > > Please always send full error traces, they contain a lot of useful > details. > > Meantime in this case we can figure it out... > >> #Setting up cave network >> unvisited_caves = range(0,20) >> current = 0 >> visited_caves = [0] >> *unvisited_caves.remove(0)* > > In Python 3 eange does not return a list. It returns something called > a "range object" which helps save memory for large daya sets. > If you need to use it as a list you need to explicitly > convert it using list(): > > unvisited_caves = range(0,20) I think you missed your own solution here, Alan. You probably meant: unvisited_caves = list(range(0, 20)) Timo > ... > unvisited_caves.remove(0) > > However remove() may not do what you think. It removes the > value zero from your list not the first element. I this case they are > the same but in other cases they might not be. You may want to use > del() instead > > del(unvisited_caves[0]) > > HTH > From steve at pearwood.info Thu Feb 26 12:38:57 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 26 Feb 2015 22:38:57 +1100 Subject: [Tutor] Don't Understand Problem In-Reply-To: References: <1424925038005-5087587.post@n6.nabble.com> Message-ID: <20150226113857.GU7655@ando.pearwood.info> On Thu, Feb 26, 2015 at 08:55:55AM +0000, Alan Gauld wrote: > However remove() may not do what you think. It removes the > value zero from your list not the first element. I this case they are > the same but in other cases they might not be. You may want to use del() > instead > > del(unvisited_caves[0]) del is not a function, it is a statement, so it doesn't need the brackets (parentheses for any Americans reading). del unvisited_caves[0] Although the parens don't do any harm. To be clear, `del somelist[x]` deletes the xth item from somelist. But `somelist.remove(x)` deletes the first item that equals x, equivalent to this Python code: for i in range(len(somelist)): if somelist[i] == x: del somelist[i] break -- Steve From steve at pearwood.info Thu Feb 26 13:03:20 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 26 Feb 2015 23:03:20 +1100 Subject: [Tutor] How to save telnet output logs to a text file in python In-Reply-To: References: Message-ID: <20150226120320.GV7655@ando.pearwood.info> On Thu, Feb 26, 2015 at 12:24:17PM +0530, kailash ganesh wrote: > Hi All, > > Please someone help on the below request. > > I am learning python and trying to connect my satellite decoder using > telnet. When I tried to connect my device through telnet python script, I > could successfully connected to the device. Can you show the code you use? You have something below which looks like code, but it doesn't seem to be Python. It has line numbers. Can you explain what it is please? > But i want to capture/save as well as read the output and logs of device > (connected thru telnet) from starting in a text file. Also, i want to send > few commands to get the output of the command and store in the text file. The documentation for the telnetlib module includes this example: >>> from telnetlib import Telnet >>> tn = Telnet('www.python.org', 79) # connect to finger port >>> tn.write(b'guido\r\n') >>> print(tn.read_all()) Login Name TTY Idle When Where guido Guido van Rossum pts/2 snag.cnri.reston.. I tried running that example, but www.python.org doesn't respond for me and I eventually got this error: TimeoutError: [Errno 110] Connection timed out Maybe my firewall blocks that port, or maybe the site is not listening. But the important part is the tn.read_all() function. If that works for you, you can do this instead: output = tn.read_all() # display to screen print(output) # write to a file with open("MyFile.txt", "wb") as f: f.write(output) # Check that the file wrote correctly. with open("MyFile.txt", "rb") as f: print(f.read()) Does that help? If you need more help, please show your code, without line numbers, and show any errors you get. -- Steve From beachkidken at gmail.com Thu Feb 26 13:13:57 2015 From: beachkidken at gmail.com (Ken G.) Date: Thu, 26 Feb 2015 07:13:57 -0500 Subject: [Tutor] Rearranging a list Message-ID: <54EF0E05.7000301@gmail.com> Assuming I have the following list and code how do I best be able rearrange the list as stated below: list = [0, 0, 21, 35, 19, 42] Using print list[2:6] resulted in the following: 2 21 3 35 4 19 5 42 I would like to rearrange the list as follow: 5 42 3 35 2 21 4 19 I tried using list.reverse() and print list[0,6] and it resulted in: [42, 19, 35, 21, 0, 0] or as printed: 0 42 1 19 2 35 3 21 4 0 5 0 In another words, I would desire to show that: 5 appears 42 times 3 appears 35 times 2 appears 21 times 4 appears 19 times but then I lose my original index of the numbers by reversing. How do I best keep the original index number to the rearrange numbers within a list? Thanking in advance, Ken From __peter__ at web.de Thu Feb 26 13:30:54 2015 From: __peter__ at web.de (Peter Otten) Date: Thu, 26 Feb 2015 13:30:54 +0100 Subject: [Tutor] Rearranging a list References: <54EF0E05.7000301@gmail.com> Message-ID: Ken G. wrote: > Assuming I have the following list and code how do I best be able > rearrange the list as stated below: > > list = [0, 0, 21, 35, 19, 42] > > Using print list[2:6] resulted in the following: > > 2 21 > 3 35 > 4 19 > 5 42 > > I would like to rearrange the list as follow: > > 5 42 > 3 35 > 2 21 > 4 19 > > I tried using list.reverse() and print list[0,6] and it resulted in: > > [42, 19, 35, 21, 0, 0] or as printed: > > 0 42 > 1 19 > 2 35 > 3 21 > 4 0 > 5 0 > > In another words, I would desire to show that: > > 5 appears 42 times > 3 appears 35 times > 2 appears 21 times > 4 appears 19 times > > but then I lose my original index of the numbers by reversing. How do I > best keep the original index number to the rearrange numbers within a > list? Don't rearrange the original list, make a new one instead: >>> frequencies = [0, 0, 21, 35, 19, 42] >>> wanted_indices = [5, 3, 2, 4] >>> [frequencies[i] for i in wanted_indices] [42, 35, 21, 19] Or look up the values as you print them: >>> for i in wanted_indices: ... print(i, "appears", frequencies[i], "times") ... 5 appears 42 times 3 appears 35 times 2 appears 21 times 4 appears 19 times The expression [frequencies[i] for i in wanted_indices] is called "list comprehension" and is a shortcut for a loop: >>> result = [] >>> for i in wanted_indices: ... result.append(frequencies[i]) ... >>> result [42, 35, 21, 19] From steve at pearwood.info Thu Feb 26 13:40:20 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 26 Feb 2015 23:40:20 +1100 Subject: [Tutor] Rearranging a list In-Reply-To: <54EF0E05.7000301@gmail.com> References: <54EF0E05.7000301@gmail.com> Message-ID: <20150226124016.GW7655@ando.pearwood.info> On Thu, Feb 26, 2015 at 07:13:57AM -0500, Ken G. wrote: > Assuming I have the following list and code how do I best be able > rearrange the list as stated below: > > list = [0, 0, 21, 35, 19, 42] Be aware that you have "shadowed" the built-in list function, which could cause trouble for you. py> list = [1, 2, 3] py> # much later, after you have forgotten you shadowed list... py> characters = list("Hello world") Traceback (most recent call last): File "", line 1, in TypeError: 'list' object is not callable Oops. Save yourself future hassles, and pick a name like "L" (don't use "l", since that looks too similar to digit 1) or "mylist" or "seq" (short for sequence). > Using print list[2:6] resulted in the following: > > 2 21 > 3 35 > 4 19 > 5 42 I'm pretty sure it doesn't. py> lst = [0, 0, 21, 35, 19, 42] py> print(lst[2:6]) [21, 35, 19, 42] You're obviously doing a lot more than just `print lst[2:6]` to get the output you say you are getting. > I would like to rearrange the list as follow: > > 5 42 > 3 35 > 2 21 > 4 19 I don't understand how to generalise that. If you know you want that EXACT output, you can say: print "5 42" print "3 35" etc. to get it. Obviously that's not what you want, but I don't understand what rule you used to get "5 42" first, "3 35" second, etc. Where does the 5, 3, 2, 4 come from? What's the rule for getting 42 first, 19 last? > I tried using list.reverse() and print list[0,6] and it resulted in: > > [42, 19, 35, 21, 0, 0] or as printed: > > 0 42 > 1 19 > 2 35 > 3 21 > 4 0 > 5 0 > > In another words, I would desire to show that: > > 5 appears 42 times > 3 appears 35 times > 2 appears 21 times > 4 appears 19 times Huh? Now I'm *completely* confused. Your list was: [0, 0, 21, 35, 19, 42] 5, 3, 2 and 4 don't appear *at all*. You have: 0 appears twice 21 appears once 35 appears once 19 appears once 42 appears once > but then I lose my original index of the numbers by reversing. How do I > best keep the original index number to the rearrange numbers within a list? No clue what you mean. -- Steve From steve at pearwood.info Thu Feb 26 13:51:05 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 26 Feb 2015 23:51:05 +1100 Subject: [Tutor] Rearranging a list In-Reply-To: <54EF0E05.7000301@gmail.com> References: <54EF0E05.7000301@gmail.com> Message-ID: <20150226125105.GX7655@ando.pearwood.info> Ah wait, the penny drops! Now I understand what you mean! On Thu, Feb 26, 2015 at 07:13:57AM -0500, Ken G. wrote: > In another words, I would desire to show that: > > 5 appears 42 times > 3 appears 35 times > 2 appears 21 times > 4 appears 19 times > > but then I lose my original index of the numbers by reversing. How do I > best keep the original index number to the rearrange numbers within a list? Here's your list again: [0, 0, 21, 35, 19, 42] I think using a list is the wrong answer. I think you should use a dictionary: d = {0: 0, 1: 0, 2: 21, 3: 35, 4: 19, 5: 42} for key, value in sorted(d.items(), reverse=True): print(key, value) which gives this output: 5 42 4 19 3 35 2 21 1 0 0 0 How should you build the dict in the first place? There's an easy way, and an even easier way. Here's the easy way. # count the numbers numbers = [2, 3, 1, 4, 0, 4, 2, 5, 2, 3, 4, 1, 1, 1, 3, 5] counts = {} for n in numbers: i = counts.get(n, 0) counts[n] = i + 1 print(counts) which gives output: {0: 1, 1: 4, 2: 3, 3: 3, 4: 3, 5: 2} Here's the even easier way: from collections import Counter counts = Counter(numbers) print(counts) which gives very similar output: Counter({1: 4, 2: 3, 3: 3, 4: 3, 5: 2, 0: 1}) In both cases, you then run the earlier code to print the items in order: for key, value in sorted(counts.items(), reverse=True): print(key, value) -- Steve From __peter__ at web.de Thu Feb 26 14:03:14 2015 From: __peter__ at web.de (Peter Otten) Date: Thu, 26 Feb 2015 14:03:14 +0100 Subject: [Tutor] Rearranging a list References: <54EF0E05.7000301@gmail.com> Message-ID: Peter Otten wrote: > Ken G. wrote: > >> Assuming I have the following list and code how do I best be able >> rearrange the list as stated below: >> >> list = [0, 0, 21, 35, 19, 42] >> >> Using print list[2:6] resulted in the following: >> >> 2 21 >> 3 35 >> 4 19 >> 5 42 >> >> I would like to rearrange the list as follow: >> >> 5 42 >> 3 35 >> 2 21 >> 4 19 >> >> I tried using list.reverse() and print list[0,6] and it resulted in: >> >> [42, 19, 35, 21, 0, 0] or as printed: >> >> 0 42 >> 1 19 >> 2 35 >> 3 21 >> 4 0 >> 5 0 >> >> In another words, I would desire to show that: >> >> 5 appears 42 times >> 3 appears 35 times >> 2 appears 21 times >> 4 appears 19 times >> >> but then I lose my original index of the numbers by reversing. How do I >> best keep the original index number to the rearrange numbers within a >> list? > > Don't rearrange the original list, make a new one instead: > >>>> frequencies = [0, 0, 21, 35, 19, 42] >>>> wanted_indices = [5, 3, 2, 4] >>>> [frequencies[i] for i in wanted_indices] > [42, 35, 21, 19] > > Or look up the values as you print them: > >>>> for i in wanted_indices: > ... print(i, "appears", frequencies[i], "times") > ... > 5 appears 42 times > 3 appears 35 times > 2 appears 21 times > 4 appears 19 times > > The expression [frequencies[i] for i in wanted_indices] is called "list > comprehension" and is a shortcut for a loop: > >>>> result = [] >>>> for i in wanted_indices: > ... result.append(frequencies[i]) > ... >>>> result > [42, 35, 21, 19] Oops, it occurs to me that you may want the most frequent indices rather than specific indices. You can achieve that with >>> def lookup_frequency(index): ... return frequencies[index] ... >>> wanted_indices = sorted(range(len(frequencies)), key=lookup_frequency, reverse=True) >>> wanted_indices [5, 3, 2, 4, 0, 1] >>> wanted_indices[:4] [5, 3, 2, 4] You may also want to look at the collections.Counter class: >>> import collections >>> c = collections.Counter() >>> for i, freq in enumerate(frequencies): ... c[i] = freq ... >>> c.most_common(4) [(5, 42), (3, 35), (2, 21), (4, 19)] >> for key, freq in c.most_common(4): ... print(key, "appears", freq, "times") ... 5 appears 42 times 3 appears 35 times 2 appears 21 times 4 appears 19 times From __peter__ at web.de Thu Feb 26 14:04:51 2015 From: __peter__ at web.de (Peter Otten) Date: Thu, 26 Feb 2015 14:04:51 +0100 Subject: [Tutor] Rearranging a list References: <54EF0E05.7000301@gmail.com> <20150226125105.GX7655@ando.pearwood.info> Message-ID: Steven D'Aprano wrote: > Ah wait, the penny drops! Now I understand what you mean! Glad I'm not the only one ;) From ftaghdia at gmail.com Thu Feb 26 12:52:27 2015 From: ftaghdia at gmail.com (Fatimah Taghdi) Date: Thu, 26 Feb 2015 06:52:27 -0500 Subject: [Tutor] Don't get it Message-ID: I have a qestion about understanding my assignment. I was wonerding if it is possible for someone to expalin. it this is whar it asks of This assignment question will give you practice with recursive backtracking. You are to create a class called AnagramSolver that uses a word list to ?nd all combinations of words that have the same letters as a given phrase. You might want to ?rst look at the sample log of execution at the end of this part of the assignment and i am unsure of how to work with these guidlines for the constructor of the class A constructor, __init__. Takes a list of words, and constructs an anagram solver that will use the given list as its dictionary. It is not to modify the list -- *F.T.* From shouqiang1989 at sina.com Thu Feb 26 06:53:37 2015 From: shouqiang1989 at sina.com (shouqiang1989 at sina.com) Date: Thu, 26 Feb 2015 13:53:37 +0800 Subject: [Tutor] Remove a blank row of a Table Message-ID: <20150226055338.52A26117015E@webmail.sinamail.sina.com.cn> Hello, everybody: I came accross a question a few days ago. I wrote a Python script to copy something to a table in a word file. For some reaons, there are some blank rows. And I want to remove the blank rows. I tried many ways, but all didn't work. Below is the code. desfile='C:\\Daten\\TestCASE5\\Model_hill.doc' fd = w.Documents.Open(desfile) lNam = textwrap.wrap(reportItem.PName) maxLines = len(lNam) for idx in xrange (1,maxLines) : if fd.Tables[6].Rows[idx].Cells[1] == None : fd.Tables[6].Rows[idx].Remove() else : pass Thanks in advance _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Thu Feb 26 15:35:59 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Feb 2015 14:35:59 +0000 Subject: [Tutor] Don't Understand Problem In-Reply-To: <54EEFE4C.4060605@gmail.com> References: <1424925038005-5087587.post@n6.nabble.com> <54EEFE4C.4060605@gmail.com> Message-ID: On 26/02/15 11:06, Timo wrote: >> If you need to use it as a list you need to explicitly >> convert it using list(): >> >> unvisited_caves = range(0,20) > I think you missed your own solution here, Alan. You probably meant: > > unvisited_caves = list(range(0, 20)) Oops! Thanks for picking that up. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Thu Feb 26 15:46:21 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Feb 2015 14:46:21 +0000 Subject: [Tutor] Don't get it In-Reply-To: References: Message-ID: On 26/02/15 11:52, Fatimah Taghdi wrote: > I have a qestion about understanding my assignment. I was wonerding if it > is possible for someone to expalin. it Your teacher maybe? As it is you have taken a question which puzzles you, sent us only a part of it and somehow expect us to understand it all based only on your partial information. > This assignment question will give you practice with recursive > backtracking. You are to create a class called AnagramSolver that uses a > word list to ?nd all combinations of words that have the same letters as a > given phrase. That rather depends on what the definition of a "word" is. If its any combination of the letters given its not too difficult. If they must be valid words then you need a definitive list (ie a lexicon) to check against. > You might want to ?rst look at the sample log of execution at > the end of this part of the assignment Maybe that would help us too? > and i am unsure of how to work with these guidlines for the constructor of > the class > > A constructor, __init__. Takes a list of words, and constructs an anagram > solver that will use the given list as its dictionary. It is not to modify > the list Is that last paragraph your interpretation or part of the assignment? If the latter then letting us see any other hints might help us figure out what your teacher is thinking of. As it is we can only make wild guesses. Have you tried asking your teacher for clarification? In my experience most teachers are happy to help if you ask intelligent questions that show you have seriously thought about the assignment first, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Thu Feb 26 15:50:55 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Feb 2015 14:50:55 +0000 Subject: [Tutor] Remove a blank row of a Table In-Reply-To: <20150226055338.52A26117015E@webmail.sinamail.sina.com.cn> References: <20150226055338.52A26117015E@webmail.sinamail.sina.com.cn> Message-ID: On 26/02/15 05:53, shouqiang1989 at sina.com wrote: > Hello, everybody: I came accross a question a few days > ago. I wrote a Python script to copy something to a table in a word > file. For some reaons, there are some blank rows. And I want to remove > the blank rows. I tried many ways, but all didn't work. Below is the As you can probably see your code came scrambled beyond reasonable recognition. (We can guess but we can't be sure) Can you repost in plain text please, not in HTML. > code. desfile='C:\\Daten\\TestCASE5\\Model_hill.doc' > fd = w.Documents.Open(desfile) lNam = textwrap.wrap(reportItem.PName) > maxLines = len(lNam) for idx in xrange (1,maxLines) : > if fd.Tables[6].Rows[idx].Cells[1] == None : > fd.Tables[6].Rows[idx].Remove() > else : > pass Also, since Python by default can't handle Word files can you tell us which library you are using to do this. In other words in the line: fd = w.Documents.Open(desfile) Where do w, Document, and Open() come from? They are seemingly not a part of the standard Python library. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From beachkidken at gmail.com Thu Feb 26 17:33:35 2015 From: beachkidken at gmail.com (Ken G.) Date: Thu, 26 Feb 2015 11:33:35 -0500 Subject: [Tutor] Rearranging a list In-Reply-To: References: <54EF0E05.7000301@gmail.com> <20150226125105.GX7655@ando.pearwood.info> Message-ID: <54EF4ADF.4030406@gmail.com> I may have mis-stated my intention. I will rewrite my request for assistance later and resubmit. Thanks, Ken On 02/26/2015 08:04 AM, Peter Otten wrote: > Steven D'Aprano wrote: > >> Ah wait, the penny drops! Now I understand what you mean! > Glad I'm not the only one ;) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From huijae_kim at hotmail.com Thu Feb 26 19:04:25 2015 From: huijae_kim at hotmail.com (Huijae) Date: Fri, 27 Feb 2015 03:04:25 +0900 Subject: [Tutor] Gaussian process regression Message-ID: Hi, I am trying to use Gaussian process regression for Near Infrared spectra. I have reference data(spectra), concentrations of reference data and sample data, and I am trying to predict concentrations of sample data. Here is my code. from sklearn.gaussian_process import GaussianProcess gp = GaussianProcess() gp.fit(reference, concentration) concentration_pred = gp.predict(sample) The results always gave me the same concentration even though I used different sample data. When I used some parts of reference data as sample data, it predicted concentration well. But whenever I use different data than reference data, it always gave me the same concentration. Can I get some help with this problem? What am I doing wrong? I would appreciate any help. Thanks, Jay From alan.gauld at btinternet.com Thu Feb 26 19:37:10 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Feb 2015 18:37:10 +0000 Subject: [Tutor] Gaussian process regression In-Reply-To: References: Message-ID: On 26/02/15 18:04, Huijae wrote: > Hi, I am trying to use Gaussian process regression for Near Infrared spectra. I have reference data(spectra), concentrations of reference data and sample data, and I am trying to predict concentrations of sample data. Here is my code. > from sklearn.gaussian_process import GaussianProcess gp = GaussianProcess() gp.fit(reference, concentration) concentration_pred = gp.predict(sample) The results always gave me the same concentration even though I used different sample data. When I used some parts of reference data as sample data, it predicted concentration well. But whenever I use different data than reference data, it always gave me the same concentration. Can I get some help with this problem? What am I doing wrong? I would appreciate any help. Thanks, Jay As you can probably see, your code did not make it through in readable form as HTML. Can you please repost using plain text? Also this list is aimed at beginners to Python using the standard library. You are evidently using some kind of third party library - SciPy maybe? If so you may get a better response on the SciPy support forums where more people are likely to be familiar with your issues. However, once we can see the code, some members here do use Python in science/math so might be able to help. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Thu Feb 26 22:16:01 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 26 Feb 2015 21:16:01 +0000 Subject: [Tutor] Rearranging a list In-Reply-To: <54EF4ADF.4030406@gmail.com> References: <54EF0E05.7000301@gmail.com> <20150226125105.GX7655@ando.pearwood.info> <54EF4ADF.4030406@gmail.com> Message-ID: On 26/02/2015 16:33, Ken G. wrote: > I may have mis-stated my intention. I will rewrite > my request for assistance later and resubmit. > > Thanks, > > Ken > When you come back please don't top post, it makes following long threads difficult if not impossible, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From willie14228 at outlook.com Thu Feb 26 21:51:00 2015 From: willie14228 at outlook.com (Willie Sims) Date: Thu, 26 Feb 2015 14:51:00 -0600 Subject: [Tutor] Use python to parse the subject line of emails, listen for and react to commands Message-ID: Hello I have been trying to figure out a way to parse the subject line of new emails in Gmail, the subject line will be commands for another python script. I know this isn't the most secure way of doing things but it is for a Beagle Bone, I'm really new to python and don't know of this is even possible though I don't see why not. The way I thought it would work would to have py check email subject lines coming from one sender when it sees a subject "Command(the command to follow)" it would then start another py script with that command, or otherwise sees the subject Settings(the item to change(the change)) it would change a settings page. I haven't found any examples of using py to loop back on itself like this, mostly I'm sure because this is not secure and easy to hack and clunky for remote access, I know py can parse emails, but I cant figure out how to limit to only the subject and only if its in that certain format and only if its coming from a recognized email address and since I'm using 3.4 it seems all the other kind of examples don't work half the time anyway. can someone point me in the right direction From breamoreboy at yahoo.co.uk Fri Feb 27 00:24:38 2015 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 26 Feb 2015 23:24:38 +0000 Subject: [Tutor] Use python to parse the subject line of emails, listen for and react to commands In-Reply-To: References: Message-ID: On 26/02/2015 20:51, Willie Sims wrote: > Hello I have been trying to figure out a way to parse the subject line of new emails in Gmail, the subject line will be commands for another python script. I know this isn't the most secure way of doing things but it is for a Beagle Bone, I'm really new to python and don't know of this is even possible though I don't see why not. The way I thought it would work would to have py check email subject lines coming from one sender when it sees a subject "Command(the command to follow)" it would then start another py script with that command, or otherwise sees the subject Settings(the item to change(the change)) it would change a settings page. > I haven't found any examples of using py to loop back on itself like this, mostly I'm sure because this is not secure and easy to hack and clunky for remote access, > I know py can parse emails, but I cant figure out how to limit to only the subject and only if its in that certain format and only if its coming from a recognized email address and since I'm using 3.4 it seems all the other kind of examples don't work half the time anyway. > can someone point me in the right direction > Will this https://docs.python.org/3/library/email-examples.html at least get you going? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From alan.gauld at btinternet.com Fri Feb 27 01:18:23 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Feb 2015 00:18:23 +0000 Subject: [Tutor] Use python to parse the subject line of emails, listen for and react to commands In-Reply-To: References: Message-ID: On 26/02/15 20:51, Willie Sims wrote: > I know py can parse emails, but I cant figure out how to limit to only > the subject and only if its in that certain format > and only if its coming from a recognized email address OK, Show us what you've tried. That makes it easier for us to see what is tripping you up. Otherwise we are just guessing. All 3 things you ask for can be done but we need a starting point and the best one is your existing, but faulty, code. > and since I'm using 3.4 it seems all the other kind of examples don't work A lot of old examples on the web will be for Python v32 and there are significant differences to v3. However, Python v3 has not lost any important functionality so whatever worked in v2 can be made to work in v3. Again we just need a clue as to what you are trying to do. (show us your code - and any error messages and tell us your OS too) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Fri Feb 27 02:57:00 2015 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 27 Feb 2015 12:57:00 +1100 Subject: [Tutor] Gaussian process regression In-Reply-To: References: Message-ID: <20150227015659.GY7655@ando.pearwood.info> On Fri, Feb 27, 2015 at 03:04:25AM +0900, Huijae wrote: > Hi, I am trying to use Gaussian process regression for Near Infrared > spectra. I have reference data(spectra), concentrations of reference > data and sample data, and I am trying to predict concentrations of > sample data. Here is my code. from sklearn.gaussian_process import > GaussianProcess gp = GaussianProcess() gp.fit(reference, > concentration) concentration_pred = gp.predict(sample) The results > always gave me the same concentration even though I used different > sample data. When I used some parts of reference data as sample data, > it predicted concentration well. But whenever I use different data > than reference data, it always gave me the same concentration. Can I > get some help with this problem? What am I doing wrong? I would > appreciate any help. Thanks, Jay Your mail program has mangled your code and mixed up the layout. I suggest turning off all formatting, "Rich Text" or HTML mail, since that usually destroys the layout of code. I'm going to try to guess your code's layout: from sklearn.gaussian_process import GaussianProcess gp = GaussianProcess() gp.fit(reference, concentration) concentration_pred = gp.predict(sample) This is not enough for us to give any meaningful advice. What is "sklearn"? What are "reference", "concentration", "sample"? We'd need to see actual data, and know what GaussianProcess does, to help. > The results always gave me the same concentration > even though I used different sample data. *Exactly* the same? To 17 decimal places? Or just close to the same? Perhaps the different samples give the same result because they are samples from the same population. > When I used some parts of > reference data as sample data, it predicted concentration well. But > whenever I use different data than reference data, it always gave me > the same concentration. You may need to ask people who know more about GaussianProcess and how it works. -- Steve From barbara_hgr at yahoo.com.br Fri Feb 27 03:16:56 2015 From: barbara_hgr at yahoo.com.br (Barbara Heliodora G. Rodrigues) Date: Fri, 27 Feb 2015 02:16:56 +0000 (UTC) Subject: [Tutor] Help with python in MAC OS 10.6 Message-ID: <199673520.1431247.1425003416015.JavaMail.yahoo@mail.yahoo.com> Dear tutor, I'd like to ask for help with an issue I have with python. My MAC is with OS 10-6.8, darwin kernel, 64 bits. For some reason I updated macports and it automatically updated python to 2.7 with a 32 bits library, and it is giving me lots of trouble. I can't install any new software that uses python, and recently I tried to use some plot (matplotlib) routines that were working fine before, simply didn't work, the window with the plot didn't open.Is there a way to force macports to install a 64bits version of python?I downloaded and installed the 3.4 and 3.1 myself, but still the computer only sees the version macports installed.Thank you!Regards, B?rbara From shouqiang1989 at sina.com Fri Feb 27 04:19:51 2015 From: shouqiang1989 at sina.com (shouqiang1989 at sina.com) Date: Fri, 27 Feb 2015 11:19:51 +0800 Subject: [Tutor] Remove a blank row of a Table Message-ID: <20150227031951.0B004C34F22@webmail.sinamail.sina.com.cn> Hello, everybody, I came accross a question a few days ago. I wrote a Python script to copy something to a table in a word file. For some reaons, there are some blank rows. And I want to remove the blank rows. I tried many ways, but all didn't work. Below is the code. The code in blue is to remove the blank row. import codecs import os import textwrap import win32com,string,shutil from win32com.client import Dispatch,constants def ReportPackage(reportName, reportApi, package=None): desfile='C:\\Daten\\TestCASE5\\Model_hill.doc' w = win32com.client.Dispatch('Word.Application') w.Visible = 1 os.path.join(reportApi.GetReportDir(), reportName) fd = w.Documents.Open(desfile) #open the model file info = reportApi.GetInfo() if package is None: package = reportApi.GetMainPackage() result = info.GetResult() execTime = info.GetExecutionTime() pkgName =package.GetName() else: result = package.GetResult() execTime = package.GetTime() i=1 s=0 f=0 e=0 form = fd.Tables[6] form.Rows.Add() form.Rows.Last.Cells[2].Range.InsertAfter("%(pkgName)s" % {'pkgName': pkgName}) form.Rows.Last.Cells[3].Range.InsertAfter("%(executionTime)s" %{'executionTime': execTime}) form.Rows.Add() lines = form.Rows.Last() lines.Cells[0].Range.InsertAfter("Num") lines.Cells[1].Range.InsertAfter("Time") lines.Cells[2].Range.InsertAfter("Comment") lines.Cells[3].Range.InsertAfter("Result") testCase = package.GetTestCase(excludeSubPackages=reportApi.IsSet("hideSubPackages", "True")) for reportItem in testCase.IterTestSteps(): try: if reportItem.PResult == "NONE" : #constants.RESULT_NONE: strResult = '' else : strResult = reportItem.PResult lNam = textwrap.wrap(reportItem.PName) maxLines = len(lNam) fd.Tables[6].Rows.Add() if strResult == 'SUCCESS': fd.Tables[6].Rows.Last.Cells[3].Shading.BackgroundPatternColorIndex=4 s=s+1 elif strResult == 'FAILED': fd.Tables[6].Rows.Last.Cells[3].Shading.BackgroundPatternColor=250 f=f+1 elif strResult == 'ERROR' : fd.Tables[6].Rows.Last.Cells[3].Shading.BackgroundPatternColor=180 e=e+1 if strResult == 'SUCCESS' or strResult == 'FAILED' or strResult == 'ERROR' : fd.Tables[6].Rows.Last.Cells[3].Range.InsertAfter(strResult) fd.Tables[6].Rows.Last.Cells[2].Range.InsertAfter(lNam[0]) fd.Tables[6].Rows.Last.Cells[1].Range.InsertAfter(("%.3f" % reportItem.PTimestamp)) fd.Tables[6].Rows.Last.Cells[0].Range.InsertAfter(i) i=i+1 else : pass for idx in xrange (1,maxLines) : if fd.Tables[6].Rows[idx].Cells[1] == None : fd.Tables[6].Rows[idx].Remove() else : pass except : break s=str(s) f=str(f) e=str(e) fd.Tables[6].Rows.Add() fd.Tables[6].Rows.Last.Cells[2].Range.InsertAfter("s="+s+' ') fd.Tables[6].Rows.Last.Cells[2].Range.InsertAfter("f="+f+' ') fd.Tables[6].Rows.Last.Cells[2].Range.InsertAfter("e="+e+' ') #insert the results in table 7 fd.Save.im_self fd.Close() def _ReportProjectElement(): return() def ReportProject(): return() Thanks in advance. -------------------------------- Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Fri Feb 27 10:45:52 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Feb 2015 09:45:52 +0000 Subject: [Tutor] Help with python in MAC OS 10.6 In-Reply-To: <199673520.1431247.1425003416015.JavaMail.yahoo@mail.yahoo.com> References: <199673520.1431247.1425003416015.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 27/02/15 02:16, Barbara Heliodora G. Rodrigues wrote: > Dear tutor, > I'd like to ask for help with an issue I have with python. My MAC is with OS 10-6.8, I'm not a MacOs expert but I know MacOS uses Python in some of its tools so do not mess with the standard version, you might break something. > I can't install any new software that uses python, What the OS uses as Python should not necessarily impact what you use as Python. Usually its just a case of changing a link or creating an alias or environment variable. At the worst case you can edit the shebang line of your scripts. > I tried to use some plot (matplotlib) routines that were working fine before, How are you running these scripts? Do you just double click an icon or do you use a commandline? If the latter what do you type? If the former somebody with a modern Mac will need to advise. > Is there a way to force macports to install a 64bits version of python? Probably, but I don't know macports. > I downloaded and installed the 3.4 and 3.1 myself, but still the > computer only sees the version macports installed. Have you tried calling python3 instead of just python? That should find your Python 3.X version. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Fri Feb 27 12:03:12 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Feb 2015 11:03:12 +0000 Subject: [Tutor] Remove a blank row of a Table In-Reply-To: <20150227031951.0B004C34F22@webmail.sinamail.sina.com.cn> References: <20150227031951.0B004C34F22@webmail.sinamail.sina.com.cn> Message-ID: On 27/02/15 03:19, shouqiang1989 at sina.com wrote: > Hello, everybody, I came accross a question a few days > ago. I wrote a Python script to copy something to a table in a word > file. For some reaons, there are some blank rows. And I want to remove > the blank rows. I tried many ways, but all didn't work. Below is the > code. The code in blue is to remove the blank row. First thing is that there is no blue on a plain text email, so we can't see which lines. You need to add a comment to alert us. > import codecs > import os > import textwrap > import win32com,string,shutil > from win32com.client import Dispatch,constants Most of your code seems to be based on calls to the win32com library and the Word object model functions. Most of us on this list don't work with that regularly (if at all) so you probably will get a better response on the PyWin32 support forum. There is a Win32 mailing list too, on Gmane its gmane.comp.python.windows > def ReportPackage(reportName, reportApi, package=None): > desfile='C:\\Daten\\TestCASE5\\Model_hill.doc' As a general style point its usually better to make filenames a parameter of the function. Otherwise the function is of limited reuse potential as it can only ever work on one file. Its not clear what reportApi is but you seem to call lots of functions on it. Is it a Win32 thing or another python module? > w = win32com.client.Dispatch('Word.Application') > w.Visible = 1 > os.path.join(reportApi.GetReportDir(), reportName) You call os.path.join here but do not store the result. It does nothing. > fd = w.Documents.Open(desfile) #open the model file info = reportApi.GetInfo() I assume the info assignment is supposed to be inline? > if package is None: > package = reportApi.GetMainPackage() > result = info.GetResult() > execTime = info.GetExecutionTime() > pkgName =package.GetName() > else: > result = package.GetResult() > execTime = package.GetTime() No idea what that did but it seems irrelevant to most of what follows. > i=1 > s=0 > f=0 > e=0 No idea what these are supposed to be for. Its much better to use meaningful names. The cost of typing a few extra letters is a small price to pay for the extra readability. > > form = fd.Tables[6] I'm guessing this is a hard coded dependency on the structure of your document which we can't see. I'll just assume that its correct. > form.Rows.Add() > form.Rows.Last.Cells[2].Range.InsertAfter("%(pkgName)s" % {'pkgName': pkgName}) > form.Rows.Last.Cells[3].Range.InsertAfter("%(executionTime)s" %{'executionTime': execTime}) > > form.Rows.Add() > lines = form.Rows.Last() > lines.Cells[0].Range.InsertAfter("Num") > lines.Cells[1].Range.InsertAfter("Time") > lines.Cells[2].Range.InsertAfter("Comment") > lines.Cells[3].Range.InsertAfter("Result") This is all Word object model stuff so I'll just assume its correct. > testCase = package.GetTestCase(excludeSubPackages=reportApi.IsSet("hideSubPackages", "True")) We don;t know what package does nor what reportApi does so again I'll just assume you know what you are doing here. And I don't know what testCase might be either, nor what the reportItem objects are. So I'll stop here. Can you see the pattern? So much of what you are doing relies on external libraries that are not part of Python that it's almost impossible for us to comment on your code. You really need to find somebody familiar with the Word API rather than a Python expert. You may be lucky and find one here, but a dedicated forum is a much better bet. We can comment on some finer points of your Python style but that's probably not going to solve your real issue. > except : > break But this one I can't let rest. By doing this you are hiding all attempts by Python to alert you to problems. If anything goes wrong in the code above Python throws an exception which you just throw away. Python may be telling you the solution to your problem but you are ignoring it. Always catch specific exceptions, but only if you know how to handle them. Otherwise let Python help you by telling you what's gone wrong. > def _ReportProjectElement(): > return() The () after return is misleading, lose them. It makes it look like you are calling a function called return, which you aren't. Its usually better when writing stubs to return a hard coded example of valid output. If the function doesn't return anything its more obvious if you use pass rather than return. (IMHO at least :-) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From rishiglorious at gmail.com Fri Feb 27 13:21:29 2015 From: rishiglorious at gmail.com (Rishi Ganesh V) Date: Fri, 27 Feb 2015 17:51:29 +0530 Subject: [Tutor] Tutor Digest, Vol 132, Issue 57 In-Reply-To: <1425035540017.26127006@boxbe> References: <1425035540017.26127006@boxbe> Message-ID: how to pass the argument in the command line i have the input file as csv and output file as txt both input file and output file i am passing the value to an argument like inputfile=sys.argv[1] , output file=sys.argv[2] convert(inputfile,outputfile) how to pass the value in argument On Fri, Feb 27, 2015 at 4:30 PM, wrote: > [image: Boxbe] This message is eligible > for Automatic Cleanup! (tutor-request at python.org) Add cleanup rule > > | More info > > > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Gaussian process regression (Steven D'Aprano) > 2. Help with python in MAC OS 10.6 (Barbara Heliodora G. Rodrigues) > 3. Remove a blank row of a Table (shouqiang1989 at sina.com) > 4. Re: Help with python in MAC OS 10.6 (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 27 Feb 2015 12:57:00 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Gaussian process regression > Message-ID: <20150227015659.GY7655 at ando.pearwood.info> > Content-Type: text/plain; charset=us-ascii > > On Fri, Feb 27, 2015 at 03:04:25AM +0900, Huijae wrote: > > > Hi, I am trying to use Gaussian process regression for Near Infrared > > spectra. I have reference data(spectra), concentrations of reference > > data and sample data, and I am trying to predict concentrations of > > sample data. Here is my code. from sklearn.gaussian_process import > > GaussianProcess gp = GaussianProcess() gp.fit(reference, > > concentration) concentration_pred = gp.predict(sample) The results > > always gave me the same concentration even though I used different > > sample data. When I used some parts of reference data as sample data, > > it predicted concentration well. But whenever I use different data > > than reference data, it always gave me the same concentration. Can I > > get some help with this problem? What am I doing wrong? I would > > appreciate any help. Thanks, Jay > > Your mail program has mangled your code and mixed up the layout. I > suggest turning off all formatting, "Rich Text" or HTML mail, since that > usually destroys the layout of code. > > I'm going to try to guess your code's layout: > > from sklearn.gaussian_process import GaussianProcess > gp = GaussianProcess() > gp.fit(reference, concentration) > concentration_pred = gp.predict(sample) > > > This is not enough for us to give any meaningful advice. What is > "sklearn"? What are "reference", "concentration", "sample"? We'd need > to see actual data, and know what GaussianProcess does, to help. > > > > The results always gave me the same concentration > > even though I used different sample data. > > *Exactly* the same? To 17 decimal places? Or just close to the same? > > Perhaps the different samples give the same result because they are > samples from the same population. > > > > When I used some parts of > > reference data as sample data, it predicted concentration well. But > > whenever I use different data than reference data, it always gave me > > the same concentration. > > You may need to ask people who know more about GaussianProcess and how > it works. > > > > -- > Steve > > > ------------------------------ > > Message: 2 > Date: Fri, 27 Feb 2015 02:16:56 +0000 (UTC) > From: "Barbara Heliodora G. Rodrigues" > To: "tutor at python.org" > Subject: [Tutor] Help with python in MAC OS 10.6 > Message-ID: > <199673520.1431247.1425003416015.JavaMail.yahoo at mail.yahoo.com> > Content-Type: text/plain; charset=UTF-8 > > Dear tutor, > I'd like to ask for help with an issue I have with python. My MAC is with > OS 10-6.8, darwin kernel, 64 bits. For some reason I updated macports and > it automatically updated python to 2.7 with a 32 bits library, and it is > giving me lots of trouble. I can't install any new software that uses > python, and recently I tried to use some plot (matplotlib) routines that > were working fine before, simply didn't work, the window with the plot > didn't open.Is there a way to force macports to install a 64bits version of > python?I downloaded and installed the 3.4 and 3.1 myself, but still the > computer only sees the version macports installed.Thank you!Regards, > B?rbara > > ------------------------------ > > Message: 3 > Date: Fri, 27 Feb 2015 11:19:51 +0800 > From: > To: "tutor" > Subject: [Tutor] Remove a blank row of a Table > Message-ID: <20150227031951.0B004C34F22 at webmail.sinamail.sina.com.cn> > Content-Type: text/plain; charset=GBK > > Hello, everybody, I came accross a question a few days > ago. I wrote a Python script to copy something to a table in a word > file. For some reaons, there are some blank rows. And I want to remove > the blank rows. I tried many ways, but all didn't work. Below is the > code. The code in blue is to remove the blank row. > > > import codecs > import os > import textwrap > import win32com,string,shutil > from win32com.client import Dispatch,constants > def ReportPackage(reportName, reportApi, package=None): > desfile='C:\\Daten\\TestCASE5\\Model_hill.doc' > w = win32com.client.Dispatch('Word.Application') > w.Visible = 1 > os.path.join(reportApi.GetReportDir(), reportName) > fd = w.Documents.Open(desfile) #open the model file > info = reportApi.GetInfo() > if package is None: > package = reportApi.GetMainPackage() > result = info.GetResult() > execTime = info.GetExecutionTime() > pkgName =package.GetName() > else: > result = package.GetResult() > execTime = package.GetTime() > i=1 > s=0 > f=0 > e=0 > > form = fd.Tables[6] > form.Rows.Add() > > > form.Rows.Last.Cells[2].Range.InsertAfter("%(pkgName)s" % {'pkgName': > pkgName}) > form.Rows.Last.Cells[3].Range.InsertAfter("%(executionTime)s" > %{'executionTime': execTime}) > > form.Rows.Add() > > lines = form.Rows.Last() > lines.Cells[0].Range.InsertAfter("Num") > lines.Cells[1].Range.InsertAfter("Time") > lines.Cells[2].Range.InsertAfter("Comment") > lines.Cells[3].Range.InsertAfter("Result") > > testCase = > package.GetTestCase(excludeSubPackages=reportApi.IsSet("hideSubPackages", > "True")) > > for reportItem in testCase.IterTestSteps(): > try: > > > if reportItem.PResult == "NONE" : #constants.RESULT_NONE: > strResult = '' > else : > strResult = reportItem.PResult > > > lNam = textwrap.wrap(reportItem.PName) > maxLines = len(lNam) > > > fd.Tables[6].Rows.Add() > > if strResult == 'SUCCESS': > > fd.Tables[6].Rows.Last.Cells[3].Shading.BackgroundPatternColorIndex=4 > s=s+1 > elif strResult == 'FAILED': > > fd.Tables[6].Rows.Last.Cells[3].Shading.BackgroundPatternColor=250 > f=f+1 > elif strResult == 'ERROR' : > > fd.Tables[6].Rows.Last.Cells[3].Shading.BackgroundPatternColor=180 > e=e+1 > > > if strResult == 'SUCCESS' or strResult == 'FAILED' or > strResult == 'ERROR' : > > fd.Tables[6].Rows.Last.Cells[3].Range.InsertAfter(strResult) > fd.Tables[6].Rows.Last.Cells[2].Range.InsertAfter(lNam[0]) > fd.Tables[6].Rows.Last.Cells[1].Range.InsertAfter(("%.3f" > % reportItem.PTimestamp)) > fd.Tables[6].Rows.Last.Cells[0].Range.InsertAfter(i) > i=i+1 > else : > pass > > > for idx in xrange (1,maxLines) : > if fd.Tables[6].Rows[idx].Cells[1] == None : > fd.Tables[6].Rows[idx].Remove() > else : > pass > except : > break > > s=str(s) > f=str(f) > e=str(e) > fd.Tables[6].Rows.Add() > fd.Tables[6].Rows.Last.Cells[2].Range.InsertAfter("s="+s+' ') > fd.Tables[6].Rows.Last.Cells[2].Range.InsertAfter("f="+f+' ') > fd.Tables[6].Rows.Last.Cells[2].Range.InsertAfter("e="+e+' ') > #insert the results in table 7 > > > > fd.Save.im_self > fd.Close() > > > > > def _ReportProjectElement(): > return() > > > > def ReportProject(): > return() > > > Thanks in advance. > > > > -------------------------------- > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > ------------------------------ > > Message: 4 > Date: Fri, 27 Feb 2015 09:45:52 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Help with python in MAC OS 10.6 > Message-ID: > Content-Type: text/plain; charset=utf-8; format=flowed > > On 27/02/15 02:16, Barbara Heliodora G. Rodrigues wrote: > > Dear tutor, > > I'd like to ask for help with an issue I have with python. My MAC is > with OS 10-6.8, > > I'm not a MacOs expert but I know MacOS uses Python in some of its tools > so do not mess with the standard version, you might break something. > > > I can't install any new software that uses python, > > What the OS uses as Python should not necessarily impact what you use as > Python. Usually its just a case of changing a link or creating an alias > or environment variable. > > At the worst case you can edit the shebang line of your scripts. > > > I tried to use some plot (matplotlib) routines that were working fine > before, > > How are you running these scripts? Do you just double click an icon or > do you use a commandline? If the latter what do you type? > If the former somebody with a modern Mac will need to advise. > > > Is there a way to force macports to install a 64bits version of python? > > Probably, but I don't know macports. > > > I downloaded and installed the 3.4 and 3.1 myself, but still the > > computer only sees the version macports installed. > > Have you tried calling python3 instead of just python? > That should find your Python 3.X version. > > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 132, Issue 57 > ************************************** > > From rishiglorious at gmail.com Fri Feb 27 13:31:13 2015 From: rishiglorious at gmail.com (Rishi Ganesh V) Date: Fri, 27 Feb 2015 18:01:13 +0530 Subject: [Tutor] Tutor Digest, Vol 132, Issue 57 In-Reply-To: References: <1425035540017.26127006@boxbe> Message-ID: Dear tutor, how to pass the argument in the command line i have the input file as csv and output file as txt both input file and output file i am passing the value to an argument in the command line in the script it is like def convert(inputfile, outputfile): reader = csv.reader(open(inputfile, "rb")) file = open(outputfile, 'w+') ...... inputfile=sys.argv[1] , output file=sys.argv[2] convert(inputfile,outputfile) 1.how to pass the value to an argument in the command line 2.if i compiled i am getting an following error Value error: too many values to unpack So how to avoid these error... On Fri, Feb 27, 2015 at 5:51 PM, Rishi Ganesh V wrote: > how to pass the argument in the command line > i have the input file as csv and output file as txt > both input file and output file i am passing the value to an argument > > like > inputfile=sys.argv[1] , output file=sys.argv[2] > > convert(inputfile,outputfile) > > > how to pass the value in argument > > On Fri, Feb 27, 2015 at 4:30 PM, wrote: > >> [image: Boxbe] This message is >> eligible for Automatic Cleanup! (tutor-request at python.org) Add cleanup >> rule >> >> | More info >> >> >> Send Tutor mailing list submissions to >> tutor at python.org >> >> To subscribe or unsubscribe via the World Wide Web, visit >> https://mail.python.org/mailman/listinfo/tutor >> or, via email, send a message with subject or body 'help' to >> tutor-request at python.org >> >> You can reach the person managing the list at >> tutor-owner at python.org >> >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Tutor digest..." >> >> >> Today's Topics: >> >> 1. Re: Gaussian process regression (Steven D'Aprano) >> 2. Help with python in MAC OS 10.6 (Barbara Heliodora G. Rodrigues) >> 3. Remove a blank row of a Table (shouqiang1989 at sina.com) >> 4. Re: Help with python in MAC OS 10.6 (Alan Gauld) >> >> >> ---------------------------------------------------------------------- >> >> Message: 1 >> Date: Fri, 27 Feb 2015 12:57:00 +1100 >> From: Steven D'Aprano >> To: tutor at python.org >> Subject: Re: [Tutor] Gaussian process regression >> Message-ID: <20150227015659.GY7655 at ando.pearwood.info> >> Content-Type: text/plain; charset=us-ascii >> >> On Fri, Feb 27, 2015 at 03:04:25AM +0900, Huijae wrote: >> >> > Hi, I am trying to use Gaussian process regression for Near Infrared >> > spectra. I have reference data(spectra), concentrations of reference >> > data and sample data, and I am trying to predict concentrations of >> > sample data. Here is my code. from sklearn.gaussian_process import >> > GaussianProcess gp = GaussianProcess() gp.fit(reference, >> > concentration) concentration_pred = gp.predict(sample) The results >> > always gave me the same concentration even though I used different >> > sample data. When I used some parts of reference data as sample data, >> > it predicted concentration well. But whenever I use different data >> > than reference data, it always gave me the same concentration. Can I >> > get some help with this problem? What am I doing wrong? I would >> > appreciate any help. Thanks, Jay >> >> Your mail program has mangled your code and mixed up the layout. I >> suggest turning off all formatting, "Rich Text" or HTML mail, since that >> usually destroys the layout of code. >> >> I'm going to try to guess your code's layout: >> >> from sklearn.gaussian_process import GaussianProcess >> gp = GaussianProcess() >> gp.fit(reference, concentration) >> concentration_pred = gp.predict(sample) >> >> >> This is not enough for us to give any meaningful advice. What is >> "sklearn"? What are "reference", "concentration", "sample"? We'd need >> to see actual data, and know what GaussianProcess does, to help. >> >> >> > The results always gave me the same concentration >> > even though I used different sample data. >> >> *Exactly* the same? To 17 decimal places? Or just close to the same? >> >> Perhaps the different samples give the same result because they are >> samples from the same population. >> >> >> > When I used some parts of >> > reference data as sample data, it predicted concentration well. But >> > whenever I use different data than reference data, it always gave me >> > the same concentration. >> >> You may need to ask people who know more about GaussianProcess and how >> it works. >> >> >> >> -- >> Steve >> >> >> ------------------------------ >> >> Message: 2 >> Date: Fri, 27 Feb 2015 02:16:56 +0000 (UTC) >> From: "Barbara Heliodora G. Rodrigues" >> To: "tutor at python.org" >> Subject: [Tutor] Help with python in MAC OS 10.6 >> Message-ID: >> <199673520.1431247.1425003416015.JavaMail.yahoo at mail.yahoo.com> >> Content-Type: text/plain; charset=UTF-8 >> >> Dear tutor, >> I'd like to ask for help with an issue I have with python. My MAC is with >> OS 10-6.8, darwin kernel, 64 bits. For some reason I updated macports and >> it automatically updated python to 2.7 with a 32 bits library, and it is >> giving me lots of trouble. I can't install any new software that uses >> python, and recently I tried to use some plot (matplotlib) routines that >> were working fine before, simply didn't work, the window with the plot >> didn't open.Is there a way to force macports to install a 64bits version of >> python?I downloaded and installed the 3.4 and 3.1 myself, but still the >> computer only sees the version macports installed.Thank you!Regards, >> B?rbara >> >> ------------------------------ >> >> Message: 3 >> Date: Fri, 27 Feb 2015 11:19:51 +0800 >> From: >> To: "tutor" >> Subject: [Tutor] Remove a blank row of a Table >> Message-ID: <20150227031951.0B004C34F22 at webmail.sinamail.sina.com.cn> >> Content-Type: text/plain; charset=GBK >> >> Hello, everybody, I came accross a question a few days >> ago. I wrote a Python script to copy something to a table in a word >> file. For some reaons, there are some blank rows. And I want to remove >> the blank rows. I tried many ways, but all didn't work. Below is the >> code. The code in blue is to remove the blank row. >> >> >> import codecs >> import os >> import textwrap >> import win32com,string,shutil >> from win32com.client import Dispatch,constants >> def ReportPackage(reportName, reportApi, package=None): >> desfile='C:\\Daten\\TestCASE5\\Model_hill.doc' >> w = win32com.client.Dispatch('Word.Application') >> w.Visible = 1 >> os.path.join(reportApi.GetReportDir(), reportName) >> fd = w.Documents.Open(desfile) #open the model file >> info = reportApi.GetInfo() >> if package is None: >> package = reportApi.GetMainPackage() >> result = info.GetResult() >> execTime = info.GetExecutionTime() >> pkgName =package.GetName() >> else: >> result = package.GetResult() >> execTime = package.GetTime() >> i=1 >> s=0 >> f=0 >> e=0 >> >> form = fd.Tables[6] >> form.Rows.Add() >> >> >> form.Rows.Last.Cells[2].Range.InsertAfter("%(pkgName)s" % >> {'pkgName': pkgName}) >> form.Rows.Last.Cells[3].Range.InsertAfter("%(executionTime)s" >> %{'executionTime': execTime}) >> >> form.Rows.Add() >> >> lines = form.Rows.Last() >> lines.Cells[0].Range.InsertAfter("Num") >> lines.Cells[1].Range.InsertAfter("Time") >> lines.Cells[2].Range.InsertAfter("Comment") >> lines.Cells[3].Range.InsertAfter("Result") >> >> testCase = >> package.GetTestCase(excludeSubPackages=reportApi.IsSet("hideSubPackages", >> "True")) >> >> for reportItem in testCase.IterTestSteps(): >> try: >> >> >> if reportItem.PResult == "NONE" : #constants.RESULT_NONE: >> strResult = '' >> else : >> strResult = reportItem.PResult >> >> >> lNam = textwrap.wrap(reportItem.PName) >> maxLines = len(lNam) >> >> >> fd.Tables[6].Rows.Add() >> >> if strResult == 'SUCCESS': >> >> fd.Tables[6].Rows.Last.Cells[3].Shading.BackgroundPatternColorIndex=4 >> s=s+1 >> elif strResult == 'FAILED': >> >> fd.Tables[6].Rows.Last.Cells[3].Shading.BackgroundPatternColor=250 >> f=f+1 >> elif strResult == 'ERROR' : >> >> fd.Tables[6].Rows.Last.Cells[3].Shading.BackgroundPatternColor=180 >> e=e+1 >> >> >> if strResult == 'SUCCESS' or strResult == 'FAILED' or >> strResult == 'ERROR' : >> >> fd.Tables[6].Rows.Last.Cells[3].Range.InsertAfter(strResult) >> >> fd.Tables[6].Rows.Last.Cells[2].Range.InsertAfter(lNam[0]) >> >> fd.Tables[6].Rows.Last.Cells[1].Range.InsertAfter(("%.3f" % >> reportItem.PTimestamp)) >> fd.Tables[6].Rows.Last.Cells[0].Range.InsertAfter(i) >> i=i+1 >> else : >> pass >> >> >> for idx in xrange (1,maxLines) : >> if fd.Tables[6].Rows[idx].Cells[1] == None : >> fd.Tables[6].Rows[idx].Remove() >> else : >> pass >> except : >> break >> >> s=str(s) >> f=str(f) >> e=str(e) >> fd.Tables[6].Rows.Add() >> fd.Tables[6].Rows.Last.Cells[2].Range.InsertAfter("s="+s+' ') >> fd.Tables[6].Rows.Last.Cells[2].Range.InsertAfter("f="+f+' ') >> fd.Tables[6].Rows.Last.Cells[2].Range.InsertAfter("e="+e+' ') >> #insert the results in table 7 >> >> >> >> fd.Save.im_self >> fd.Close() >> >> >> >> >> def _ReportProjectElement(): >> return() >> >> >> >> def ReportProject(): >> return() >> >> >> Thanks in advance. >> >> >> >> -------------------------------- >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> >> ------------------------------ >> >> Message: 4 >> Date: Fri, 27 Feb 2015 09:45:52 +0000 >> From: Alan Gauld >> To: tutor at python.org >> Subject: Re: [Tutor] Help with python in MAC OS 10.6 >> Message-ID: >> Content-Type: text/plain; charset=utf-8; format=flowed >> >> On 27/02/15 02:16, Barbara Heliodora G. Rodrigues wrote: >> > Dear tutor, >> > I'd like to ask for help with an issue I have with python. My MAC is >> with OS 10-6.8, >> >> I'm not a MacOs expert but I know MacOS uses Python in some of its tools >> so do not mess with the standard version, you might break something. >> >> > I can't install any new software that uses python, >> >> What the OS uses as Python should not necessarily impact what you use as >> Python. Usually its just a case of changing a link or creating an alias >> or environment variable. >> >> At the worst case you can edit the shebang line of your scripts. >> >> > I tried to use some plot (matplotlib) routines that were working fine >> before, >> >> How are you running these scripts? Do you just double click an icon or >> do you use a commandline? If the latter what do you type? >> If the former somebody with a modern Mac will need to advise. >> >> > Is there a way to force macports to install a 64bits version of python? >> >> Probably, but I don't know macports. >> >> > I downloaded and installed the 3.4 and 3.1 myself, but still the >> > computer only sees the version macports installed. >> >> Have you tried calling python3 instead of just python? >> That should find your Python 3.X version. >> >> >> HTH >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> http://www.amazon.com/author/alan_gauld >> Follow my photo-blog on Flickr at: >> http://www.flickr.com/photos/alangauldphotos >> >> >> >> >> ------------------------------ >> >> Subject: Digest Footer >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> https://mail.python.org/mailman/listinfo/tutor >> >> >> ------------------------------ >> >> End of Tutor Digest, Vol 132, Issue 57 >> ************************************** >> >> > From alan.gauld at btinternet.com Fri Feb 27 14:02:14 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Feb 2015 13:02:14 +0000 Subject: [Tutor] CLI args [was:Re: Tutor Digest, Vol 132, Issue 57] In-Reply-To: References: <1425035540017.26127006@boxbe> Message-ID: On 27/02/15 12:31, Rishi Ganesh V wrote: > in the script it is like > def convert(inputfile, outputfile): > reader = csv.reader(open(inputfile, "rb")) > file = open(outputfile, 'w+') > ...... > > > > inputfile=sys.argv[1] , output file=sys.argv[2] > > convert(inputfile,outputfile) The assignments need to be on separate lines not comma separated Then, assuming your script is called myscript.py you call it like $ python myscript.py myinputfile.csv myoutputfile.txt You can find more in the "talking to the User" topic of my tutorial (see below) Please do not send the entire digest, some people pay by the byte. Also change the subject line to something descriptive so it can be found in the archives. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Fri Feb 27 20:56:25 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 27 Feb 2015 11:56:25 -0800 Subject: [Tutor] Use python to parse the subject line of emails, listen for and react to commands In-Reply-To: References: Message-ID: On Thu, Feb 26, 2015 at 4:18 PM, Alan Gauld wrote: > On 26/02/15 20:51, Willie Sims wrote: >> I know py can parse emails, but I cant figure out how to limit to only >> the subject and only if its in that certain format >> and only if its coming from a recognized email address > > OK, Show us what you've tried. That makes it easier for us to see what is > tripping you up. Otherwise we are just guessing. > > All 3 things you ask for can be done but we need a starting point and the > best one is your existing, but faulty, code. Also, if possible, include the sample inputs to the program, and the desired output. Pretend that your program worked perfectly, and show input and imaginary-perfect output. You can feel free to sanitize the input so that it's not revealing anything personally sensitive, of course! Just have something that has enough of the shape of the original input that we can tell what you want to extract. This will allow folks to actually execute your program on the set of data that you are using, and compare what you're getting vs what you want. To compare the difference, the delta, between what we've got and what we want, is a good technique that folks can use to troubleshoot. Generally, it's be great if you can provide a short, self-contained, correct example. (http://sscce.org/) We're not asking this to be pedantic, but to sharpen the problem statement. By making the question self-contained and standalone, you'll make it much easier for folks to *replicate* what you're seeing. Without this, it becomes harder for us to know what problem you're trying to solve, or what difficulties you're encountering. Good luck! From thomas.toker at yahoo.com Fri Feb 27 21:00:29 2015 From: thomas.toker at yahoo.com (Thomas Toker) Date: Fri, 27 Feb 2015 20:00:29 +0000 (UTC) Subject: [Tutor] Variable data to CSV Message-ID: <401478744.1392379.1425067229722.JavaMail.yahoo@mail.yahoo.com> Hey all so I'm new to python(like 2 days ago new) I need to find the device address, usb port, and number of times the error occurs Heres what I have:? import re?import csv import reimport csvf = open("file.txt", "r") #location of log file searchlines = f.readlines() ? ? ? ? ? ? ? ? ? #create list from filef.close()for element in searchlines:? ? ?usbPres = re.search('(USB)',element) ?#pattern to find usb lines? ? ?devAddr = re.search('(address)\s\d+',element) ?#parsing pattern for device address? ? ?port = re.search('(port)\s\d',element) ?#parsing pattern for port? ? ?if usbPres:? ? ? ? ?This is where I get lost because I want to assign the correct port to device address and then count number of time it failed before a new device is inserted into that port. then write it to a CSV **** SAMPLE TEXT *** [11883.112089] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11883.224080] usb 1-7: new high speed USB device using ehci_hcd and address 42 [11883.328151] hub 1-0:1.0: unable to enumerate USB device on port 7 [11904.472097] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11907.440096] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11910.408093] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11913.376095] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11913.616090] usb 1-7: new high speed USB device using ehci_hcd and address 47 [11913.716121] hub 1-0:1.0: unable to enumerate USB device on port 7 [11927.340096] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11930.308096] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11933.276124] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11936.244118] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? [11939.212116] hub 1-0:1.0: Cannot enable port 7. Maybe the USB cable is bad?Any help is much appreciated.Tom From willie14228 at outlook.com Fri Feb 27 20:43:46 2015 From: willie14228 at outlook.com (Willie Sims) Date: Fri, 27 Feb 2015 13:43:46 -0600 Subject: [Tutor] Use python to parse the subject line of emails, listen for and react to commands In-Reply-To: References: Message-ID: I have started working with 2.7 simply because I don't know when the error is caused by me or because of version issues. This is how far I have gotten, I can access and pull emails that only come from a selected email address (OWNER) I have it parsed down to print the subject only And I have it saving the string to a file output.txt And I have it deleting the emails so they don't reread, Now I want to eval the output.txt and act on the keyword that is written,, each key word will be a python script name. So if I sent in the subject line "status" It saves the word as status.py in output.txt, then at the bottom I tried eval output.txt but get the error Traceback (most recent call last): File "C:\Python27\New folder\start.py", line 82, in start_command = eval(open("output.txt").read()) File "", line 1, in NameError: name 'test' is not defined import sys import imaplib import getpass import email import email.header import datetime EMAIL_ACCOUNT = "myemail at gmail.com" EMAIL_FOLDER = "INBOX" OWNER = "willie14228 at outlook.com" COMMAND_FILE = open("output.txt","w") def process_mailbox(M): rv, data = M.search(None, "From", (OWNER)) if rv != 'OK': print "No messages found!" return for num in data[0].split(): rv, data = M.fetch(num, '(RFC822)') if rv != 'OK': print "ERROR getting message", num return msg = email.message_from_string(data[0][1]) decode = email.header.decode_header(msg['Subject'])[0] subject = unicode(decode[0]) print 'Message %s: %s' % (num, subject) COMMAND_FILE.write('%s' % (subject)) COMMAND_FILE.close() #print 'Raw Date:', msg['Date'] M = imaplib.IMAP4_SSL('imap.gmail.com') try: rv, data = M.login(EMAIL_ACCOUNT, getpass.getpass()) except imaplib.IMAP4.error: print "LOGIN FAILED!!! " sys.exit(1) print rv, data rv, mailboxes = M.list() if rv == 'OK': print "Mailboxes:" print mailboxes rv, data = M.select(EMAIL_FOLDER) if rv == 'OK': print "Processing mailbox...\n" process_mailbox(M) M.select('INBOX') # select all trash M.store("1:*", '+FLAGS', '\\Deleted') #Flag all Trash as Deleted M.expunge() M.close() else: print "ERROR: Unable to open mailbox ", rv M.logout() start_command = eval(open("output.txt").read()) Traceback (most recent call last): File "C:\Python27\New folder\start.py", line 82, in start_command = eval(open("output.txt").read()) File "", line 1, in NameError: name 'test' is not defined -----Original Message----- From: Tutor [mailto:tutor-bounces+willie14228=outlook.com at python.org] On Behalf Of Alan Gauld Sent: Thursday, February 26, 2015 6:18 PM To: tutor at python.org Subject: Re: [Tutor] Use python to parse the subject line of emails, listen for and react to commands On 26/02/15 20:51, Willie Sims wrote: > I know py can parse emails, but I cant figure out how to limit to > only > the subject and only if its in that certain format > and only if its coming from a recognized email address OK, Show us what you've tried. That makes it easier for us to see what is tripping you up. Otherwise we are just guessing. All 3 things you ask for can be done but we need a starting point and the best one is your existing, but faulty, code. > and since I'm using 3.4 it seems all the other kind of examples don't > work A lot of old examples on the web will be for Python v32 and there are significant differences to v3. However, Python v3 has not lost any important functionality so whatever worked in v2 can be made to work in v3. Again we just need a clue as to what you are trying to do. (show us your code - and any error messages and tell us your OS too) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sat Feb 28 00:16:12 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Feb 2015 23:16:12 +0000 Subject: [Tutor] Variable data to CSV In-Reply-To: <401478744.1392379.1425067229722.JavaMail.yahoo@mail.yahoo.com> References: <401478744.1392379.1425067229722.JavaMail.yahoo@mail.yahoo.com> Message-ID: On 27/02/15 20:00, Thomas Toker wrote: > Hey all so I'm new to python(like 2 days ago new) Welcome. However it will help if: 1) You always post in plain text. As you see below HTML code gets zapped in email. > I need to find the device address, usb port, and number of times the error occurs OK, Assume we don;t know anything about USB Explain how that relates tom your sample data below. Which columns do you want to extract/process? Your data is not consistent in structure so using csv is probably more trouble than its worth. Look at using split() based on both spaces and colons. > import re import csv > import reimport csvf = open("file.txt", "r") #location of log file > searchlines = f.readlines() #create list from filef.close()for element in searchlines: usbPres = re.search('(USB)',element) #pattern to find usb lines devAddr = re.search('(address)\s\d+',element) #parsing pattern for device address port = re.search('(port)\s\d',element) #parsing pattern for port if usbPres: This is where I get lost because I want to assign the correct port to device address and then count number of time it failed before a new device is inserted into that port. then write it to a CSV But the code is too messed up to read easily so please repost in plain text. > > **** SAMPLE TEXT *** > [11883.112089] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? > [11883.224080] usb 1-7: new high speed USB device using ehci_hcd and address 42 > [11883.328151] hub 1-0:1.0: unable to enumerate USB device on port 7 > [11904.472097] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? > [11907.440096] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? > [11910.408093] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? > [11913.376095] hub 1-0:1.0: Cannot enable port 3. Maybe the USB cable is bad? HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From cs at zip.com.au Fri Feb 27 23:58:42 2015 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 28 Feb 2015 09:58:42 +1100 Subject: [Tutor] Help with python in MAC OS 10.6 In-Reply-To: <199673520.1431247.1425003416015.JavaMail.yahoo@mail.yahoo.com> References: <199673520.1431247.1425003416015.JavaMail.yahoo@mail.yahoo.com> Message-ID: <20150227225842.GA44759@cskk.homeip.net> On 27Feb2015 02:16, Barbara Heliodora G. Rodrigues wrote: >I'd like to ask for help with an issue I have with python. My MAC is with OS 10-6.8, darwin kernel, 64 bits. For some reason I updated macports and it automatically updated python to 2.7 with a 32 bits library, and it is giving me lots of trouble. I can't install any new software that uses python, and recently I tried to use some plot (matplotlib) routines that were working fine before, simply didn't work, the window with the plot didn't open.Is there a way to force macports to install a 64bits version of python? Since I use MacPorts and Alan doesn't I'll chip in... First up, you're talking about the MacPorts pythn (in /opt/local) not the system Python (in /usr). This page: http://stackoverflow.com/questions/2111283/how-to-build-64-bit-python-on-os-x-10-6-only-64-bit-no-universal-nonsense seems to offer useful advice on getting MacPorts to install your preferred variant on Python. Next, re this: >I downloaded and installed the 3.4 and 3.1 myself, but still the computer only sees the version macports installed. You need to clarify what this statement means, probably with examples of how you are invoking your python programs, and the output of "which python". Your Mac should (now) have multiple Pythons installed: /usr/bin/python Supplied with MacOSX, the system Python. Probably 64-bit python. As the cited web page above says, run: file /usr/bin/python to see what architecture it is. You can do that for any of the other executables too to check how they were built. /opt/local/bin/python The MacPorts python (python 2 by default). It should like you need to reinstall this with the right "variants" settings to get it to be 64-bit. Your personally built Pythons. Regarding the last, please outline what options you used to build these. It is very important to build/install with a suitable --prefix Configure option to put them in the right place: not a specific place, but a place _not_ conflicting with the OSX or MacPorts pythons, for example /usr/local/python-2.7.7 (adjust to suit). It is normal to add some symlinks in /usr/local/bin for "python", "python2" etc pointing at your preferred executables. Next, _how_ are you installing extra packages like matplotlib etc? I would advocate using MacPorts to install these if available; that leaves the arrangements in the hands of MacPorts and keeps things simple for you. Otherwise, I would next suggest learning to use virtualenv to make a specific python "environment" for you work. This is easier than it sounds. The virtualenv command prepares a direct of your choice (eg $HOME/venv-2.7.7, to invent a name) which contains "python" and "pip" executables in the "bin" subdirectory which are crafted to automatically install and use packages entirely within the virtualenv directory, avoiding conflicts with other systems like OSX or MacPorts. This is great for experimentation of maintaining special setups of your own. You can base the virtualenv of any of the installed Pythons (OSX, MacPorts, whatever), to get the installed libraries for free. Please respond with further information and we can proceed from there. Cheers, Cameron Simpson To have no errors Would be life without meaning No struggle, no joy - Haiku Error Messages http://www.salonmagazine.com/21st/chal/1998/02/10chal2.html From alan.gauld at btinternet.com Sat Feb 28 00:26:39 2015 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Feb 2015 23:26:39 +0000 Subject: [Tutor] Use python to parse the subject line of emails, listen for and react to commands In-Reply-To: References: Message-ID: On 27/02/15 19:43, Willie Sims wrote: > I have started working with 2.7 simply because I don't know when the error > is caused by me or because of version issues. > This is how far I have gotten, > I can access and pull emails that only come from a selected email address > (OWNER) > I have it parsed down to print the subject only > And I have it saving the string to a file output.txt > And I have it deleting the emails so they don't reread, > Now I want to eval the output.txt and act on the keyword that is written,, That's nearly always a bad idea. eval is a big security risk, especially if applied to external input. And as you've discovered, it makes debugging into a bit of a nightmare. > eval output.txt but get the error > > Traceback (most recent call last): > File "C:\Python27\New folder\start.py", line 82, in > start_command = eval(open("output.txt").read()) > File "", line 1, in > NameError: name 'test' is not defined > That's probably because a line in output.txt contains the word test which is not known to python. Without seeing output.txt it's impossible to be more specific. > import sys > import imaplib > import getpass > import email > import email.header > import datetime > > EMAIL_ACCOUNT = "myemail at gmail.com" > EMAIL_FOLDER = "INBOX" > OWNER = "willie14228 at outlook.com" > COMMAND_FILE = open("output.txt","w") > > def process_mailbox(M): > rv, data = M.search(None, "From", (OWNER)) > if rv != 'OK': > print "No messages found!" > return > for num in data[0].split(): > rv, data = M.fetch(num, '(RFC822)') > if rv != 'OK': > print "ERROR getting message", num > return > msg = email.message_from_string(data[0][1]) > decode = email.header.decode_header(msg['Subject'])[0] > subject = unicode(decode[0]) > print 'Message %s: %s' % (num, subject) > COMMAND_FILE.write('%s' % (subject)) > COMMAND_FILE.close() > #print 'Raw Date:', msg['Date'] I assume this is where the function is supposed to end? Note that you are throwing away all the data you find. It is lost when the function exits. Are the print statements and file output sufficient? Also note you have the file closure inside the loop. That means you only get the first item in the file before you close it I'm not clear what the loop is doing so it might be OK. > M = imaplib.IMAP4_SSL('imap.gmail.com') > try: > rv, data = M.login(EMAIL_ACCOUNT, getpass.getpass()) > except imaplib.IMAP4.error: > print "LOGIN FAILED!!! " > sys.exit(1) > print rv, data > rv, mailboxes = M.list() > if rv == 'OK': > print "Mailboxes:" > print mailboxes > rv, data = M.select(EMAIL_FOLDER) > if rv == 'OK': > print "Processing mailbox...\n" > process_mailbox(M) > M.select('INBOX') # select all trash > M.store("1:*", '+FLAGS', '\\Deleted') #Flag all Trash as Deleted > M.expunge() > M.close() > else: > print "ERROR: Unable to open mailbox ", rv > > M.logout() > start_command = eval(open("output.txt").read()) > > > Traceback (most recent call last): > File "C:\Python27\New folder\start.py", line 82, in > start_command = eval(open("output.txt").read()) > File "", line 1, in > NameError: name 'test' is not defined -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Sat Feb 28 02:26:54 2015 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 27 Feb 2015 17:26:54 -0800 Subject: [Tutor] Use python to parse the subject line of emails, listen for and react to commands In-Reply-To: References: Message-ID: > That's nearly always a bad idea. eval is a big security risk, especially if > applied to external input. And as you've discovered, > it makes debugging into a bit of a nightmare. Yes, I concur with Alan. eval() is definitely the wrong tool here. It's **extraordinarily** dangerous in the context of consuming arbitrary email input. Did anyone teach you to use eval()? An alternative approach to what you're considering is to define a mapping from command name to functionality. A quick-and-dirty approach uses a dictionary, and may have enough power for what you're trying to do. Here's an example to demonstrate: let's say that we'd like a calculator that takes a sequence of operations, like: zero inc inc double and performs them in turn to zero out memory, increment, increment, and double. (getting us four). Here's a brief sketch of what this might look like: ######################################## def zero(n): return 0 def double(n): return n * 2 def inc(n): return n + 1 cmd_mapping = { 'zero': zero, 'double': double, 'inc': inc } ## Run the calculator: memory = 0 for cmd_string in 'inc inc inc double double inc'.split(): cmd = cmd_mapping[cmd_string] memory = cmd(memory) print memory ######################################## Here, we let a string dictate what's being computed, but in a controlled fashion. The "magic" here is the line: cmd = cmd_mapping[cmd_string] which gets a function, which we can just call later on. Since cmd_mapping is a dictionary whose contents we control, we know that the only command being looked up has to be in the cmd_mapping. Compare vs. an eval-based approach. Unlike an approach that uses eval(), if the command string contains bad values here, nothing too bad will happen: at worst, we'll see a reliable dictionary lookup error. You'll even get a good line number in the stack trace! If we were to use eval, we would not. In the worst case, we might accidentally let an adversary dictate what our computer is going to do, against our wishes. For more discussion why eval() is almost certainly not the tool you want to use, see: http://code.activestate.com/lists/python-tutor/33338/ From willie14228 at outlook.com Sat Feb 28 04:38:22 2015 From: willie14228 at outlook.com (Willie Sims) Date: Fri, 27 Feb 2015 21:38:22 -0600 Subject: [Tutor] Use python to parse the subject line of emails, listen for and react to commands In-Reply-To: References: Message-ID: Sorry, I should clarify something No one has taught me anything, I have been trying to learn all this on my own. To be honest much of the code I have is taken from examples and modified for what I was trying to do. Talk about learning the Hard Way!!! I have actually made everything work My test.py is simply a print ("it works") The way I made it work was to execfile the subject +.py, Again this is a small embedded device (BeagleBone Black) that will be using a mobile hotspot for internet, the hotspot has a private ip (Verizon) so I cannot access the server from outside the network. As such and because I am looking for ways to minimize data usage I want to be able interact with the device through email commands...... The code is not pretty and I have no doubt that there are thousands of ways for it to be hacked or messed up since there is little to no error checking in it. I don?t know enough to do so yet sorry I am doing the best I can and have only started learning python a week ago. I still have to add in a more complex command system that will allow me to change a settings page. So for example if I sent an email to the devices registered email address with the command NEW_OWNER(EMAILADDRESS at EMAIL.COM),(PASSWORD) it would change the Owners email to the one listed in the subject and only accept emails from that email address if the password matches. My plan is to have an email template that the script will reply back with that will have the commands listed in html so when the command is clicked from the email it will automatically open the email app and add in the keyword in the subject line to help eliminate typo errors.. Each Keyword is an .py script that this script will start it does not yet have a way of doing more complex changes like what I listed above and while I wish I could say that I wrote all this script from scratch the truth is I butchered other scripts from examples and made it work. But It is helping me learn (ALONG WITH GIVING ME A LOT OF GRAY HAIRS) that being said I love how python can be SIMPLE or as complex as you need it! Sorry for what may seem like dumb questions I really do want to thank all of you for your help! #!/usr/bin/env python import sys import imaplib import getpass import email import email.header EMAIL_ACCOUNT = "MYEMAIL at gmail.com" # the email account that py will check EMAIL_FOLDER = "INBOX" OWNER = "willie14228 at outlook.com" COMMAND_FILE = open("output.txt","w") def process_mailbox(M): rv, data = M.search(None, "From",(OWNER)) if rv != 'OK': print "No messages found!" return for num in data[0].split(): rv, data = M.fetch(num, '(RFC822)') if rv != 'OK': print "ERROR getting message", num return msg = email.message_from_string(data[0][1]) decode = email.header.decode_header(msg['Subject'])[0] subject = unicode(decode[0]) print '%s' % (subject) COMMAND_FILE.write('%s' % (subject)+'.py') COMMAND_FILE.close() EX = '%s' %(subject)+'.py' #save the subject as an name.py execfile (EX) # exe name as a py M = imaplib.IMAP4_SSL('imap.gmail.com') try: rv, data = M.login(EMAIL_ACCOUNT, getpass.getpass()) except imaplib.IMAP4.error: print "LOGIN FAILED!!! " sys.exit(1) print rv, data rv, mailboxes = M.list() #if rv == 'OK': #print "Mailboxes:" #print mailboxes rv, data = M.select(EMAIL_FOLDER) if rv == 'OK': print "Processing mailbox...\n" process_mailbox(M) M.select('INBOX') M.store("1:*", '+FLAGS', '\\Deleted') #Flag all Trash as Deleted M.expunge() M.close() else: print "ERROR: Unable to open mailbox ", rv M.logout() -----Original Message----- From: Danny Yoo [mailto:dyoo at hashcollision.org] Sent: Friday, February 27, 2015 7:27 PM To: willie14228 at outlook.com Cc: Python Tutor Mailing List Subject: Re: [Tutor] Use python to parse the subject line of emails, listen for and react to commands > That's nearly always a bad idea. eval is a big security risk, > especially if applied to external input. And as you've discovered, it > makes debugging into a bit of a nightmare. Yes, I concur with Alan. eval() is definitely the wrong tool here. It's **extraordinarily** dangerous in the context of consuming arbitrary email input. Did anyone teach you to use eval()? An alternative approach to what you're considering is to define a mapping from command name to functionality. A quick-and-dirty approach uses a dictionary, and may have enough power for what you're trying to do. Here's an example to demonstrate: let's say that we'd like a calculator that takes a sequence of operations, like: zero inc inc double and performs them in turn to zero out memory, increment, increment, and double. (getting us four). Here's a brief sketch of what this might look like: ######################################## def zero(n): return 0 def double(n): return n * 2 def inc(n): return n + 1 cmd_mapping = { 'zero': zero, 'double': double, 'inc': inc } ## Run the calculator: memory = 0 for cmd_string in 'inc inc inc double double inc'.split(): cmd = cmd_mapping[cmd_string] memory = cmd(memory) print memory ######################################## Here, we let a string dictate what's being computed, but in a controlled fashion. The "magic" here is the line: cmd = cmd_mapping[cmd_string] which gets a function, which we can just call later on. Since cmd_mapping is a dictionary whose contents we control, we know that the only command being looked up has to be in the cmd_mapping. Compare vs. an eval-based approach. Unlike an approach that uses eval(), if the command string contains bad values here, nothing too bad will happen: at worst, we'll see a reliable dictionary lookup error. You'll even get a good line number in the stack trace! If we were to use eval, we would not. In the worst case, we might accidentally let an adversary dictate what our computer is going to do, against our wishes. For more discussion why eval() is almost certainly not the tool you want to use, see: http://code.activestate.com/lists/python-tutor/33338/ From cs at zip.com.au Sat Feb 28 23:54:26 2015 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 1 Mar 2015 09:54:26 +1100 Subject: [Tutor] Variable data to CSV In-Reply-To: References: Message-ID: <20150228225426.GA77592@cskk.homeip.net> On 27Feb2015 23:16, alan.gauld at btinternet.com wrote: >On 27/02/15 20:00, Thomas Toker wrote: >>I need to find the device address, usb port, and number of times the error occurs > >OK, Assume we don;t know anything about USB >Explain how that relates tom your sample data below. >Which columns do you want to extract/process? >Your data is not consistent in structure so using csv is >probably more trouble than its worth. The OP wanted to write the results of his scan as CSV. The input isn't CSV; it looks like Linux kernal demsg output with time-since-boot timestamp prefixes. >Look at using split() based on both spaces and colons. I'd be: - using split on space as suggested - discarding/skipping (possibly noting) the timestamp column - grabbing column 2 and checking for "hub" or "usb", ignoring other lines - grabbing column 3 as the device designator; looks like 1+2 is a useful device key - keeping some state for the counting, and resetting the counter when you see a new device - for extra points, later, keeping multiple state in case thiese processes ever overlap I would suggest using "in" to check for strings and because they are very fixed in kernel messages, checking for long strings: # split line into words words = line.split() if "new high speed USB device using ehci_hcd and address" in line: # get port number from last field port = int(words[-1]) and so forth. Must simpler. Regarding counters: # at start of script: counts = {} # dict of counter based on port (or better, (device, port)) # when new device seen (nb: possibly print out accumulated prior count value) count[port] = 0 # when new error seen count[port] += 1 Chase CSV as a totally separat thing later; just use print() for now. Cheers, Cameron Simpson I am of course experienced in teaching and have read the writings of Socrates. - egnilges at phoenix.Princeton.Edu From ftaghdia at gmail.com Sat Feb 28 21:20:49 2015 From: ftaghdia at gmail.com (Fatimah Taghdi) Date: Sat, 28 Feb 2015 15:20:49 -0500 Subject: [Tutor] BinaryTrees Message-ID: So i am doing this assignment and we have make a function that changes a binary tree represenation list of lists to nodes and I was wondering if somone can help on where to start and If there is a possiblity of keeping track of the indexdes. -- *F.T.*