From haleysandherr at gmail.com Tue Nov 1 17:28:34 2016 From: haleysandherr at gmail.com (Haley Sandherr) Date: Tue, 1 Nov 2016 17:28:34 -0400 Subject: [Tutor] Python code Message-ID: Hello, I am new to python and need help with this question: Compose a function odd ( ) that takes three bool arguments and returns True if an odd number of arguments are True and False otherwise. From steve at pearwood.info Tue Nov 1 20:15:25 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 2 Nov 2016 11:15:25 +1100 Subject: [Tutor] Python code In-Reply-To: References: Message-ID: <20161102001524.GJ3365@ando.pearwood.info> On Tue, Nov 01, 2016 at 05:28:34PM -0400, Haley Sandherr wrote: > Hello, I am new to python and need help with this question: > > Compose a function odd ( ) that takes three bool arguments and returns > True if an odd number of arguments are True and False otherwise. What part are you having trouble with? Can you show us what code you have tried to write? Do you know how to define a function that takes three arguments? Here's an example of a function that takes FOUR arguments and does nothing: def my_function(m, b, x, p): pass Can you...? - change the name of the function? - change it so that it takes three arguments rather than four? - choose more sensible names for the arguments? - change the "do nothing" body (pass) to make it do something more useful? Start by doing that, and if you still need help, show us the code you have come up with and we'll continue from there. -- Steve From badouglas at gmail.com Tue Nov 1 20:18:21 2016 From: badouglas at gmail.com (bruce) Date: Tue, 1 Nov 2016 20:18:21 -0400 Subject: [Tutor] implementing sed - termination error Message-ID: Hi Running a test on a linux box, with python. Trying to do a search/replace over a file, for a given string, and replacing the string with a chunk of text that has multiple lines. >From the cmdline, using sed, no prob. however, implementing sed, runs into issues, that result in a "termination error" The error gets thrown, due to the "\" of the newline. SO, and other sites have plenty to say about this, but haven't run across any soln. The test file contains 6K lines, but, the process requires doing lots of search/replace operations, so I'm interested in testing this method to see how "fast" the overall process is. The following psuedo code is what I've used to test. The key point being changing the "\n" portion to try to resolved the termination error. import subprocess ll_="ffdfdfdfghhhh" ll2_="12112121212121212" hash="aaaaa" data_=ll_+"\n"+ll2_+"\n"+qq22_ print data_ cc='sed -i "s/'+hash+'/'+data_+'/g" '+dname print cc proc=subprocess.Popen(cc, shell=True,stdout=subprocess.PIPE) res=proc.communicate()[0].strip() =================== error sed: -e expression #1, char 38: unterminated `s' command From alan.gauld at yahoo.co.uk Tue Nov 1 21:19:03 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 2 Nov 2016 01:19:03 +0000 Subject: [Tutor] implementing sed - termination error In-Reply-To: References: Message-ID: On 02/11/16 00:18, bruce wrote: > Trying to do a search/replace over a file, for a given string, and > replacing the string with a chunk of text that has multiple lines. > > From the cmdline, using sed, no prob. however, implementing sed, runs > into issues, that result in a "termination error" I don;t understand what you mean by that last paragraph. "using sed, no prob" implies you know the command you want to run because you got it to work on the command line? If that's correct can you share the exact command you typed at the command line that worked? "implementing sed" implies you are trying to write the sed tool in Python. but your code suggests you are trying to run sed from within a Python script - very different. > The error gets thrown, due to the "\" of the newline. That sounds very odd. What leads you to that conclusion? For that matter which \ or newline? In which string - the search string, the replacement string or the file content? > The test file contains 6K lines, but, the process requires doing lots > of search/replace operations, so I'm interested in testing this method > to see how "fast" the overall process is. I'm not sure what you are testing? Is it the sed tool itself? Or is it the Python script that runs sed? Or something else? > The following psuedo code is what I've used to test. Pseudo code is fine to explain complex algorithms but in this case the actual code is probably more useful. > The key point > being changing the "\n" portion to try to resolved the termination > error. Again, I don't really understand what you mean by that. > import subprocess > > ll_="ffdfdfdfghhhh" > ll2_="12112121212121212" > hash="aaaaa" > > data_=ll_+"\n"+ll2_+"\n"+qq22_ > print data_ > > cc='sed -i "s/'+hash+'/'+data_+'/g" '+dname > print cc I assume dname is your file? I'd also use string formatting to construct the command, simply because sed uses regex and a lot of + signs looks like a regex so it is confusing (to me at least). But see the comment below about Popen args. > > proc=subprocess.Popen(cc, shell=True,stdout=subprocess.PIPE) > res=proc.communicate()[0].strip() > > > > =================== > error > sed: -e expression #1, char 38: unterminated `s' command My first instinct when dealing with subprocess errors is to set shell=False to ensure the shell isn't messing about with my inputs. What happens if you set shell false? I'd also tend to put the sed arguments into a list rather than pass a single string. -- 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 yahoo.co.uk Tue Nov 1 21:25:47 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 2 Nov 2016 01:25:47 +0000 Subject: [Tutor] Python code In-Reply-To: References: Message-ID: On 01/11/16 21:28, Haley Sandherr wrote: > Hello, I am new to python and need help with this question: What kind of help? What exactly do you find difficult? > > Compose a function odd ( ) Can you define a function? Any function? > that takes three bool arguments Can you define a function that takes arguments - any arguments? Can you define one that takes exactly 3 arguments? > and returns True Can you define a function that returns a value - any value? Can you define a function that returns True? > if an odd number of arguments are True and False otherwise. Can you test if a value is True? Can you test if 2 out of 3 are True? (There are several ways to do this! Some easy and some harder but shorter ) How far down that list do you get before becoming stuck? I could show you a single line solution, but I doubt you would learn very much from it. It is better for you to come up with your own solution where you actually understand what every line of code does. -- 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 Wed Nov 2 00:58:08 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 1 Nov 2016 21:58:08 -0700 Subject: [Tutor] Python code In-Reply-To: References: Message-ID: On Nov 1, 2016 4:57 PM, "Haley Sandherr" wrote: > > Hello, I am new to python and need help with this question: > > Compose a function odd ( ) that takes three bool arguments and returns True if an odd number of arguments are True and False otherwise. Do you understand all of the terms in the question? Are there terms in the question that you don't know? Try a simpler, related problem if you are getting stuck: it may help point the way forward. For example, your original question has three arguments. Can you do the problem variation that just has one boolean argument? Call this odd1(). You can see that it's like the original problem. If you can do this, try writing odd2(): a function that can deal with two arguments. Can you do this? What other similar functions have you seen so far? These questions are intended to help us calibrate our mental model of what you currently understand. Please tell us more do we can give you appropriate answers. From cs at zip.com.au Wed Nov 2 01:22:21 2016 From: cs at zip.com.au (cs at zip.com.au) Date: Wed, 2 Nov 2016 16:22:21 +1100 Subject: [Tutor] implementing sed - termination error In-Reply-To: References: Message-ID: <20161102052221.GA29852@cskk.homeip.net> On 01Nov2016 20:18, bruce wrote: >Running a test on a linux box, with python. >Trying to do a search/replace over a file, for a given string, and >replacing the string with a chunk of text that has multiple lines. > >From the cmdline, using sed, no prob. however, implementing sed, runs >into issues, that result in a "termination error" Just terminology: you're not "implementing sed", which is a nontrivial task that would involve writing a python program that could do everything sed does. You're writing a small python program to call sed to do the work. Further discussion below. >The error gets thrown, due to the "\" of the newline. SO, and other >sites have plenty to say about this, but haven't run across any soln. > >The test file contains 6K lines, but, the process requires doing lots >of search/replace operations, so I'm interested in testing this method >to see how "fast" the overall process is. > >The following psuedo code is what I've used to test. The key point >being changing the "\n" portion to try to resolved the termination >error. > >import subprocess > >ll_="ffdfdfdfghhhh" >ll2_="12112121212121212" >hash="aaaaa" > >data_=ll_+"\n"+ll2_+"\n"+qq22_ >print data_ Presuming qq22_ is not shown. >cc='sed -i "s/'+hash+'/'+data_+'/g" '+dname >print cc >proc=subprocess.Popen(cc, shell=True,stdout=subprocess.PIPE) >res=proc.communicate()[0].strip() There are two fairly large problems with this program. The first is your need to embed newlines in the replacement pattern. You have genuine newlines in your string, but a sed command would look like this: sed 's/aaaaa/ffdfdfdfghhhh\ 12112121212121212\ qqqqq/g' so you need to replace the newlines with "backslash and newline". Fortunately strings have a .replace() method which you can use for this purpose. Look it up: https://docs.python.org/3/library/stdtypes.html#str.replace You can use it to make data_ how you want it to be for the command. The second problem is that you're then trying to invoke sed by constructing a shell command string and handing that to Popen. This means that you need to embed shell syntax in that string to quote things like the sed command. All very messy. It is better to _bypass_ the shell and invoke sed directory by leaving out the "shell=True" parameter. All the command line (which is the shell) is doing is honouring the shell quoting and constructing a sed invocation as distinct strings: sed -i s/this/that/g filename You want to do the equivalent in python, something like this: sed_argv = [ 'sed', '-i', 's/'+hash+'/'+data_+'/g', dname ] proc=subprocess.Popen(sed_argv, stdout=subprocess.PIPE) See how you're now unconcerned by any difficulties around shell quoting? You're now dealing directly in strings. There are a few other questions, such as: if you're using sed's -i option, why is stdout a pipe? And what if hash or data_ contain slashes, which you are using in sed to delimit them? Hoping this will help you move forward. Cheers, Cameron Simpson From palani at vahaitech.com Wed Nov 2 02:44:50 2016 From: palani at vahaitech.com (Palanikumar Gopalakrishnan) Date: Wed, 2 Nov 2016 12:14:50 +0530 Subject: [Tutor] Module webbrowser.os Message-ID: Hi Guys, I recently tested with some code , which open browser import webbrowser webbrowser.open("https://www.google.com") After that i want to experiment with webbrowser.os module, But dont know how to execute it.So I use dir(webbrowser.os) to find some details. Then i tried the following webbrowser.os(umask) But It retruns the following error *Traceback (most recent call last): File "", line 1, in NameError: name 'umask' is not defined* -- *Warm Regards,* *Palanikumar Gopalakrishnan *[image: ?] *Developer* From __peter__ at web.de Wed Nov 2 04:21:45 2016 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Nov 2016 09:21:45 +0100 Subject: [Tutor] implementing sed - termination error References: Message-ID: bruce wrote: > Hi > > Running a test on a linux box, with python. > > Trying to do a search/replace over a file, for a given string, and > replacing the string with a chunk of text that has multiple lines. > > From the cmdline, using sed, no prob. however, implementing sed, runs > into issues, that result in a "termination error" > > The error gets thrown, due to the "\" of the newline. SO, and other > sites have plenty to say about this, but haven't run across any soln. > > The test file contains 6K lines, but, the process requires doing lots > of search/replace operations, so I'm interested in testing this method > to see how "fast" the overall process is. > > The following psuedo code is what I've used to test. The key point > being changing the "\n" portion to try to resolved the termination > error. Here's a self-contained example that demonstrates that the key change is to avoid shell=True. $ cat input.txt foo alpha beta foo gamma epsilon foo zeta $ sed s/foo/bar\\nbaz/g input.txt bar baz alpha beta bar baz gamma epsilon bar baz zeta $ python3 Python 3.4.3 (default, Sep 14 2016, 12:36:27) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import subprocess >>> subprocess.call(["sed", "s/foo/bar\\nbaz/g", "input.txt"]) bar baz alpha beta bar baz gamma epsilon bar baz zeta 0 Both the shell and Python require you to escape, so if you use one after the other you have to escape the escapes; but with only one level of escapes and a little luck you need not make any changes between Python and the shell. From alan.gauld at yahoo.co.uk Wed Nov 2 05:16:56 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 2 Nov 2016 09:16:56 +0000 Subject: [Tutor] Module webbrowser.os In-Reply-To: References: Message-ID: On 02/11/16 06:44, Palanikumar Gopalakrishnan wrote: > After that i want to experiment with webbrowser.os module, But dont know > how to execute it. webbrowser.os seems to just be a link to the standard os module. So you should read the docs for os...and use the os module directly. > So I use dir(webbrowser.os) to find some details. Then i > tried the following > > webbrowser.os(umask) > > But It retruns the following error > > *Traceback (most recent call last): File "", line 1, in > NameError: name 'umask' is not defined* I'm not sure why because it works for me in both Python 2.7 and 3.4. Which OS are you using? And which Python version? But note that umask is a function so webbrowser.os(umask) returns a function reference. To get the umask value you must supply one: webbrowser.os(umask(0x777)) And the returned value will be the current umask() (Which you should store and restore when finished with the new umask) -- 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 Nov 2 07:36:40 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 2 Nov 2016 22:36:40 +1100 Subject: [Tutor] Module webbrowser.os In-Reply-To: References: Message-ID: <20161102113639.GL3365@ando.pearwood.info> On Wed, Nov 02, 2016 at 12:14:50PM +0530, Palanikumar Gopalakrishnan wrote: > Hi Guys, > I recently tested with some code , which open browser > > import webbrowser > webbrowser.open("https://www.google.com") > > After that i want to experiment with webbrowser.os module, webbrowser.os is just the os module. https://docs.python.org/2/library/os.html https://docs.python.org/3/library/os.html When a module imports another module, say: import os then "os" becomes a top level name, available as webbrowser.os. But you shouldn't use it. Just do "import os" and then use "os" on its own. -- Steve From steve at pearwood.info Wed Nov 2 21:31:30 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 3 Nov 2016 12:31:30 +1100 Subject: [Tutor] Module webbrowser.os In-Reply-To: References: Message-ID: <20161103013130.GP3365@ando.pearwood.info> On Wed, Nov 02, 2016 at 09:16:56AM +0000, Alan Gauld via Tutor wrote: > On 02/11/16 06:44, Palanikumar Gopalakrishnan wrote: > > webbrowser.os(umask) > > > > But It retruns the following error > > > > *Traceback (most recent call last): File "", line 1, in > > NameError: name 'umask' is not defined* > > I'm not sure why because it works for me in both Python 2.7 and 3.4. It may work for you if you ran "from os import *" first. Otherwise, in a fresh Python environment, there's no name "umask": py> uname Traceback (most recent call last): File "", line 1, in NameError: name 'uname' is not defined And so webbrowser.os(umask) fails because umask is not defined. If you define it, you get a second error: py> uname = 17 py> webbrowser.os(uname) Traceback (most recent call last): File "", line 1, in TypeError: 'module' object is not callable I think that what Palanikumar intended was: webbrowser.os.uname > Which OS are you using? And which Python version? > > But note that umask is a function so > > webbrowser.os(umask) > > returns a function reference. To get the umask value you must > supply one: > > webbrowser.os(umask(0x777)) I think you've missed the round brackets () and imagined a dot . :-) -- Steve From palani at vahaitech.com Thu Nov 3 02:43:45 2016 From: palani at vahaitech.com (Palanikumar Gopalakrishnan) Date: Thu, 3 Nov 2016 02:43:45 -0400 Subject: [Tutor] Module webbrowser.os Message-ID: On Wed, Nov 2, 2016 at 7:36 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: Python code (Danny Yoo) > 2. Re: implementing sed - termination error (cs at zip.com.au) > 3. Module webbrowser.os (Palanikumar Gopalakrishnan) > 4. Re: implementing sed - termination error (Peter Otten) > 5. Re: Module webbrowser.os (Alan Gauld) > 6. Re: Module webbrowser.os (Steven D'Aprano) > > > ---------- Forwarded message ---------- > From: Danny Yoo > To: Haley Sandherr > Cc: Tutor at python.org > Date: Tue, 1 Nov 2016 21:58:08 -0700 > Subject: Re: [Tutor] Python code > On Nov 1, 2016 4:57 PM, "Haley Sandherr" wrote: > > > > Hello, I am new to python and need help with this question: > > > > Compose a function odd ( ) that takes three bool arguments and returns > True if an odd number of arguments are True and False otherwise. > > Do you understand all of the terms in the question? Are there terms in the > question that you don't know? > > Try a simpler, related problem if you are getting stuck: it may help point > the way forward. > > For example, your original question has three arguments. Can you do the > problem variation that just has one boolean argument? Call this odd1(). > You can see that it's like the original problem. > > If you can do this, try writing odd2(): a function that can deal with two > arguments. Can you do this? > > What other similar functions have you seen so far? > > These questions are intended to help us calibrate our mental model of what > you currently understand. Please tell us more do we can give you > appropriate answers. > > > > ---------- Forwarded message ---------- > From: cs at zip.com.au > To: bruce > Cc: Python Tutor Mailing List > Date: Wed, 2 Nov 2016 16:22:21 +1100 > Subject: Re: [Tutor] implementing sed - termination error > On 01Nov2016 20:18, bruce wrote: > >> Running a test on a linux box, with python. >> Trying to do a search/replace over a file, for a given string, and >> replacing the string with a chunk of text that has multiple lines. >> >> From the cmdline, using sed, no prob. however, implementing sed, runs >> into issues, that result in a "termination error" >> > > Just terminology: you're not "implementing sed", which is a nontrivial > task that would involve writing a python program that could do everything > sed does. You're writing a small python program to call sed to do the work. > > Further discussion below. > > The error gets thrown, due to the "\" of the newline. SO, and other >> sites have plenty to say about this, but haven't run across any soln. >> >> The test file contains 6K lines, but, the process requires doing lots >> of search/replace operations, so I'm interested in testing this method >> to see how "fast" the overall process is. >> >> The following psuedo code is what I've used to test. The key point >> being changing the "\n" portion to try to resolved the termination >> error. >> >> import subprocess >> >> ll_="ffdfdfdfghhhh" >> ll2_="12112121212121212" >> hash="aaaaa" >> >> data_=ll_+"\n"+ll2_+"\n"+qq22_ >> print data_ >> > > Presuming qq22_ is not shown. > > cc='sed -i "s/'+hash+'/'+data_+'/g" '+dname >> print cc >> proc=subprocess.Popen(cc, shell=True,stdout=subprocess.PIPE) >> res=proc.communicate()[0].strip() >> > > There are two fairly large problems with this program. The first is your > need to embed newlines in the replacement pattern. You have genuine > newlines in your string, but a sed command would look like this: > > sed 's/aaaaa/ffdfdfdfghhhh\ > 12112121212121212\ > qqqqq/g' > > so you need to replace the newlines with "backslash and newline". > > Fortunately strings have a .replace() method which you can use for this > purpose. Look it up: > > https://docs.python.org/3/library/stdtypes.html#str.replace > > You can use it to make data_ how you want it to be for the command. > > The second problem is that you're then trying to invoke sed by > constructing a shell command string and handing that to Popen. This means > that you need to embed shell syntax in that string to quote things like the > sed command. All very messy. > > It is better to _bypass_ the shell and invoke sed directory by leaving out > the "shell=True" parameter. All the command line (which is the shell) is > doing is honouring the shell quoting and constructing a sed invocation as > distinct strings: > > sed > -i > s/this/that/g > filename > > You want to do the equivalent in python, something like this: > > sed_argv = [ 'sed', '-i', 's/'+hash+'/'+data_+'/g', dname ] > proc=subprocess.Popen(sed_argv, stdout=subprocess.PIPE) > > See how you're now unconcerned by any difficulties around shell quoting? > You're now dealing directly in strings. > > There are a few other questions, such as: if you're using sed's -i option, > why is stdout a pipe? And what if hash or data_ contain slashes, which you > are using in sed to delimit them? > > Hoping this will help you move forward. > > Cheers, > Cameron Simpson > > > > ---------- Forwarded message ---------- > From: Palanikumar Gopalakrishnan > To: tutor at python.org > Cc: > Date: Wed, 2 Nov 2016 12:14:50 +0530 > Subject: [Tutor] Module webbrowser.os > Hi Guys, > I recently tested with some code , which open browser > > import webbrowser > webbrowser.open("https://www.google.com") > > After that i want to experiment with webbrowser.os module, But dont know > how to execute it.So I use dir(webbrowser.os) to find some details. Then i > tried the following > > webbrowser.os(umask) > > But It retruns the following error > > > > *Traceback (most recent call last): File "", line 1, in > NameError: name 'umask' is not defined* > > > > > > -- > > *Warm Regards,* > > *Palanikumar Gopalakrishnan *[image: ?] > *Developer* > > > > ---------- Forwarded message ---------- > From: Peter Otten <__peter__ at web.de> > To: tutor at python.org > Cc: > Date: Wed, 02 Nov 2016 09:21:45 +0100 > Subject: Re: [Tutor] implementing sed - termination error > bruce wrote: > > > Hi > > > > Running a test on a linux box, with python. > > > > Trying to do a search/replace over a file, for a given string, and > > replacing the string with a chunk of text that has multiple lines. > > > > From the cmdline, using sed, no prob. however, implementing sed, runs > > into issues, that result in a "termination error" > > > > The error gets thrown, due to the "\" of the newline. SO, and other > > sites have plenty to say about this, but haven't run across any soln. > > > > The test file contains 6K lines, but, the process requires doing lots > > of search/replace operations, so I'm interested in testing this method > > to see how "fast" the overall process is. > > > > The following psuedo code is what I've used to test. The key point > > being changing the "\n" portion to try to resolved the termination > > error. > > Here's a self-contained example that demonstrates that the key change is to > avoid shell=True. > > $ cat input.txt > foo > alpha > beta foo gamma > epsilon > foo zeta > $ sed s/foo/bar\\nbaz/g input.txt > bar > baz > alpha > beta bar > baz gamma > epsilon > bar > baz zeta > $ python3 > Python 3.4.3 (default, Sep 14 2016, 12:36:27) > [GCC 4.8.4] on linux > Type "help", "copyright", "credits" or "license" for more information. > >>> import subprocess > >>> subprocess.call(["sed", "s/foo/bar\\nbaz/g", "input.txt"]) > bar > baz > alpha > beta bar > baz gamma > epsilon > bar > baz zeta > 0 > > Both the shell and Python require you to escape, so if you use one after > the > other you have to escape the escapes; but with only one level of escapes > and > a little luck you need not make any changes between Python and the shell. > > > > > > > ---------- Forwarded message ---------- > From: Alan Gauld > To: tutor at python.org > Cc: > Date: Wed, 2 Nov 2016 09:16:56 +0000 > Subject: Re: [Tutor] Module webbrowser.os > On 02/11/16 06:44, Palanikumar Gopalakrishnan wrote: > > After that i want to experiment with webbrowser.os module, But dont know > > how to execute it. > > webbrowser.os seems to just be a link to the standard os module. > So you should read the docs for os...and use the os module directly. > > > So I use dir(webbrowser.os) to find some details. Then i > > tried the following > > > > webbrowser.os(umask) > > > > But It retruns the following error > > > > *Traceback (most recent call last): File "", line 1, in > > NameError: name 'umask' is not defined* > > I'm not sure why because it works for me in both Python 2.7 and 3.4. > Which OS are you using? And which Python version? > > But note that umask is a function so > > webbrowser.os(umask) > > returns a function reference. To get the umask value you must > supply one: > > webbrowser.os(umask(0x777)) > > And the returned value will be the current umask() (Which you > should store and restore when finished with the new umask) > > -- > 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 > > > > > > ---------- Forwarded message ---------- > From: "Steven D'Aprano" > To: tutor at python.org > Cc: > Date: Wed, 2 Nov 2016 22:36:40 +1100 > Subject: Re: [Tutor] Module webbrowser.os > On Wed, Nov 02, 2016 at 12:14:50PM +0530, Palanikumar Gopalakrishnan wrote: > > Hi Guys, > > I recently tested with some code , which open browser > > > > import webbrowser > > webbrowser.open("https://www.google.com") > > > > After that i want to experiment with webbrowser.os module, > > webbrowser.os is just the os module. > > https://docs.python.org/2/library/os.html > https://docs.python.org/3/library/os.html > > When a module imports another module, say: > > import os > > then "os" becomes a top level name, available as webbrowser.os. But you > shouldn't use it. Just do "import os" and then use "os" on its own. > > > > -- > Steve > > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > Hi Alan, My python version is *2.7. *I tried the following but it not working , Returns same error message webbrowser.os(umask) webbrowser.os(umask(0x777)) -- *Warm Regards,* *Palanikumar Gopalakrishnan *[image: ?] *Developer* From alan.gauld at yahoo.co.uk Thu Nov 3 05:14:49 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 3 Nov 2016 09:14:49 +0000 Subject: [Tutor] Module webbrowser.os In-Reply-To: <20161103013130.GP3365@ando.pearwood.info> References: <20161103013130.GP3365@ando.pearwood.info> Message-ID: On 03/11/16 01:31, Steven D'Aprano wrote: > On Wed, Nov 02, 2016 at 09:16:56AM +0000, Alan Gauld via Tutor wrote: >> >> webbrowser.os(umask(0x777)) > > I think you've missed the round brackets () and imagined a dot . :-) Umm, yes, here is the actual session from my xterm: web.os.umask(0x777) # after import webbrowser as web Amazing how your brain sees what it thinks it should see! -- 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 yahoo.co.uk Thu Nov 3 05:19:49 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 3 Nov 2016 09:19:49 +0000 Subject: [Tutor] Module webbrowser.os In-Reply-To: References: Message-ID: On 03/11/16 06:43, Palanikumar Gopalakrishnan wrote: > On Wed, Nov 2, 2016 at 7:36 AM, wrote: ... >> Today's Topics: >> >> 1. Re: Python code (Danny Yoo) >> 2. Re: implementing sed - termination error (cs at zip.com.au) >> 3. Module webbrowser.os (Palanikumar Gopalakrishnan) >> 4. Re: implementing sed - termination error (Peter Otten) >> 5. Re: Module webbrowser.os (Alan Gauld) >> 6. Re: Module webbrowser.os (Steven D'Aprano) Please do not send the entire digest. Delete all that is not relevant. Everyone else has already seen those messages and some users pay by the byte. > Hi Alan, > > My python version is *2.7. *I tried the following but it not > working , Returns same error message > > > webbrowser.os(umask) > > webbrowser.os(umask(0x777)) > As Steve pointed out in his most recent post it should have been: webbrowser.os.umask(0x777) umask is an *attribute* of os not a parameter. And as we have both pointed out don't use webbrowser.os, just use os directly: import os os.umask(24) -- 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 ben+python at benfinney.id.au Thu Nov 3 05:32:37 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 03 Nov 2016 20:32:37 +1100 Subject: [Tutor] Turn off digest mode before participating in the forum (was: Module webbrowser.os) References: Message-ID: <85oa1w9adm.fsf_-_@benfinney.id.au> Alan Gauld via Tutor writes: > Please do not send the entire digest. > Delete all that is not relevant. Rather: Don't reply to the digest message. It breaks threading (because you're not replying to the actual message that was sent by the person you're responding to). Digest mode is only for use if you *know* that email address will never participate in the discussion. Instead: If you want to participate on the forum, turn off digest mode from the beginning. Receive the individual messages. Reply to the one message from the person you're intending to reply to. -- \ ?The future always arrives too fast, and in the wrong order.? | `\ ?Alvin Toffler | _o__) | Ben Finney From bnolf at cox.net Thu Nov 3 11:48:41 2016 From: bnolf at cox.net (Bill Nolf) Date: Thu, 3 Nov 2016 11:48:41 -0400 Subject: [Tutor] compress directory Message-ID: <20161103114842.Y98TK.475567.imail@fed1rmwml107> How do I compress (gzip and/or tar) a directory in python? I found examples of compressing a file using gzip or tar but not a directory. thanks From robertvstepp at gmail.com Thu Nov 3 14:02:56 2016 From: robertvstepp at gmail.com (boB Stepp) Date: Thu, 3 Nov 2016 13:02:56 -0500 Subject: [Tutor] compress directory In-Reply-To: <20161103114842.Y98TK.475567.imail@fed1rmwml107> References: <20161103114842.Y98TK.475567.imail@fed1rmwml107> Message-ID: On Thu, Nov 3, 2016 at 10:48 AM, Bill Nolf wrote: > How do I compress (gzip and/or tar) a directory in python? I found examples of compressing a file using gzip or tar but not a directory. > thanks I did a search for almost your exact question and got this: http://stackoverflow.com/questions/1855095/how-to-create-a-zip-archive-of-a-directory No time to look it over, but perhaps it will help. -- boB From ben+python at benfinney.id.au Thu Nov 3 14:19:31 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 04 Nov 2016 05:19:31 +1100 Subject: [Tutor] compress directory References: <20161103114842.Y98TK.475567.imail@fed1rmwml107> Message-ID: <85k2ck8lzg.fsf@benfinney.id.au> Bill Nolf writes: > How do I compress (gzip and/or tar) a directory in python? I found > examples of compressing a file using gzip or tar but not a directory. The Python standard library contains implementations of many common tools. It's well worth searching there first if you need something to do with data structures, protocols, or file formats. In this case, yes, there are several archive formats supported . -- \ ?Most people, I think, don't even know what a rootkit is, so | `\ why should they care about it?? ?Thomas Hesse, Sony BMG, 2006 | _o__) | Ben Finney From bn58243 at gmail.com Thu Nov 3 13:56:59 2016 From: bn58243 at gmail.com (Bill Nolf) Date: Thu, 3 Nov 2016 13:56:59 -0400 Subject: [Tutor] tar a directory Message-ID: python version 2.6.6 I'm trying to tar/gzip a directory, the directory is defined as an variable I want to tar and gzip the directory archive in the example below: import tarfile dirarchive = /a/b/c/archive Test 1 tar.add(dirarchive) Error: name 'tar' not defined Test 2 tarfile.add(dirarchive) Error: 'module' object has no attribute add Test 3 archive = tarfile.open(dirachive, "a:gz") archive.add=(dirarchive) archive.close() Error: IOError [Errono 21] Is a directory: /a/b/c/archive Test 4 archive = tarfile.open("test.tgz", "a:gz") archive.add=(dirarchive, arcname="test") archive.close() Create a gzip file called test.tgz in the current directory, which is close but no cigar What I would like is the following gzip file: /a/b/c/archive.tgz From ben+python at benfinney.id.au Thu Nov 3 23:16:59 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 04 Nov 2016 14:16:59 +1100 Subject: [Tutor] tar a directory References: Message-ID: <85a8dg7x3o.fsf@benfinney.id.au> Bill Nolf writes: > python version 2.6.6 > > I'm trying to tar/gzip a directory, the directory is defined as an variable > > I want to tar and gzip the directory archive in the example below: > > import tarfile > dirarchive = /a/b/c/archive This code will not run. I can guess what you might mean, but the larger problem is: You are obviously running different code from what you present here to us. Can you instead make a complete, simple example that *you* have run, and you know the result? That way, we will all be looking at the same code and the same behaviour. -- \ ?Try to learn something about everything and everything about | `\ something.? ?Thomas Henry Huxley | _o__) | Ben Finney From alan.gauld at yahoo.co.uk Fri Nov 4 05:54:22 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 4 Nov 2016 09:54:22 +0000 Subject: [Tutor] tar a directory In-Reply-To: References: Message-ID: On 03/11/16 17:56, Bill Nolf wrote: > Test 4 > > archive = tarfile.open("test.tgz", "a:gz") > archive.add=(dirarchive, arcname="test") > archive.close() > > Create a gzip file called test.tgz in the current directory, which is close > but no cigar > What I would like is the following gzip file: > > /a/b/c/archive.tgz So why not: archive = tarfile.open("/a/b/c/archive.tgz", "a:gz") or is that too obvious? -- 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 yahoo.co.uk Fri Nov 4 08:30:31 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 4 Nov 2016 12:30:31 +0000 Subject: [Tutor] Fwd: Re: tar a directory In-Reply-To: References: Message-ID: <581C7F67.50303@yahoo.co.uk> Always use reply-all or reply-list when responding to tutor posts.... ============================== The archive file changes each time so I need to set a variable based on the changing directory Sent from my iPhone > On Nov 4, 2016, at 5:54 AM, Alan Gauld via Tutor wrote: > >> On 03/11/16 17:56, Bill Nolf wrote: >> >> Test 4 >> >> archive = tarfile.open("test.tgz", "a:gz") >> archive.add=(dirarchive, arcname="test") >> archive.close() >> >> Create a gzip file called test.tgz in the current directory, which is close >> but no cigar >> What I would like is the following gzip file: >> >> /a/b/c/archive.tgz > > So why not: > > archive = tarfile.open("/a/b/c/archive.tgz", "a:gz") > > or is that too obvious? > > -- > 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 drtraceyjones at hotmail.com Fri Nov 4 17:57:23 2016 From: drtraceyjones at hotmail.com (tracey jones-Francis) Date: Fri, 4 Nov 2016 21:57:23 +0000 Subject: [Tutor] Code not working advise pls Message-ID: Hi, I want to write a function that will calculate and return the sum of the n highest value in a list a. Also, when n is less than 0, the answer should be zero, and if n is greater than the number of elements in the list, all elements should be included in the sum. In addition i want to write the code in a function with only one line of code in it. So far I have:- def sumHighest(a, n): lambda a, n : sum(a[:n]) This doesn't work but i want to use lambda and the slice in the function. An appropriate test would be:- input - sumHighest([1,2,3,4], 2) output - 7 Where am I going wrong? Thanks T. From lloydyf333 at gmail.com Fri Nov 4 12:44:11 2016 From: lloydyf333 at gmail.com (Lloyd Francis) Date: Fri, 4 Nov 2016 16:44:11 +0000 Subject: [Tutor] sumHighest function help Message-ID: Hi, I want to write a function that will calculate and return the sum of the *n* highest value in a list *a. *Also, when n is less than 0, the answer should be zero, and if n is greater than the number of elements in the list, all elements should be included in the sum. In addition i want to write the code in a function with only one line of code in it. So far I have:- def sumHighest(a, n): lambda a, n : sum(a[:n]) This doesn't work but i want to use *lambda *and the slice in the function. An appropriate test would be:- input - sumHighest([1,2,3,4], 2) output - 7 thanks L. From cs at zip.com.au Fri Nov 4 21:19:00 2016 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 5 Nov 2016 12:19:00 +1100 Subject: [Tutor] Code not working advise pls In-Reply-To: References: Message-ID: <20161105011900.GA67152@cskk.homeip.net> On 04Nov2016 21:57, tracey jones-Francis wrote: >I want to write a function that will calculate and return the sum of the n >highest value in a list a. Also, when n is less than 0, the answer should be >zero, and if n is greater than the number of elements in the list, all >elements should be included in the sum. > >In addition i want to write the code in a function with only one line of code in it. > >So far I have:- > >def sumHighest(a, n): >lambda a, n : sum(a[:n]) > >This doesn't work but i want to use lambda and the slice in the function. >An appropriate test would be:- >input - sumHighest([1,2,3,4], 2) >output - 7 When you say it doesn't work, it is considered good practice to show a transcript of it running, what its output (or error) was, and what you hoped to see. You have provided the second though, which is a good start. Just looking at the above, as written it should not even compile. I am presuming you are trying to define "sumHighest" to perform the function expressed in the lambda. In Python there are basicly two says to define a function. The commonest way looks like this: def sumHighest(a, n): return sum(a[:n]) In a sense, this does two things: it defines a function which accepts `a` and `n` and returns the result of a sum call; and secondarily, it _binds_ that function definition to the name "sumHighest". The less common way, which can be used if the function preforms a single Python expression, looks like this: sumHighest = lambda a, n: sum(a[:]) Here the two actions are more clearly separated: the "lambda" on the right hand side defines a function just as the first example did, and the "sumHigest =" _binds_ that function to the name "sumHighest". Both forms now give you a callable function which can be used with the name "sumHighest". You seem to have mixed the two forms together. I hope the two example above show you how they differ. Pick one. Otherwise, you function isn't quite there. Look up Python's built in "sorted()" function and consider how it may help. If you come back with further queries, please include a cut/paste transcript of the your program's code, and a run of it with the output. (NB: cut/patse the text, don't attach a screenshot.) Cheers, Cameron Simpson From alan.gauld at yahoo.co.uk Fri Nov 4 21:26:11 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 5 Nov 2016 01:26:11 +0000 Subject: [Tutor] sumHighest function help In-Reply-To: References: Message-ID: On 04/11/16 16:44, Lloyd Francis wrote: It looks suspiciously like you posted this same message from two addresses with different subjects, please don't do that as it splits the responses and makes searching archives more difficult. > I want to write a function that will calculate and return the sum of the *n* > highest value in a list *a. *Also, when n is less than 0, the answer should > be zero, and if n is greater than the number of elements in the list, all > elements should be included in the sum. I'm not totally clear what you mean. Lets conmsider the value of n: if n < 0 return 0 if n == 0 return ??? if n > len(lst) return sum(lst) if n > 0 and n < len(lst) return sum of n "highest" values - define highest? eg. What are the 3 highest values in the list [1,7,3,9,2,5,1,9] are they: [5,1,9] - highest positions [9,9,7] - highest valued items [9,7,5] - highest individual values or something else? Can you clarify the 2nd and last cases please? > In addition i want to write the code in a function with only one line of > code in it. This is a strange and wholly artificial request. We can write almost any function with one line but it's rarely a good idea. Let's ignore it for now and focus on writing a function that works. If we really need to we can reduce it to one line later. > So far I have:- > > def sumHighest(a, n): > lambda a, n : sum(a[:n]) This makes no sense since your function does not return any value. And the lambda line defines a function but never calls it. I'd suggest following the logic of your requirement above: def sumHighest(a,n): if n < 0: return 0 if n > len(a): return sum(a) if n == 0: return ???? # you must clarify else: newlist = find_N_highest(a,n) return sum(newlist) > This doesn't work but i want to use *lambda *and the slice in the function. Its not clear what role the slice plays until we understand what is meant by "highest" And lambda just returns a function which is not what you want. You may need a lambda to filter your list but again we don't know until we understand your requirement better. > An appropriate test would be:- > > input - sumHighest([1,2,3,4], 2) > output - 7 This could mean any of the cases I gave above, it doesn't clarify anything. -- 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 Nov 4 21:20:05 2016 From: cs at zip.com.au (cs at zip.com.au) Date: Sat, 5 Nov 2016 12:20:05 +1100 Subject: [Tutor] sumHighest function help In-Reply-To: References: Message-ID: <20161105012005.GA97143@cskk.homeip.net> Interesting. Tracey Jones has a very similar question... - Cameron Simpson On 04Nov2016 16:44, Lloyd Francis wrote: >Hi, > >I want to write a function that will calculate and return the sum of the *n* >highest value in a list *a. *Also, when n is less than 0, the answer should >be zero, and if n is greater than the number of elements in the list, all >elements should be included in the sum. > >In addition i want to write the code in a function with only one line of >code in it. >So far I have:- > >def sumHighest(a, n): >lambda a, n : sum(a[:n]) > >This doesn't work but i want to use *lambda *and the slice in the function. > >An appropriate test would be:- > >input - sumHighest([1,2,3,4], 2) >output - 7 > >thanks L. From __peter__ at web.de Sat Nov 5 08:07:01 2016 From: __peter__ at web.de (Peter Otten) Date: Sat, 05 Nov 2016 13:07:01 +0100 Subject: [Tutor] sumHighest function help References: Message-ID: Lloyd Francis wrote: > I want to write a function that will calculate and return the sum of the > *n* highest value in a list *a. *Also, when n is less than 0, the answer > should be zero, and if n is greater than the number of elements in the > list, all elements should be included in the sum. > > In addition i want to write the code in a function with only one line of > code in it. > So far I have:- > > def sumHighest(a, n): > lambda a, n : sum(a[:n]) > > This doesn't work but i want to use *lambda *and the slice in the > function. > > An appropriate test would be:- > > input - sumHighest([1,2,3,4], 2) > output - 7 > > thanks L. sum_highest = lambda items, n: sum(sorted(items, reverse=True)[:max(n, 0)]) or better: import heapq def sum_highest(items, n): return sum(heapq.nlargest(n, items)) From alan.gauld at yahoo.co.uk Sat Nov 5 08:42:06 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 5 Nov 2016 12:42:06 +0000 Subject: [Tutor] sumHighest function help In-Reply-To: References: Message-ID: On 05/11/16 12:07, Peter Otten wrote: > sum_highest = lambda items, n: sum(sorted(items, reverse=True)[:max(n, 0)]) > > or better: > > import heapq > > def sum_highest(items, n): > return sum(heapq.nlargest(n, items)) No, the first solution is "better" because it used lambda and slicing and so meets all of the OP's "requirements" ;-) -- 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 crk at godblessthe.us Sat Nov 5 21:44:15 2016 From: crk at godblessthe.us (Clayton Kirkwood) Date: Sat, 5 Nov 2016 18:44:15 -0700 Subject: [Tutor] Q regarding external program calling Message-ID: <068a01d237cf$48779480$d966bd80$@godblessthe.us> Looked all over, but haven't found the answer. If I have a (windows) program which I wish to start, even shell scripts, and possibly capture the output from, how do I do that? Thanks, C PS, also, please me to where I can find more. My searches were rather useless. From ben+python at benfinney.id.au Sat Nov 5 22:01:29 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 06 Nov 2016 13:01:29 +1100 Subject: [Tutor] Call an external program and capture its output (was: Q regarding external program calling) References: <068a01d237cf$48779480$d966bd80$@godblessthe.us> Message-ID: <851syp8iyu.fsf@benfinney.id.au> "Clayton Kirkwood" writes: > Looked all over, but haven't found the answer. Did you look in the Python standard library documentation ? > If I have a (windows) program which I wish to start, even shell > scripts, and possibly capture the output from, how do I do that? That depends on what ?capture the output? means. If you mean you want to capture the data in the ?stdout? and ?stderr? streams from the program, the standard library ?subprocess? module is what you want. More generally, running different programs concurrently has a section in the standard library documentation. > PS, also, please me to where I can find more. My searches were rather > useless. The Python documentation and Python wiki should always be early in your repertoire of searches for Python functionality. -- \ ?Few things are harder to put up with than the annoyance of a | `\ good example.? ?Mark Twain, _Pudd'n'head Wilson_ | _o__) | Ben Finney From dyoo at hashcollision.org Sat Nov 5 22:47:08 2016 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 5 Nov 2016 19:47:08 -0700 Subject: [Tutor] Q regarding external program calling In-Reply-To: <068a01d237cf$48779480$d966bd80$@godblessthe.us> References: <068a01d237cf$48779480$d966bd80$@godblessthe.us> Message-ID: Hi Clayton, I'm not too familiar with development on Windows, unfortunately, but I think the 'subprocess' module is what you're looking for. https://docs.python.org/3/library/subprocess.html For example: http://stackoverflow.com/questions/748028/how-to-get-output-of-exe-in-python-script should help you get started. To find that example, I did a web search (google, bing, duckduckgo) with the terms: [capture output in python] and all three search engines return reasonable results. Try it out and see if that helps you find some other good examples. If you have more questions, please feel free to ask. Good luck! From alan.gauld at yahoo.co.uk Sun Nov 6 04:09:24 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 6 Nov 2016 09:09:24 +0000 Subject: [Tutor] Q regarding external program calling In-Reply-To: <068a01d237cf$48779480$d966bd80$@godblessthe.us> References: <068a01d237cf$48779480$d966bd80$@godblessthe.us> Message-ID: On 06/11/16 01:44, Clayton Kirkwood wrote: > Looked all over, but haven't found the answer. If I have a (windows) program > which I wish to start, even shell scripts, and possibly capture the output > from, how do I do that? Others have already pointed you to the subprocess module. The documentation there includes several examples. On Windows it sometimes helps to start a program via the "start" command. eg start notepad.exe This also works with data files to start the associated program: eg start myfile.txt But otherwise it should just work as described in the docs. You may need to find the full path to the executable. If your program has a GUI however, accessing the output becomes much more difficult and may not even be possible. In that case you may need to resort to driving it programmatically via its API using a tool like pywin32 or ctypes. Some popular programs such as Excel have dedicated modules that you can use to read/write data. -- 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 jasondurnen at gmail.com Sun Nov 6 22:25:25 2016 From: jasondurnen at gmail.com (Jason Durnen) Date: Sun, 6 Nov 2016 21:25:25 -0600 Subject: [Tutor] Trouble Removing Whitespace Message-ID: Hello, I am totally new to programming but thought I would give it a shot. I recently purchased the Python Crash Course book and have run in to a problem in the second chapter. The section that talks about removing whitespace in code to be more precise. This is the code that I type in, but the result will not trim the extra space. The first group is how it is shown in the book, but when it prints, the ' is not included anywhere. favorite_language = 'python ' print (favorite_language) favorite_language = favorite_language.rstrip() print(favorite_language) In this section, I added double quotations around the single quotation and the word python, however I can't get it to remove the whitespace when it print the word. Is there something that I'm missing? favorite_language = "'Python '" print(favorite_language) favorite_language = favorite_language.rstrip() print(favorite_language) The following is the output I get from the two examples I have above: python python 'Python ' 'Python ' Press any key to continue . . . Any help you could give me would be greatly appreciated! Thanks for your time. Jason Durnen jasondurnen at gmail.com From alan.gauld at yahoo.co.uk Mon Nov 7 04:09:08 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 7 Nov 2016 09:09:08 +0000 Subject: [Tutor] Trouble Removing Whitespace In-Reply-To: References: Message-ID: On 07/11/16 03:25, Jason Durnen wrote: > This is the code that I type in, but the result will not trim the extra > space. The tricky thing about white space is that you can't se it, so how do you know it is there or not? One way is to surround it with something you can see: data = 'a string ' print(':'+data+':') # -> :a string : data = data.rstrip() print(':'+data+':') # -> :a string: > The first group is how it is shown in the book, but when it prints, > the ' is not included anywhere. Correct that's because the quote is what tells Python that it is a string. When the string is printed Python does not show the quotes. You can tell Python to include the quotes by asking it to print the *representation* of the data using the repr() function: print(repr(data)) This is another way of seeing the whitespace. > In this section, I added double quotations around the single quotation and > the word python, however I can't get it to remove the whitespace when it > print the word. Is there something that I'm missing? The problem is that rstrip() only strips whitespace as far back as the first non-white-space character. In your case that's the ' so rstrip() can find no whitespace to remove. Try your original code again but use either of the techniques I mentioned to see the whitespace. I think you'll find that it was removed after all. -- 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 Nov 7 04:14:15 2016 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 Nov 2016 10:14:15 +0100 Subject: [Tutor] Trouble Removing Whitespace References: Message-ID: Jason Durnen wrote: > Hello, > I am totally new to programming but thought I would give it a shot. I > recently purchased the Python Crash Course book and have run in to a > problem in the second chapter. The section that talks about removing > whitespace in code to be more precise. > > This is the code that I type in, but the result will not trim the extra > space. The first group is how it is shown in the book, but when it prints, > the ' is not included anywhere. > > favorite_language = 'python ' > print (favorite_language) > favorite_language = favorite_language.rstrip() > print(favorite_language) I don't know what you use for your experiments, for my demonstration below I use Python 3's "interactive interpreter" which is invoked from the command line with $ python3 The $ is the prompt which you don't have to type yourself and which will look differently on Windows. If all goes well you'll see something similar to Python 3.4.3 (default, Sep 14 2016, 12:36:27) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. >>> Let's start our experimentation: >>> print("python ") python >>> print("python") python OK, the two strings are different, but you do not see the difference because it consists of whitespace. One way around this is to print something else afterwards: >>> print("python ", 3) python 3 >>> print("python", 3) python 3 Now you should see a difference, more space between "python" and "3" in the first case. Invoking rstrip() removes that extra space at the end of the first string: >>> print("python ".strip(), 3) python 3 For debugging purposes you can convert a string using repr() which will not only add quotes, but also change newline and a few other characters to escape sequences. You can invoke repr() manually >>> print(repr("python ")) 'python ' >>> print(repr("python ".strip())) 'python' or implicitly by typing an expression in the interactive interpreter: >>> "python " 'python ' >>> "python ".strip() 'python' Here's a triple-quoted string spanning over multiple lines to demonstrate newline handling: >>> """triple ... quoted ... string ... """ 'triple\nquoted\nstring\n' > In this section, I added double quotations around the single quotation and > the word python, however I can't get it to remove the whitespace when it > print the word. Is there something that I'm missing? rstrip() removes whitespace from the end of the string, but at the end of your string is now a "'", not a " ". Therefore nothing is removed. > > favorite_language = "'Python '" > print(favorite_language) > favorite_language = favorite_language.rstrip() > print(favorite_language) > > The following is the output I get from the two examples I have above: > python > python > 'Python ' > 'Python ' > Press any key to continue . . . > > Any help you could give me would be greatly appreciated! > Thanks for your time. > > Jason Durnen > jasondurnen at gmail.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From eryksun at gmail.com Mon Nov 7 05:25:41 2016 From: eryksun at gmail.com (eryk sun) Date: Mon, 7 Nov 2016 10:25:41 +0000 Subject: [Tutor] Q regarding external program calling In-Reply-To: References: <068a01d237cf$48779480$d966bd80$@godblessthe.us> Message-ID: On Sun, Nov 6, 2016 at 9:09 AM, Alan Gauld via Tutor wrote: > On 06/11/16 01:44, Clayton Kirkwood wrote: >> Looked all over, but haven't found the answer. If I have a (windows) program >> which I wish to start, even shell scripts, and possibly capture the output >> from, how do I do that? > > Others have already pointed you to the subprocess module. > The documentation there includes several examples. > > On Windows it sometimes helps to start a program via the > "start" command. `start` is a cmd shell built-in command, so it requires passing shell=True to subprocess.Popen. It allows more control over how a process is started -- such as whether to use the current or a new console, the window state, the process working directory, priority, and CPU affinity -- and whether the shell should wait on the process. Popen directly supports most of what `start` does, and otherwise you can use os.startfile, which is generally safer than using the shell. > start notepad.exe Using `start` like this is typical in a batch file, to avoid waiting for the command to exit. In contrast, Popen defaults to asynchronous mode, and waiting requires the wait() or communicate() methods. > start myfile.txt `start` isn't generally necessary here. Both with and without `start`, cmd tries to locate and execute (open) the file. If the target is a batch file (i.e. .bat or .cmd), then cmd either executes it in place or, if the `start` command is used, executes it in a new shell via `cmd.exe /k`. Otherwise cmd first tries to execute the target via CreateProcess(). If the latter fails, cmd tries ShellExecuteEx(), using the default file association. For example, the .py extension is usually associated with the ProgId "Python.File". If the py launcher is installed, then the default action for this ProgId is typically the template command 'C:\Windows\py.exe "%1" %*'. ShellExecuteEx substitutes the target file and command-line arguments for the %1 and %* template parameters and then calls CreateProcess. The `start` command expands the set of possible targets to whatever ShellExecuteEx supports, including directories and virtual targets. For example: * Opening directories in Explorer * Opening `shell:` folders such as shell:UserProgramFiles * Executing "App Paths" commands registered under [HKCU|HKLM]\Software\Microsoft\Windows\CurrentVersion\App Paths > If your program has a GUI however, accessing the output > becomes much more difficult and may not even be > possible. In that case you may need to resort > to driving it programmatically via its API using > a tool like pywin32 or ctypes. The best-case scenario is an app that exports a COM IDispatch interface for scripting, which you can access via PyWin32's win32com module. From palani at vahaitech.com Tue Nov 8 09:46:44 2016 From: palani at vahaitech.com (Palanikumar Gopalakrishnan) Date: Tue, 8 Nov 2016 20:16:44 +0530 Subject: [Tutor] IndentationError: unexpected indent Message-ID: Hi Guys, I tried this code from internet, Its returns following please guide me to solve this error -- *Warm Regards,* *Palanikumar Gopalakrishnan *[image: ?] *Developer* From palani at vahaitech.com Tue Nov 8 09:47:34 2016 From: palani at vahaitech.com (Palanikumar Gopalakrishnan) Date: Tue, 8 Nov 2016 20:17:34 +0530 Subject: [Tutor] Fwd: IndentationError: unexpected indent In-Reply-To: References: Message-ID: Hi Guys, I tried this code from internet, Its returns following please guide me to solve this error * passwordFile = open('File.txt') secretPassword = passwordFile.read() print('Enter your password.') typedPassword = input() if typedPassword == secretPassword: print('Access granted') if typedPassword == '12345': print('That password is one that an idiot puts on their luggage.') else: print('Access denied')* -- *Warm Regards,* *Palanikumar Gopalakrishnan *[image: ?] *Developer* -- *Warm Regards,* *Palanikumar Gopalakrishnan *[image: ?] *Developer* From alan.gauld at yahoo.co.uk Tue Nov 8 11:09:57 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 8 Nov 2016 16:09:57 +0000 Subject: [Tutor] Fwd: IndentationError: unexpected indent In-Reply-To: References: Message-ID: On 08/11/16 14:47, Palanikumar Gopalakrishnan wrote: > Hi Guys, > I tried this code from internet, Its returns following please > guide me to solve this error > > * passwordFile = open('File.txt') secretPassword = > passwordFile.read() print('Enter your password.') typedPassword = input() > if typedPassword == secretPassword: print('Access granted') if > typedPassword == '12345': print('That password is one that an idiot > puts on their luggage.') else: print('Access denied')* Since the code has no indentation at all I assume you have posted in HTML or somesuch. You need to post using plain text so we can see the indentation. Also do not summarize the error but post the full error text. -- 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 Joaquin.Alzola at lebara.com Tue Nov 8 10:01:54 2016 From: Joaquin.Alzola at lebara.com (Joaquin Alzola) Date: Tue, 8 Nov 2016 15:01:54 +0000 Subject: [Tutor] Fwd: IndentationError: unexpected indent In-Reply-To: References: Message-ID: >Subject: [Tutor] Fwd: IndentationError: unexpected indent You are using a mixture of space and tabs or number of spaces. The exception give you the line that has the problem. --- Joaquin This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt. From bryonadams at openmailbox.org Wed Nov 9 17:30:20 2016 From: bryonadams at openmailbox.org (Bryon Adams) Date: Wed, 9 Nov 2016 17:30:20 -0500 Subject: [Tutor] Question About the .format Method. Message-ID: <4e14aabe-67e6-31b7-4c3e-42609a62e12a@openmailbox.org> Hello, Working on a simple function to get an IP address and make it look pretty for the PyNet course. I'm wondering if there's way to evenly space text with the string.format() method similar to how I'm doing it with the % operator. The last two prints keep everything left aligned and 20 spaces wide. Is there a way to accomplish this with the .format() method that I use in the first print function? # Getting the IP address and putting it into list ip4 = input('Please enter a /24 network address: ') ip4 = ip4.split('.') # Split string into a list ip4 = ip4[:3] # Force list to be a /24 network address ip4.append('0') print('{}.{}.{}.{}'.format(ip4[0], ip4[1], ip4[2], ip4[3])) ip4_str = '.'.join(ip4) ip4_bin = bin(int(ip4[0])) ip4_hex = hex(int(ip4[0])) # Printing the table print('\n'+'---------------------------------------------------------') print('%-20s %-20s %-20s' %('NETWORK_NUMBER', 'FIRST_OCTET_BINARY', 'FIRST_OCTET_HEX')) print('%-20s %-20s %-20s' %(ip4_str, ip4_bin, ip4_hex)) PS. I realise the first print can be simplified with a .join but I forgot about .join and left it to help illustrate my question. Thanks, Bryon From mrjordie at hotmail.com Wed Nov 9 19:18:45 2016 From: mrjordie at hotmail.com (Jordan Trudell) Date: Thu, 10 Nov 2016 00:18:45 +0000 Subject: [Tutor] Python Script Message-ID: Hello, I need help running a script, as I am getting an error. Is it possible if I could get help with it? Please reply if so. From __peter__ at web.de Thu Nov 10 04:08:54 2016 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Nov 2016 10:08:54 +0100 Subject: [Tutor] Question About the .format Method. References: <4e14aabe-67e6-31b7-4c3e-42609a62e12a@openmailbox.org> Message-ID: Bryon Adams wrote: > Hello, > Working on a simple function to get an IP address and make it look > pretty for the PyNet course. I'm wondering if there's way to evenly > space text with the string.format() method similar to how I'm doing it > with the % operator. The last two prints keep everything left aligned > and 20 spaces wide. Is there a way to accomplish this with the .format() > method that I use in the first print function? You can left-align, center or right-align with format(): >>> print("| {:<12} | {:^12} | {:>12} |".format("left", "center", "right")) | left | center | right | The default is right-align for numbers and left-align for strings: >>> "{:12}".format(42) ' 42' >>> "{:12}".format("42") '42 ' You can find the details here: From alan.gauld at yahoo.co.uk Thu Nov 10 04:10:56 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 10 Nov 2016 09:10:56 +0000 Subject: [Tutor] Python Script In-Reply-To: References: Message-ID: On 10/11/16 00:18, Jordan Trudell wrote: > Hello, I need help running a script, as I am getting an error. OK, But we need to know what version of Python and which OS you use. Also post the script and the full error message you get. (Don't send attachments because they usually get stripped by the server, paste the text into your mail and send as plain text not html.) Finally, it might help if you tell us exactly how you are trying to run the script. -- 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 yahoo.co.uk Thu Nov 10 04:20:10 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 10 Nov 2016 09:20:10 +0000 Subject: [Tutor] Question About the .format Method. In-Reply-To: <4e14aabe-67e6-31b7-4c3e-42609a62e12a@openmailbox.org> References: <4e14aabe-67e6-31b7-4c3e-42609a62e12a@openmailbox.org> Message-ID: On 09/11/16 22:30, Bryon Adams wrote: > Hello, > Working on a simple function to get an IP address and make it look > pretty for the PyNet course. I'm wondering if there's way to evenly > space text with the string.format() method similar to how I'm doing it > with the % operator. Yes, read section 6.1.3 of the documentation https://docs.python.org/3/library/string.html#formatstrings You can do everything that % formatting can do, and some more. See the examples in section 6.1.3.2 -- 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 bschindl at scad.edu Thu Nov 10 08:08:14 2016 From: bschindl at scad.edu (Brian Schindler) Date: Thu, 10 Nov 2016 08:08:14 -0500 (EST) Subject: [Tutor] MEL to Python Translation of array index in conditional statement Message-ID: <768596933.35798402.1478783294945.JavaMail.zimbra@scad.edu> I'm trying to convert the following code from MEL (Maya Embedded Language) to Python and having trouble with syntax errors in the conditional statement. Could you help me out? float $pos[3] = `xform -q -rp $obj`; if ($pos[0] != 0 || $pos[1] != 0 || $pos[2] != 0) Brian Schindler Professor of Animation School of Digital Media Savannah College of Art and Design? Office: 912.525.8528 Fax: 912.525.8597 bschindl at scad.edu SCAD: The University for Creative Careers? NOTICE: This e-mail message and all attachments transmitted with it may contain legally privileged and confidential information intended solely for the use of the addressee. If the reader of this message is not the intended recipient, you are hereby notified that any reading, dissemination, distribution, copying, or other use of this message or its attachments is strictly prohibited. If you have received this message in error, please notify the sender immediately by telephone or by electronic mail and then delete this message and all copies and backups thereof. Thank you. From __peter__ at web.de Thu Nov 10 13:19:58 2016 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Nov 2016 19:19:58 +0100 Subject: [Tutor] MEL to Python Translation of array index in conditional statement References: <768596933.35798402.1478783294945.JavaMail.zimbra@scad.edu> Message-ID: Brian Schindler wrote: > I'm trying to convert the following code from MEL (Maya Embedded Language) > to Python and having trouble with syntax errors in the conditional > statement. What did you try? > Could you help me out? > > float $pos[3] = `xform -q -rp $obj`; > if ($pos[0] != 0 || $pos[1] != 0 || $pos[2] != 0) I don't know MEL. Is xform a commandline tool? In that case you might need something along the lines of output = subprocess.Popen( ["xform", "-q", "-rp", obj], stdout=subprocess.PIPE).communicate()[0] pos = [float(s) for s in output.split()] if pos[0] or pos[1] or pos[2]: ... # whatever > Brian Schindler > Professor of Animation Well, what can I say -- it's never too late to read . Or if you prefer the classics;) From steve at pearwood.info Thu Nov 10 16:57:12 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 11 Nov 2016 08:57:12 +1100 Subject: [Tutor] MEL to Python Translation of array index in conditional statement In-Reply-To: <768596933.35798402.1478783294945.JavaMail.zimbra@scad.edu> References: <768596933.35798402.1478783294945.JavaMail.zimbra@scad.edu> Message-ID: <20161110215704.GH3365@ando.pearwood.info> On Thu, Nov 10, 2016 at 08:08:14AM -0500, Brian Schindler wrote: > I'm trying to convert the following code from MEL (Maya Embedded > Language) to Python and having trouble with syntax errors in the > conditional statement. Could you help me out? Only if you help us to help you. I don't know MEL and don't know how to read the following: > float $pos[3] = `xform -q -rp $obj`; > if ($pos[0] != 0 || $pos[1] != 0 || $pos[2] != 0) and chances are nobody else here does either. Can you explain in words what it does? If you're getting an error, best to show us the code you tried and the FULL error you are getting (copy and paste it please, as text, don't post a screenshot). I'm going to take a wild guess that the code means something like: pos = an array of four values if pos[0] != 0 or pos[1] != 0 or pos[2] != 0 then: call an external program xform with arguments -q -rp obj convert the result to a floating point value set pos[3] to that number which would be something similar to: import subprocess if any(pos[:3]): output = subprocess.check_output(['xform', '-q', '-rp', obj]) pos[3] = float(output) -- Steve From alan.gauld at yahoo.co.uk Thu Nov 10 20:09:41 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 11 Nov 2016 01:09:41 +0000 Subject: [Tutor] MEL to Python Translation of array index in conditional statement In-Reply-To: <768596933.35798402.1478783294945.JavaMail.zimbra@scad.edu> References: <768596933.35798402.1478783294945.JavaMail.zimbra@scad.edu> Message-ID: On 10/11/16 13:08, Brian Schindler wrote: > I'm trying to convert the following code from MEL (Maya Embedded Language) > to Python You'll probably get better support fromthe Maya community than here since most of us don;'t know anything about Maya's language. > and having trouble with syntax errors in the conditional statement. > float $pos[3] = `xform -q -rp $obj`; > if ($pos[0] != 0 || $pos[1] != 0 || $pos[2] != 0) That is presumably the Maya code? Unfortunately I don't know exactly what it does - I can make a guess but that's all it would be. For example, is the indentation on line 2 significant? (It would be in python) I'm guessing the backtick(`) mean you are executing an OS command? If so you'll need the python subprocess module to do the equivalent. If the 2nd line does what I think, the equivalent Python code would be something like: if pos[0] or pos[1] or pos[2]: # do something here Can you show us what you tried and what error message(s) you got(in full)? -- 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 yahoo.co.uk Tue Nov 15 20:14:14 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 16 Nov 2016 01:14:14 +0000 Subject: [Tutor] Please ignore: just testing Message-ID: <6961c5e3-713a-2211-6bd4-831e002ffb60@yahoo.co.uk> The group seems unusually quiet so I'm just testing the server is working ok.... -- 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 guest0x013 at gmail.com Wed Nov 16 13:48:01 2016 From: guest0x013 at gmail.com (Freedom Peacemaker) Date: Wed, 16 Nov 2016 19:48:01 +0100 Subject: [Tutor] please help me with after method Message-ID: Hi, i need help. I am using Python 3.4 and I have wrote little app for windows only ( windows 7 and higher). Its timer and my app working but not good. Some people said that i should use after method instead of update() and nobody told me how. Ive tried many times but i dont know how do it correctly. Please help me improve my app. When you run app first enter minutes in entry then press start. If you first press start your pc will shutdown with no time to stop it my code: from tkinter import * import tkinter as tk import time, os def startCount(): setTime = setMinutes.get() * 60 strTime = str(setTime) timeSet = ("\""+"shutdown /s /f /t " +strTime+"\"") os.system(timeSet) for t in range(setTime, -1, -1): lcd = "{:02d}:{:02d}".format(*divmod(t, 60)) timeString.set(lcd) try: root.update() except TclError: messagebox.showinfo('Info', 'Closing app wont stop timer.') return time.sleep(1) return root = tk.Tk() setMinutes = IntVar() timeString = StringVar() label_font = ('Verdana', 30) root.geometry('210x120+200+200') root.title('Timer v1.0') root.resizable(0, 0) L1 = tk.Label(root, text='How much time you have?') L1.grid(row=0, columnspan=3, sticky='WE') L2 = tk.Label(root, textvariable=timeString, font=label_font, bg='white', fg='orange', relief='raised', bd=3) L2.grid(row=1, columnspan=3, sticky='WE', padx=5, pady=5) E1 = tk.Entry(root, textvariable=setMinutes).grid(row=2, column=1, padx=5, pady=5) B1 = tk.Button(root, text='S T A R T', fg='green', bg='black', command=startCount) B1.grid(row=2, rowspan=2, sticky='NS', column=0, padx=5, pady=5) root.mainloop() From omarilamar at gmail.com Wed Nov 16 17:51:26 2016 From: omarilamar at gmail.com (Omari Lamar) Date: Wed, 16 Nov 2016 17:51:26 -0500 Subject: [Tutor] Python Help Message-ID: Good Day, I am looking for assistance with the python language. Can you send out an eblast asking that if anyone can offer 1 on 1 assistance via skype to cover the basics that would be greatly appreciated. -- Omari Lamar Creating My Future From ben+python at benfinney.id.au Wed Nov 16 18:33:13 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 17 Nov 2016 10:33:13 +1100 Subject: [Tutor] Python Help References: Message-ID: <854m3757ba.fsf@benfinney.id.au> Omari Lamar writes: > I am looking for assistance with the python language. Yes, we offer that here. You need to ask your question in this forum and volunteers will collaborate to teach you, in public. This way many other people can also benefit from observing the discussion. > Can you send out an eblast asking that if anyone can offer 1 on 1 > assistance via skype to cover the basics that would be greatly > appreciated. What rate are you willing to pay for one-on-one real-time interaction? That is rather less beneficial to the community and quite a drain on one person's time, so you can expect to pay handsomely for it. Instead I would recommend you take the opportunity of collaborative tutoring by public discussion here. -- \ ?I have a large seashell collection, which I keep scattered on | `\ the beaches all over the world. Maybe you've seen it.? ?Steven | _o__) Wright | Ben Finney From alan.gauld at yahoo.co.uk Wed Nov 16 19:03:37 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 17 Nov 2016 00:03:37 +0000 Subject: [Tutor] please help me with after method In-Reply-To: References: Message-ID: On 16/11/16 18:48, Freedom Peacemaker wrote: > Hi, i need help. I am using Python 3.4 and I have wrote little app for > windows only ( windows 7 and higher). Its timer and my app working but not > good. Some people said that i should use after method instead of update() after() executes a function after a delay. In your case you could use it to trigger an immediate shutdown after the delay elapses. But I'm not sure that would be much better than doing what you are doing. The other use of after is to avoid loops in event handlers such as the one you have here. This allows control to return to the GUI window. See below... > When you run app first enter minutes in entry then press start. If you > first press start your pc will shutdown with no time to stop it You can fix that by setting a default value for the time. But you still need to write some code to cancel the shutdown (by killing the process perhaps?) > def startCount(): > setTime = setMinutes.get() * 60 > strTime = str(setTime) > timeSet = ("\""+"shutdown /s /f /t " +strTime+"\"") > os.system(timeSet) Up to here is fine but you don't want a long running loop inside an event handler. Although, in this case, it probably doesn't run for long, it just counts down very quickly. Instead you want it to count down every second or so. So you want to call a function that displays the time remaining then calls after() with a delay of 1 second. The call to after should have the same function in it. Like so: def displayCountdown(): # display the time here # decrement the time by 1 second # if any time remains: # call after(1000,displayCountdown) # 1000ms = 1s Note that after only needs the function name, don't include any parentheses. > for t in range(setTime, -1, -1): > lcd = "{:02d}:{:02d}".format(*divmod(t, 60)) > timeString.set(lcd) > try: > root.update() > except TclError: > messagebox.showinfo('Info', 'Closing app wont stop timer.') > return > time.sleep(1) > return 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 yahoo.co.uk Wed Nov 16 19:09:44 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 17 Nov 2016 00:09:44 +0000 Subject: [Tutor] Python Help In-Reply-To: References: Message-ID: On 16/11/16 22:51, Omari Lamar wrote: > I am looking for assistance with the python language. Can you send out an > eblast asking that if anyone can offer 1 on 1 assistance via skype to cover > the basics that would be greatly appreciated. Further to Bens message, we don't offer private 1-1 tutoring but simply answer questions and expolain issues on the public mailing list. Take a look at the list archives to see how it works. If you want to contribute to the community by asking questions on the list please comply with the following for best results: 1) Tell us the OS and Python version 2) Show us the code and the full error text, if any. 3) Explain in simple English(avoiding technical jargon if possible) what you don't understand (eg what you expected to happen and what actually happened) 4) Post in plain text not HTML. The latter causes Python code to become badly formatted and makes reading it difficult. 5) Don't send attachments, cut 'n paste text into the message. It looks like a lot but it will help you get better quality answers much faster. -- 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 yahoo.co.uk Thu Nov 17 17:07:49 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 17 Nov 2016 22:07:49 +0000 Subject: [Tutor] please help me with after method In-Reply-To: References: Message-ID: <053292a7-23d8-c716-0afb-278f132207d1@yahoo.co.uk> Always use REply-All or Reply-List to the tutor list. On 17/11/16 18:34, Freedom Peacemaker wrote: > Thank you Alan for answer but i still cant make it. I have improved my > program but it still uses root.update() and now my app looks > professional :) It is my first program. I am self learning Python > since july this year but still i need a lot of knowledge. Could you > help me improve my app with root.after? OK, I'll try. > And there is problem - when im closing app with X button after using > app it shows two windows. One with messagebox i wrote, and second > blank new tk window. I dont know where im doing mistake, or it is > caused by root.update maybe? Maybe with using root.after problem will > be no more. Maybe, but I'll need to look at the code more closely. There are a couple of things that could cause this.... Having looked, I think you need to bind the window manager close button to root.quit Take a look at the wm_xxxx methods in the Tkinter docs. > > def displayCountdown(): > lcd = "{:02d}:{:02d}".format(*divmod(t, 60)) > timeString.set(lcd) > setTime -= 1 > if setTime > 0: > root.after(1000,displayCountdown) > Where is 't' (used in the divmod) defined? Looking below I think it should use setTime? Otherwise it looks like it should work. All you need to do is insert a call to displayCountdown() in your START button event handler. > There are problems with my app but im so proud that i wrote myself Its rare that anything is ever perfect but the buzz of getting something to work more or less as you want it to is always good. :-) > import sys, time, os > import tkinter as tk > from tkinter import * > You should probably only ose one of the tkinter imports. And the first is the preferred method for production code. > def change_1(): > B1['state'] = tk.DISABLED > B2['state'] = tk.NORMAL > > def change_2(): > B1['state'] = tk.NORMAL > B2['state'] = tk.DISABLED > > def change_3(): > B1['state'] = tk.DISABLED > B2['state'] = tk.DISABLED Add the displayCountdown() definition here > > def startCount(): > setTime = setMinutes.get() * 60 > strTime = str(setTime) > timeSet = ("\""+"shutdown /s /f /t " +strTime+"\"") > os.system(timeSet) > change_1() displayCountdown() # uses the after() method. This removes the need for all of the code below. > for t in range(setTime, -1, -1): > lcd = "{:02d}:{:02d}".format(*divmod(t, 60)) > timeString.set(lcd) > try: > root.update() > except TclError: > messagebox.showinfo('Info', 'Closing app wont stop timer.') > return > time.sleep(1) > return > The rest of your code is unchanged. But note I haven't tested this! :-) > def stopCount(): > passwd = "science" > passwdGet = getPass.get() > if passwd != passwdGet: You could make this more secure. You should probably do some reading about best [practice for handling passwords. But for now it probably meets your needs. > messagebox.showinfo('Wrong', 'It wasnt correct password') > change_3() > else: > messagebox.showinfo('Good', 'Shutdown canceled') > os.system("shutdown /a") > change_2() > return > > root = tk.Tk() > setMinutes = IntVar() > getPass = StringVar() > timeString = StringVar() > label_font = ('Verdana', 30) > root.geometry('260x150+200+200') > root.title('Timer v1.4') > root.resizable(0, 0) > > L1 = tk.Label(root, text='How much time you have?') > L1.grid(row=0, columnspan=3, sticky='WE') > > L2 = tk.Label(root, textvariable=timeString, font=label_font, bg='white', > fg='orange', relief='raised', bd=3) > L2.grid(row=1, columnspan=3, sticky='WE', padx=5, pady=5) > > E1 = tk.Entry(root, textvariable=setMinutes, bg='lightgreen') > E1.grid(row=2, column=1, padx=5, pady=5) > > B1 = tk.Button(root, text='S T A R T', fg='green', bg='black', > command=startCount) > B1.grid(row=2, rowspan=2, sticky='NS', column=0, padx=5, pady=5) > > E2 = tk.Entry(root, textvariable=getPass, bg='red') > E2.grid(row=3, column=1, padx=5, pady=5) > > B2 = tk.Button(root, text='S T O P', fg='red', bg='black', > command=stopCount, > state=tk.DISABLED) > B2.grid(row=2, rowspan=2, sticky='NS', column=2, padx=5, pady=5) > > root.mainloop() > > > > 2016-11-17 1:03 GMT+01:00 Alan Gauld via Tutor >: > > On 16/11/16 18:48, Freedom Peacemaker wrote: > > Hi, i need help. I am using Python 3.4 and I have wrote little > app for > > windows only ( windows 7 and higher). Its timer and my app > working but not > > good. Some people said that i should use after method instead of > update() > > after() executes a function after a delay. > In your case you could use it to trigger an > immediate shutdown after the delay elapses. > But I'm not sure that would be much better > than doing what you are doing. > > The other use of after is to avoid loops in > event handlers such as the one you have here. > This allows control to return to the GUI window. > > See below... > > > When you run app first enter minutes in entry then press start. > If you > > first press start your pc will shutdown with no time to stop it > > You can fix that by setting a default value for the time. > But you still need to write some code to cancel the shutdown > (by killing the process perhaps?) > > > def startCount(): > > setTime = setMinutes.get() * 60 > > strTime = str(setTime) > > timeSet = ("\""+"shutdown /s /f /t " +strTime+"\"") > > os.system(timeSet) > > Up to here is fine but you don't want a long running loop > inside an event handler. Although, in this case, it probably > doesn't run for long, it just counts down very quickly. > > Instead you want it to count down every second or so. > > So you want to call a function that displays the time > remaining then calls after() with a delay of 1 second. > The call to after should have the same function in it. > Like so: > > def displayCountdown(): > # display the time here > # decrement the time by 1 second > # if any time remains: > # call after(1000,displayCountdown) # 1000ms = 1s > > Note that after only needs the function name, don't > include any parentheses. > > > for t in range(setTime, -1, -1): > > lcd = "{:02d}:{:02d}".format(*divmod(t, 60)) > > timeString.set(lcd) > > try: > > root.update() > > except TclError: > > messagebox.showinfo('Info', 'Closing app wont stop > timer.') > > return > > time.sleep(1) > > return > > > 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 > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > > -- 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 yahoo.co.uk Thu Nov 17 19:05:26 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 18 Nov 2016 00:05:26 +0000 Subject: [Tutor] please help me with after method In-Reply-To: <053292a7-23d8-c716-0afb-278f132207d1@yahoo.co.uk> References: <053292a7-23d8-c716-0afb-278f132207d1@yahoo.co.uk> Message-ID: On 17/11/16 22:07, Alan Gauld via Tutor wrote: >> def displayCountdown(): >> lcd = "{:02d}:{:02d}".format(*divmod(t, 60)) >> timeString.set(lcd) >> setTime -= 1 >> if setTime > 0: >> root.after(1000,displayCountdown) >> > > Where is 't' (used in the divmod) defined? Looking below I think > it should use setTime? Also, because you modify setTime, you need to declare it as global. So the function should look like: def displayCountdown(): global setTime lcd = "{:02d}:{:02d}".format(*divmod(setTime, 60)) timeString.set(lcd) setTime -= 1 if setTime > 0: root.after(1000,displayCountdown) -- 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 bryonadams at openmailbox.org Fri Nov 18 16:00:31 2016 From: bryonadams at openmailbox.org (Bryon Adams) Date: Fri, 18 Nov 2016 16:00:31 -0500 Subject: [Tutor] Variable Question Message-ID: <135009f0-2062-35c3-c552-7a46da75f5d2@openmailbox.org> Hello, Variable throwing me off in a script I'm running on Python3.5, on Fedora 24. I take four strings and create a list of them. In my below code, if I print out prefix and as_path, both give me the same (I included the output below). What causes this behavior? Is this just how Python is handling the variables in memory and I'm actually working on 'entries' each time? I fixed it already by changing how I assign prefix and as_path. # Given 'show ip bgp' entry1 = "* 1.0.192.0/18 157.130.10.233 0 701 38040 9737 i" entry2 = "* 1.1.1.0/24 157.130.10.233 0 701 1299 15169 i" entry3 = "* 1.1.42.0/24 157.130.10.233 0 701 9505 17408 2.1465 i" entry4 = "* 1.0.192.0/19 157.130.10.233 0 701 6762 6762 6762 6762 38040 9737 i" entries = [entry1.split(), entry2.split(), entry3.split(), entry4.split()] prefix = entries as_path = entries n = 0 for i in prefix: prefix[n] = prefix[n][1] n += 1 print(prefix) print(as_path) [bryon at fedberry ~/pynet]$ python3 week3-2.py ['1.0.192.0/18', '1.1.1.0/24', '1.1.42.0/24', '1.0.192.0/19'] ['1.0.192.0/18', '1.1.1.0/24', '1.1.42.0/24', '1.0.192.0/19'] 192.0/1 1.0/2 42.0/2 192.0/1 Thanks, Bryon From alan.gauld at yahoo.co.uk Fri Nov 18 20:16:08 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 19 Nov 2016 01:16:08 +0000 Subject: [Tutor] Variable Question In-Reply-To: <135009f0-2062-35c3-c552-7a46da75f5d2@openmailbox.org> References: <135009f0-2062-35c3-c552-7a46da75f5d2@openmailbox.org> Message-ID: On 18/11/16 21:00, Bryon Adams wrote: > Fedora 24. I take four strings and create a list of them. In my below > code, if I print out prefix and as_path, both give me the same Because they are the same. They are both references to entries. > included the output below). What causes this behavior? Is this just how > Python is handling the variables in memory and I'm actually working on > 'entries' each time? Yes, Python variables are just labels attached to objects. In this case the label 'entries' is applied to a list of lists. Then you create the labels 'prefix' and 'as_path' and assign them to the same list object. > entries = [entry1.split(), entry2.split(), entry3.split(), entry4.split()] > prefix = entries > as_path = entries All 3 names refer to the same underlying object. > n = 0 > for i in prefix: > prefix[n] = prefix[n][1] > n += 1 This would be slightly prettier written as: for index, item in enumerate(prefix): prefix[index] = item[1] -- 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 bryonadams at openmailbox.org Sat Nov 19 14:50:40 2016 From: bryonadams at openmailbox.org (Bryon Adams) Date: Sat, 19 Nov 2016 14:50:40 -0500 Subject: [Tutor] Variable Question In-Reply-To: References: <135009f0-2062-35c3-c552-7a46da75f5d2@openmailbox.org> Message-ID: On 11/18/2016 08:16 PM, Alan Gauld via Tutor wrote: > for index, item in enumerate(prefix): > prefix[index] = item[1] > > I forgot about enumerate! That helped me clean up and actually finish my next exercise as I was having trouble working for my lists the way I was previously. Thank you very much =) From __peter__ at web.de Sun Nov 20 04:25:11 2016 From: __peter__ at web.de (Peter Otten) Date: Sun, 20 Nov 2016 10:25:11 +0100 Subject: [Tutor] Variable Question References: <135009f0-2062-35c3-c552-7a46da75f5d2@openmailbox.org> Message-ID: Bryon Adams wrote: > On 11/18/2016 08:16 PM, Alan Gauld via Tutor wrote: >> for index, item in enumerate(prefix): >> prefix[index] = item[1] >> >> > > I forgot about enumerate! That helped me clean up and actually finish my > next exercise as I was having trouble working for my lists the way I was > previously. > > Thank you very much =) enumerate() is a useful tool, but given the code you provide in your original post I recommend that you build a new list rather than modifying the existing one: prefix = [] for item in entries: prefix.append(item[1]) The above is such a common pattern that Python offers syntactic sugar called "list comprehension" to write this: prefix = [item[1] for item in entries] In both cases the original entries list is not changed. From thorsten at thorstenkampe.de Sun Nov 20 04:38:46 2016 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 20 Nov 2016 10:38:46 +0100 Subject: [Tutor] Generic dictionary Message-ID: [Crossposted to tutor and general mailing list] Hi, I'd like to extend the dictionary class by creating a class that acts like a dictionary if the class is instantiated with a dictionary and acts like a "dictitem" ([(key1, value1), (key2, value2), ...]) if instantiated with a list (that is dictitem). The code (see extract at bottom) works well but it contains a lot of "if this is a dictionary then do as a dictionary already does" boilerplate code". How can I "inherit"(?)/"subclass"(?)/derive from dict so I don't have to write the code for the dictionary case? Thorsten ``` class GenericDict: """ a GenericDict is a dictionary or a list of tuples (when the keys are not hashable) """ def __init__(inst, generic_dict): inst._generic = generic_dict def __getitem__(inst, key): if isinstance(inst._generic, dict): return inst._generic[key] else: return inst.values()[inst.keys().index(key)] def values(inst): if isinstance(inst._generic, dict): return inst._generic.values() else: try: return list(zip(*inst._generic))[1] except IndexError: # empty GenericDict return () def keys(inst): if isinstance(inst._generic, dict): return inst._generic.keys() else: try: return list(zip(*inst._generic))[0] except IndexError: # empty GenericDict return () ``` From bfishbein79 at gmail.com Tue Nov 22 19:33:35 2016 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Tue, 22 Nov 2016 18:33:35 -0600 Subject: [Tutor] how to move an executable into path Message-ID: Everything was going fine with my selenium webdriver programs, but then today I updated to Firefox 50. Everything stopped working. So I updated to selenium 3, hoping this would work. But apparently I need something called geckodriver. I managed to download this, but it?s in the wrong place: in my downloads folder. So here?s what happens when I try to do anything with selenium: >>> from selenium import webdriver >>> driver=webdriver.Firefox() Traceback (most recent call last): File "", line 1, in driver=webdriver.Firefox() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 135, in __init__ self.service.start() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 71, in start os.path.basename(self.path), self.start_error_message) WebDriverException: Message: 'geckodriver' executable needs to be in PATH. So I?m not sure where the geckodriver file needs to go. Can it be anywhere on the path? could I just put it in the site-packages folder for example? And here?s the big problem: all of these folders are hidden, and I have no idea how to get into them. I?m on a mac and using python2.7. I should probably learn how to handle paths and file systems, etc., but right now I just want to get my programs running again. Any help is greatly appreciated. -Ben From monikajg at netzero.net Wed Nov 23 01:09:16 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Wed, 23 Nov 2016 06:09:16 GMT Subject: [Tutor] __getitem__ Message-ID: <20161122.220916.14422.0@webmail11.dca.untd.com> Hi: Can you please explain __getitem__? My understanding is that it brings back dictionary's value. Is this correct? If so which value does it bring? Does it look up this value by using a key? Where is this key specified in " numbers.__getitem__" ? The below supposedly brings back dictionary's keys list sorted by values. But how does it do it? numbers = {'first': 1, 'second': 2, 'third': 3, 'Fourth': 4} sorted(numbers, key=numbers.__getitem__) Thank you very much Monika ____________________________________________________________ 3 Signs You May Have a Fatty Liver [Watch] livecellresearch.com http://thirdpartyoffers.netzero.net/TGL3241/583532f442b7c32f440b1st04duc From monikajg at netzero.net Wed Nov 23 01:26:13 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Wed, 23 Nov 2016 06:26:13 GMT Subject: [Tutor] __getitem__ another problem Message-ID: <20161122.222613.14422.1@webmail11.dca.untd.com> Hi: Can you please explain what is going on below? I do not understand how numbermap.__getitem__ brings back month's key. Does numbermap.__getitem__ bring back numbermap key or value? If key then it is not consistent with my understanding of problem in my previous email. So month is sorted by numbermap values or keys? month = dict(one='January', two='February', three='March', four='April', five='May') numbermap = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} sorted(month, key=numbermap.__getitem__) ['one', 'two', 'three', 'four', 'five'] This is from: http://pythoncentral.io/how-to-sort-python-dictionaries-by-key-or-value/ ____________________________________________________________ Which Haircuts Look Exceptional on Older Women? starsgossip.com http://thirdpartyoffers.netzero.net/TGL3241/583536c537dff36c4036dst01duc From alan.gauld at yahoo.co.uk Wed Nov 23 05:05:50 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 23 Nov 2016 10:05:50 +0000 Subject: [Tutor] __getitem__ In-Reply-To: <20161122.220916.14422.0@webmail11.dca.untd.com> References: <20161122.220916.14422.0@webmail11.dca.untd.com> Message-ID: On 23/11/16 06:09, monikajg at netzero.net wrote: > Can you please explain __getitem__? __getitem__ is the operator overload for indexing. It is like the __add__() method which overloads the + operator. So if you imple,ent __add__() in your class you can add two instances together using + and Python calls your __add__() method behind the scenes. In the same way when you index a collection object (with []) Python calls the __getitem__ method behind the scenes. So for a dictionary you can access the values of the dictionary by indexing it with a key: d = {1:2,3:4} n = d[1] # calls d.__getitem__(1) resulting in n = 2 > My understanding is that it brings back dictionary's value. > Is this correct? It brings back the value of the provided key. > If so which value does it bring? > Does it look up this value by using a key? Yes. > Where is this key specified in " numbers.__getitem__" ? Either by using indexing like numbers[somekey] or by someone explicitly calling numbers.__getitem__(aKey) In your example below sorted accesses the values using the supplied function (which can be any arbitrary function that accepts an argument and returns a value.) By providing __getitem__ as the input function sorted effectively uses the dictionary values. > The below supposedly brings back dictionary's keys list sorted by values. > But how does it do it? By making the sort key the value of each dictionary key in turn > numbers = {'first': 1, 'second': 2, 'third': 3, 'Fourth': 4} > sorted(numbers, key=numbers.__getitem__) If you try it at the prompt: >>> numbers = {'first': 1, 'second': 2, 'third': 3, 'Fourth': 4} >>> sorted(numbers, key=numbers.__getitem__) ['first', 'second', 'third', 'Fourth'] You see it works. Now try without getitem: >>> sorted(numbers) ['Fourth', 'first', 'second', 'third'] This is sorted by the keys. Now lets use a different sort method to get the values: def getValue(aKey): return numbers[aKey] This uses the more familiar indexing technique to retrieve the value for a given key. We can now use this function with sorted to get the original result: >>> sorted(numbers, key = getValue) ['first', 'second', 'third', 'Fourth'] And we can miss out the separate function definition by using a lambda: >>> sorted(numbers, key = lambda ky: numbers[ky]) ['first', 'second', 'third', 'Fourth'] >>> But the authors of your example have used __getitem__ directly because it's already available...(and the indexing technique calls __getitem__ indirectly anyway). 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 yahoo.co.uk Wed Nov 23 05:09:46 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 23 Nov 2016 10:09:46 +0000 Subject: [Tutor] __getitem__ another problem In-Reply-To: <20161122.222613.14422.1@webmail11.dca.untd.com> References: <20161122.222613.14422.1@webmail11.dca.untd.com> Message-ID: On 23/11/16 06:26, monikajg at netzero.net wrote: > I do not understand how numbermap.__getitem__ brings back month's key. numbermap returns the integer corresponding to the key. That number is then used by sorted as the basis for sorting month. So for the first entry sorted receives the value 1, for the second it gets 2. and so on. It then prints the keys corresponding to those values. > month = dict(one='January', > two='February', > three='March', > four='April', > five='May') > numbermap = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} > sorted(month, key=numbermap.__getitem__) > ['one', 'two', 'three', 'four', 'five'] -- 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 anian2005 at gmail.com Wed Nov 23 07:13:26 2016 From: anian2005 at gmail.com (anish p.k) Date: Wed, 23 Nov 2016 17:43:26 +0530 Subject: [Tutor] Query regarding using coverage.py for sub-processes Message-ID: Hi, I had a query regarding the code coverage for pyhton subprocess.I was referring the below link https://coverage.readthedocs.io/en/coverage-4.2/subprocess.html I created a site customize file ./usr/lib/python2.7/site-packages/sitecustomize.py with the coed snippet import coveragecoverage.process_startup() i am wondering what is the value of COVERAGE_PROCESS_START which needs to be set. Please do let me know about the same as i am stuck with subprocess coverage generation Thanks and Regards Anish From monikajg at netzero.net Wed Nov 23 07:15:12 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Wed, 23 Nov 2016 12:15:12 GMT Subject: [Tutor] __getitem__ Message-ID: <20161123.041512.12068.0@webmail12.dca.untd.com> Hi: Thank you very much for your explanation. Just to confirm when using __getitem__ sort will go thru every key in dict and get its value and then sort according to it. Correct? Also, you wrote: ">>> sorted(numbers, key = lambda ky: numbers[ky]) " ky is input to lambda. Where does lambda get ky? what is ky value? Thank you very much Monika ---------- Original Message ---------- From: Alan Gauld via Tutor To: tutor at python.org Subject: Re: [Tutor] __getitem__ Date: Wed, 23 Nov 2016 10:05:50 +0000 On 23/11/16 06:09, monikajg at netzero.net wrote: > Can you please explain __getitem__? __getitem__ is the operator overload for indexing. It is like the __add__() method which overloads the + operator. So if you imple,ent __add__() in your class you can add two instances together using + and Python calls your __add__() method behind the scenes. In the same way when you index a collection object (with []) Python calls the __getitem__ method behind the scenes. So for a dictionary you can access the values of the dictionary by indexing it with a key: d = {1:2,3:4} n = d[1] # calls d.__getitem__(1) resulting in n = 2 > My understanding is that it brings back dictionary's value. > Is this correct? It brings back the value of the provided key. > If so which value does it bring? > Does it look up this value by using a key? Yes. > Where is this key specified in " numbers.__getitem__" ? Either by using indexing like numbers[somekey] or by someone explicitly calling numbers.__getitem__(aKey) In your example below sorted accesses the values using the supplied function (which can be any arbitrary function that accepts an argument and returns a value.) By providing __getitem__ as the input function sorted effectively uses the dictionary values. > The below supposedly brings back dictionary's keys list sorted by values. > But how does it do it? By making the sort key the value of each dictionary key in turn > numbers = {'first': 1, 'second': 2, 'third': 3, 'Fourth': 4} > sorted(numbers, key=numbers.__getitem__) If you try it at the prompt: >>> numbers = {'first': 1, 'second': 2, 'third': 3, 'Fourth': 4} >>> sorted(numbers, key=numbers.__getitem__) ['first', 'second', 'third', 'Fourth'] You see it works. Now try without getitem: >>> sorted(numbers) ['Fourth', 'first', 'second', 'third'] This is sorted by the keys. Now lets use a different sort method to get the values: def getValue(aKey): return numbers[aKey] This uses the more familiar indexing technique to retrieve the value for a given key. We can now use this function with sorted to get the original result: >>> sorted(numbers, key = getValue) ['first', 'second', 'third', 'Fourth'] And we can miss out the separate function definition by using a lambda: >>> sorted(numbers, key = lambda ky: numbers[ky]) ['first', 'second', 'third', 'Fourth'] >>> But the authors of your example have used __getitem__ directly because it's already available...(and the indexing technique calls __getitem__ indirectly anyway). 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 _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ____________________________________________________________ Affordable Wireless Plans Set up is easy. Get online in minutes. Starting at only $14.95 per month! www.netzero.net?refcd=nzmem0216 From monikajg at netzero.net Wed Nov 23 07:25:21 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Wed, 23 Nov 2016 12:25:21 GMT Subject: [Tutor] __getitem__ Message-ID: <20161123.042521.12068.1@webmail12.dca.untd.com> Hi: I have two questions in regards to below code: 1. largest is a list, not a list of lists. [('deit', 4), ('acer', 3), ('aceilmr', 2), ('arst', 2)] so why when I do largest[0] I get the whole list again, not just the first item from the list. To get the first item I have to do largest[0][0]. 2. largest = [sorted(analist, key=lambda analist: analist[1], reverse=True)] brings back the same result as: largest = [sorted(analist, key=lambda d: d[1], reverse=True)] and the same result as: largest = [sorted(analist, key=lambda x: x[1], reverse=True)] The result is: [('deit', 4), ('acer', 3), ('aceilmr', 2), ('arst', 2)] I really do not understand why and how this works. Could you please explain? in lambda x: x[1] I pass x to lambda and it does calculation of x[1] but where does it get the x, what is the value of x? why lambda x: x[1] brings the same result as lambda d: d[1] and lambda analist: analist[1] #question. have a list of words. check for anagrams #count how many anagrams there are. #do it thru dictionary #then get anagaram list which has the biggest amount of words words = ["miracle", "claimer", "care", "race", "arts", "rats", "acre","diet", "edit", "tide", "tied"] def anagram(words): d = {} for word in words: wordl = list(word) print "word as list: " , wordl wordlsorted = sorted(wordl) print "word lsit sorted: " , wordlsorted wordsorted = ''.join(wordlsorted) print "word sorted as string: ", wordsorted d[wordsorted] = d.get(wordsorted, []) + [word] print d analist = [(key , len(value)) for key, value in d.items()] print analist print "largest: ", [sorted(analist, key=lambda analist: analist[1], reverse=True)][0] largest = [sorted(analist, key=lambda analist: analist[1], reverse=True)] print type(largest) print largest[0][0] anagram(words) Thank you very much in advance for explaining this. Monika ____________________________________________________________ Eat This Junk Food To "Reverse" Dementia Nutrition and Healing http://thirdpartyoffers.netzero.net/TGL3241/58358b1017902b0f1d93st02duc From monikajg at netzero.net Wed Nov 23 07:33:46 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Wed, 23 Nov 2016 12:33:46 GMT Subject: [Tutor] __getitem__ another problem Message-ID: <20161123.043346.12068.2@webmail12.dca.untd.com> So numbermap.__getitem__ brings back 1, then 2,then 3, then 4. Then it looks up 1 ,2, 3, 4 in month but there is no key with value 1, 2, or or in 4. What am I missing? Thank you very much Monika ---------- Original Message ---------- From: Alan Gauld via Tutor To: tutor at python.org Subject: Re: [Tutor] __getitem__ another problem Date: Wed, 23 Nov 2016 10:09:46 +0000 On 23/11/16 06:26, monikajg at netzero.net wrote: > I do not understand how numbermap.__getitem__ brings back month's key. numbermap returns the integer corresponding to the key. That number is then used by sorted as the basis for sorting month. So for the first entry sorted receives the value 1, for the second it gets 2. and so on. It then prints the keys corresponding to those values. > month = dict(one='January', > two='February', > three='March', > four='April', > five='May') > numbermap = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} > sorted(month, key=numbermap.__getitem__) > ['one', 'two', 'three', 'four', 'five'] -- 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 ____________________________________________________________ 7-Time Lotto Winner Reveals The Truth How To Win Any Lottery MNT http://thirdpartyoffers.netzero.net/TGL3241/58358cba68d69cba49c6st04duc From alan.gauld at yahoo.co.uk Wed Nov 23 17:17:51 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 23 Nov 2016 22:17:51 +0000 Subject: [Tutor] __getitem__ another problem In-Reply-To: <20161123.043346.12068.2@webmail12.dca.untd.com> References: <20161123.043346.12068.2@webmail12.dca.untd.com> Message-ID: On 23/11/16 12:33, monikajg at netzero.net wrote: > So numbermap.__getitem__ brings back 1, then 2,then 3, then 4. > Then it looks up 1 ,2, 3, 4 in month but there is no key with value 1, 2, or or in 4. > What am I missing? Your problem is not with getitem but with sorted. You need to read up on how sorted uses the key parameter. It basiocally iterates over the collection to be sorted applying the key function to each item in the collection in turn. It then sorts the collection based on the results. You can think of it as turning a collection of values like [v1,v2,v3] into a collection of pairs where the second item of each pair is the result of applying the key function to the value, like this: [(v1,key(v1)),(v2,key(v2)),(v3,key(v3))] And then sorting based on the second value of the pair. Finally it returns the first value of the sorted collection. Lets take an example where we define a key function called mag() for magnitude: def mag(n): return n if n>=0 else -n numbers = [1,-5,2,-4] Now if we apply sorted(numbers,mag) sorted iterates over numbers calling mag(n) for each number to get: [(1,1),(-5,5),(2,2),(-4,4)] And then sorts that list based on the second value of each pair: [(1,1),(2,2),(-4,4),(-5,5)] And finally returns the first values of that sorted list: [1,2,-4,-5] Now your situation with a dictionary is slightly more complex because of the added mapping between keys and values. But for a dict it works the same except that the key function is passed the dictionary key each time, but the basic idea is identical. Does that 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 alan.gauld at yahoo.co.uk Wed Nov 23 17:25:08 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 23 Nov 2016 22:25:08 +0000 Subject: [Tutor] __getitem__ In-Reply-To: <20161123.042521.12068.1@webmail12.dca.untd.com> References: <20161123.042521.12068.1@webmail12.dca.untd.com> Message-ID: On 23/11/16 12:25, monikajg at netzero.net wrote: > I have two questions in regards to below code: > 1. largest is a list, not a list of lists. > [('deit', 4), ('acer', 3), ('aceilmr', 2), ('arst', 2)] > so why when I do largest[0] I get the whole list again, I don't know you will need to show us some real code. Ideally input at the >>> prompt. > 2. largest = [sorted(analist, key=lambda analist: analist[1], reverse=True)] > brings back the same result as: > largest = [sorted(analist, key=lambda d: d[1], reverse=True)] > and the same result as: > largest = [sorted(analist, key=lambda x: x[1], reverse=True)] Yes because it doesn't matter what you call the parameter of the lambda, it's like any other function: def add2(x): return x+2 def add2(y): return y+2 def add2(z): return z+2 All of these functions are identical they always do the same regardless of what you call the parameter. Remember a lambda is just a shortcut for a function key = lambda d: d[1] is identical to def key(d): return d[1] and key = lambda analist: analist[1] is identical to def key(analist): return analist[1] Just like the add2() examples it doesn't matter what name you use for the parameter. > ...but where does it get the x, what is the value of x? See my other post about how sorted() works. -- 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 monikajg at netzero.net Wed Nov 23 19:50:03 2016 From: monikajg at netzero.net (monikajg at netzero.net) Date: Thu, 24 Nov 2016 00:50:03 GMT Subject: [Tutor] __getitem__ Message-ID: <20161123.165003.15039.0@webmail06.dca.untd.com> Hi: Thank you very much for ALL your postings. They help a lot and now things make sense. Thank you Monika ---------- Original Message ---------- From: Alan Gauld via Tutor To: tutor at python.org Subject: Re: [Tutor] __getitem__ Date: Wed, 23 Nov 2016 22:25:08 +0000 On 23/11/16 12:25, monikajg at netzero.net wrote: > I have two questions in regards to below code: > 1. largest is a list, not a list of lists. > [('deit', 4), ('acer', 3), ('aceilmr', 2), ('arst', 2)] > so why when I do largest[0] I get the whole list again, I don't know you will need to show us some real code. Ideally input at the >>> prompt. > 2. largest = [sorted(analist, key=lambda analist: analist[1], reverse=True)] > brings back the same result as: > largest = [sorted(analist, key=lambda d: d[1], reverse=True)] > and the same result as: > largest = [sorted(analist, key=lambda x: x[1], reverse=True)] Yes because it doesn't matter what you call the parameter of the lambda, it's like any other function: def add2(x): return x+2 def add2(y): return y+2 def add2(z): return z+2 All of these functions are identical they always do the same regardless of what you call the parameter. Remember a lambda is just a shortcut for a function key = lambda d: d[1] is identical to def key(d): return d[1] and key = lambda analist: analist[1] is identical to def key(analist): return analist[1] Just like the add2() examples it doesn't matter what name you use for the parameter. > ...but where does it get the x, what is the value of x? See my other post about how sorted() works. -- 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 ____________________________________________________________ 3 Signs You May Have a Fatty Liver [Watch] livecellresearch.com http://thirdpartyoffers.netzero.net/TGL3241/58363984eaf793984277ast02duc From urfa.jamil at hotmail.com Thu Nov 24 18:14:20 2016 From: urfa.jamil at hotmail.com (urfa jamil) Date: Thu, 24 Nov 2016 23:14:20 +0000 Subject: [Tutor] Python code Message-ID: I need help to write a code for this problem. Please help Ask the user to enter a series of numbers. Stop reading numbers when they enter a negative number. Calculate the average of the numbers given not including the final negative number. Question 9 options: With best regards urfa jamil From alan.gauld at yahoo.co.uk Thu Nov 24 20:10:18 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 25 Nov 2016 01:10:18 +0000 Subject: [Tutor] Python code In-Reply-To: References: Message-ID: On 24/11/16 23:14, urfa jamil wrote: > I need help to write a code for this problem. > > Please help OK, But what exactly do you want help with? Have you written any code yet? If so show us. Also if you get an error message post it. > Ask the user to enter a series of numbers. Can you do this bit? Can you get the user to enter a single number and store it? > Stop reading numbers when they enter a negative number. Can you do this bit? > Calculate the average of the numbers given Can you calculate the average of a collection of numbers? > not including the final negative number. Can you exclude the last element? > Question 9 options: No idea what that means! -- 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 ben+python at benfinney.id.au Thu Nov 24 21:49:37 2016 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 25 Nov 2016 13:49:37 +1100 Subject: [Tutor] Python code References: Message-ID: <85h96w46ke.fsf@benfinney.id.au> urfa jamil writes: > I need help to write a code for this problem. We can help by discussing the solution you have written. Simply post a reply, and include the program code you wrote for solving the problem. > Please help Note that ?help? is not the same as ?write the solution for me?. You have to do the work yourself, and we can help by discussing what you've done. -- \ ?Try to learn something about everything and everything about | `\ something.? ?Thomas Henry Huxley | _o__) | Ben Finney From juan0christian at gmail.com Thu Nov 24 19:26:04 2016 From: juan0christian at gmail.com (Juan C.) Date: Thu, 24 Nov 2016 22:26:04 -0200 Subject: [Tutor] Python code In-Reply-To: References: Message-ID: On Thu, Nov 24, 2016 at 9:14 PM, urfa jamil wrote: > > I need help to write a code for this problem. > > Please help > > > Ask the user to enter a series of numbers. Stop reading numbers when they enter a negative number. Calculate the average of the numbers given not including the final negative number. > > Question 9 options: > > > > With best regards > urfa jamil > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor It seems to me that you're just passing on to us YOUR exercise, this way you won't learn a thing. Do you at least have any initial code that you tried doing yourself? From bryonadams at openmailbox.org Fri Nov 25 17:26:55 2016 From: bryonadams at openmailbox.org (Bryon Adams) Date: Fri, 25 Nov 2016 17:26:55 -0500 Subject: [Tutor] Parsing a String Message-ID: Hello, I have written a script that pulls certain bits of information out of a Cisco router's 'show version' command. The output is given in the assignment and it does work on several different routers (I tested 3 different models from work). What I did seems a bit messy to me though, would I be able to get a second opinion here? Code in it's entirety is below. I did this using Python3.5.2 on Fedora 25. #!/usr/bin/env python3 ################################################################ # November 24, 2016 # # Take the given string for 'show version' on a Cisco router # # and return the following information: # # vendor, model, os_version, uptime, serial number # # Code should be generic and work on other versions. # # # ################################################################ sh_ver = ''' Cisco IOS Software, C880 Software (C880DATA-UNIVERSALK9-M), Version 15.0(1)M4, RELEASE SOFTWARE (fc1) Technical Support: http://www.cisco.com/techsupport Copyright (c) 1986-2010 by Cisco Systems, Inc. Compiled Fri 29-Oct-10 00:02 by prod_rel_team ROM: System Bootstrap, Version 12.4(22r)YB5, RELEASE SOFTWARE (fc1) twb-sf-881 uptime is 7 weeks, 5 days, 19 hours, 23 minutes System returned to ROM by reload at 15:33:36 PST Fri Feb 28 2014 System restarted at 15:34:09 PST Fri Feb 28 2014 System image file is "flash:c880data-universalk9-mz.150-1.M4.bin" Last reload type: Normal Reload Last reload reason: Reload Command Cisco 881 (MPC8300) processor (revision 1.0) with 236544K/25600K bytes of memory. Processor board ID FTX1000038X 5 FastEthernet interfaces 1 Virtual Private Network (VPN) Module 256K bytes of non-volatile configuration memory. 126000K bytes of ATA CompactFlash (Read/Write) License Info: License UDI: ------------------------------------------------- Device# PID SN ------------------------------------------------- *0 CISCO881-SEC-K9 FTX1000038X License Information for 'c880-data' License Level: advipservices Type: Permanent Next reboot license Level: advipservices Configuration register is 0x2102 ''' import sys # New empty dictionary to store information. router_dict = {} # Get vendor, although we know it's Cisco anyway. if 'Cisco' in sh_ver: router_dict['vendor'] = 'Cisco' else: sys.exit('This is not a Cisco device') # Split sh ver output to a list of lines lines = sh_ver.split('\n') # Get the IOS version, this parses for the string 'Cisco IOS Software', # in every line in 'lines.' It then splits the string stored in position # 0 and returns position 2 as the os version and strips off the leading # space. router_dict['os_ver'] = [i for i in lines if 'Cisco IOS Software' in i][0].split(',')[2][1:] # Get the model of router using the same logic as the IOS version. The line # doesn't have a nice split character so I rebuilt the string using spaces. router_dict['model'] = ' '.join([i for i in lines if 'bytes of memory' in i][0].split()[0:3]) # Get uptime using the same logic as 'model' router_dict['uptime'] = ' '.join([i for i in lines if 'uptime' in i][0].split()[3:]) # Get serial number using the logic from 'os_ver' router_dict['serial'] = [i for i in lines if 'Processor board ID' in i][0].split()[3] for i in router_dict: print('{:<10} {}'.format(i, router_dict.get(i))) Thanks, Bryon From bryonadams at openmailbox.org Fri Nov 25 18:07:38 2016 From: bryonadams at openmailbox.org (Bryon Adams) Date: Fri, 25 Nov 2016 18:07:38 -0500 Subject: [Tutor] Parsing a String In-Reply-To: References: Message-ID: On 11/25/2016 05:26 PM, Bryon Adams wrote: > Hello, > I have written a script that pulls certain bits of information out > of a Cisco router's 'show version' command. The output is given in the > assignment and it does work on several different routers (I tested 3 > different models from work). What I did seems a bit messy to me though, > would I be able to get a second opinion here? Code in it's entirety is > below. I did this using Python3.5.2 on Fedora 25. > > > #!/usr/bin/env python3 > ################################################################ > # November 24, 2016 # > # Take the given string for 'show version' on a Cisco router # > # and return the following information: # > # vendor, model, os_version, uptime, serial number # > # Code should be generic and work on other versions. # > # # > ################################################################ > > sh_ver = ''' > Cisco IOS Software, C880 Software (C880DATA-UNIVERSALK9-M), Version > 15.0(1)M4, RELEASE SOFTWARE (fc1) > Technical Support: http://www.cisco.com/techsupport > Copyright (c) 1986-2010 by Cisco Systems, Inc. > Compiled Fri 29-Oct-10 00:02 by prod_rel_team > ROM: System Bootstrap, Version 12.4(22r)YB5, RELEASE SOFTWARE (fc1) > twb-sf-881 uptime is 7 weeks, 5 days, 19 hours, 23 minutes > System returned to ROM by reload at 15:33:36 PST Fri Feb 28 2014 > System restarted at 15:34:09 PST Fri Feb 28 2014 > System image file is "flash:c880data-universalk9-mz.150-1.M4.bin" > Last reload type: Normal Reload > Last reload reason: Reload Command > Cisco 881 (MPC8300) processor (revision 1.0) with 236544K/25600K bytes > of memory. > Processor board ID FTX1000038X > 5 FastEthernet interfaces > 1 Virtual Private Network (VPN) Module > 256K bytes of non-volatile configuration memory. > 126000K bytes of ATA CompactFlash (Read/Write) > License Info: > License UDI: > ------------------------------------------------- > Device# PID SN > ------------------------------------------------- > *0 CISCO881-SEC-K9 FTX1000038X > License Information for 'c880-data' > License Level: advipservices Type: Permanent > Next reboot license Level: advipservices > Configuration register is 0x2102 > ''' > import sys > > # New empty dictionary to store information. > router_dict = {} > > # Get vendor, although we know it's Cisco anyway. > if 'Cisco' in sh_ver: > router_dict['vendor'] = 'Cisco' > else: > sys.exit('This is not a Cisco device') > > # Split sh ver output to a list of lines > lines = sh_ver.split('\n') > > # Get the IOS version, this parses for the string 'Cisco IOS Software', > # in every line in 'lines.' It then splits the string stored in position > # 0 and returns position 2 as the os version and strips off the leading > # space. > router_dict['os_ver'] = [i for i in lines if 'Cisco IOS Software' in > i][0].split(',')[2][1:] > > # Get the model of router using the same logic as the IOS version. The line > # doesn't have a nice split character so I rebuilt the string using > spaces. > router_dict['model'] = ' '.join([i for i in lines if 'bytes of memory' > in i][0].split()[0:3]) > > # Get uptime using the same logic as 'model' > router_dict['uptime'] = ' '.join([i for i in lines if 'uptime' in > i][0].split()[3:]) > > # Get serial number using the logic from 'os_ver' > router_dict['serial'] = [i for i in lines if 'Processor board ID' in > i][0].split()[3] > > for i in router_dict: > print('{:<10} {}'.format(i, router_dict.get(i))) > > > > Thanks, > Bryon So I checked out what the teacher had written. He wrapped everything in a for loop which makes what I have look a lot better. Relevant part below, nothing else changed other than I changed the name of a variable to make them easier to distinguish. ver_lines = sh_ver.split('\n') for line in ver_lines: if 'Cisco IOS Software' in line: router_dict['os_ver'] = line.split(',')[2][1:] if 'bytes of memory' in line: router_dict['model'] = ' '.join(line.split()[0:3]) if 'uptime' in line: router_dict['uptime'] = ' '.join(line.split()[3:]) if 'Processor board ID' in line: router_dict['serial'] = line.split()[3] From zxjhust1 at 163.com Fri Nov 25 23:59:37 2016 From: zxjhust1 at 163.com (zxjhust1) Date: Sat, 26 Nov 2016 12:59:37 +0800 (CST) Subject: [Tutor] inquiry Message-ID: | Dear tutors: I have some questions about memory mechanism of python. Do the elements of the parent go into the namespace of the subclass when we define subclass? As far as I'm concerned, they do go into the namespace of the subclass. Because when we use dir(), we can see all the elements. But there is only one 'update' name. I think the function of the subclass override the parent's. In this situation , when we instantiate the subclass, we just need one argument, that is to say, the parent's update function do the work. It confuses me. According to my understanding, as there is no 'super' key word, the 'self' should inference to the instance of the subclass when we initiate the subclass. So self.__update should inference to function of the subclass. Another quesion is about the meaning of the private variables. What condition shall we use them? In other word, I wanna know the purpose of introducing the private variables. The above-mentioned example, I think, is not enough to explain it, because when we change the __update to update, there is no change except for using update rather than _Mapping__update to inference it. The last question is about the storage of the data. For a given data, like 1 or '1', what's the form when python saves it in the memory? To be more specific, I wanna know the number of the parts we use to enclose it. For example, python uses 3 parts to save it. One is for the value. The second for the type of the data, ie, inter,str,etc. The last is for the pointer or id to show the place where it is stored. Hope to hear from you soon. Have a good weekend! Yours, sincerely. Phoenix | From anish198519851985 at gmail.com Sat Nov 26 04:07:49 2016 From: anish198519851985 at gmail.com (anish singh) Date: Sat, 26 Nov 2016 01:07:49 -0800 Subject: [Tutor] Help with Python Queue Message-ID: I was just writing to read a file using popen and wanted to use queue along with it. I have below code but it is giving this error: AttributeError: Queue instance has no attribute 'taskdone' import threading from Queue import Queue def worker(q): while True: dataset = q.get() print("q is taken out") q.taskdone() def create_data(q): print("Inside create data") output = [1, 2, 3] for i in output: print("Inside", i) print("queue is put") q.put(i) if __name__ == '__main__': q = Queue() t = threading.Thread(target=worker, args=(q,)) t.daemon = True t.start() create_data(q) q.join() From alan.gauld at yahoo.co.uk Sat Nov 26 06:41:22 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 26 Nov 2016 11:41:22 +0000 Subject: [Tutor] inquiry In-Reply-To: References: Message-ID: On 26/11/16 04:59, zxjhust1 wrote: > Dear tutors: > I have some questions about memory mechanism of python. Depending on the level of detail you need this might be more appropriate to the general Python list. Implementation details are usually a bit too advanced for most readers of tutor. However if all you want are the practical details of how to utilise the memory model this list is fine. > Do the elements of the parent go into the namespace of > the subclass when we define subclass? > > As far as I'm concerned, they do go into the namespace > of the subclass. Because when we use dir(), > we can see all the elements. > But there is only one 'update' name. I'm not sure what you mean by that? Where are you getting 'update' from? > I think the function of the subclass override the parent's. Yes that's the expected behaviour. > In this situation , when we instantiate the subclass, > we just need one argument, that is to say, > the parent's update function do the work. I think you need to post some code because what you are talking about sounds like its related to a specific example which we can't see... > According to my understanding, as there is no 'super' key word, There is a form of super in Python although it works differently in v2 and v3. Which python version are you using? And both cases work differently to Java and Smalltalk. > Another quesion is about the meaning of the private variables. Again you need to be more specific. Private attributes in Python are a bit of a bodge, more of a convention than a guarantee. > What condition shall we use them? In other word, I wanna > know the purpose of introducing the private variables. Are you familiar with OOP in other languages? That will affect how we answer that question... I have to run, hopefully someone else will picjk this up in more detail. -- 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 Sat Nov 26 07:34:43 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Nov 2016 23:34:43 +1100 Subject: [Tutor] inquiry In-Reply-To: References: Message-ID: <20161126123443.GD3365@ando.pearwood.info> Hi Phoenix, welcome! On Sat, Nov 26, 2016 at 12:59:37PM +0800, zxjhust1 wrote: > I have some questions about memory mechanism of python. Do the > elements of the parent go into the namespace of the subclass > when we define subclass? I don't quite understand your question. I *think* you are asking if the parent's attributes are copied into the subclass. The answer to that is no, they are not: py> class Parent: ... member = 'leg' ... py> class Child(Parent): ... pass ... py> print(Child.member) leg py> print('member' in vars(Child)) False The vars() function returns the namespace of the argument, so there is no attribute "member" inside the Child namespace, instead the attribute is looked up when needed. > As far as I'm concerned, they do go into the namespace of the > subclass. Because when we use dir(), we can see all the elements. But > there is only one 'update' name. I think the function of the subclass > override the parent's. In this situation , when we instantiate the > subclass, we just need one argument, that is to say, the parent's > update function do the work. It confuses me. Your question confuses me. What "update" name? Can you show a SMALL example that explains what you are talking about? The dir() function shows attribute and method names of the object, its class, and its parent classes. > According to my understanding, as there is no 'super' key word, the > 'self' should inference to the instance of the subclass when we > initiate the subclass. So self.__update should inference to function > of the subclass. I don't know what you mean by "self.__update" here, but there is an added complication when the method name starts with two underscores: name mangling. The interpreter will insert the name of the class at the front of the method. Name mangling is intended as a simple form of method protection, but in my experience it causes more problems than it solves. I'm happy to talk about name mangling more if you like, but as a beginner you will probably be much happier if you forget all about it until you have more experience. There is no "super" keyword, but there is a super() function. But beware: in Python 2 it is complicated to get right. Suppose I say: class Animal: def grow(self): print(self, 'is growing') class Mammal(Animal): pass class Dog(Mammal): pass lassie = Dog() # an instance lassie.grow() then I get something like this: <__main__.Dog object at 0xb79d0a4c> is growing So it doesn't matter which class the method is actually defined in, the instance is still a Dog instance. > Another quesion is about the meaning of the private variables. What > condition shall we use them? In other word, I wanna know the purpose > of introducing the private variables. The above-mentioned example, I > think, is not enough to explain it, because when we change the > __update to update, there is no change except for using update rather > than _Mapping__update to inference it. In some languages, like Java, programmers make a big deal about private variables. The languages enforces them as private, and then programmers typically spend hours trying to fight the language to bypass the protection. In Python, private variables are not enforced by the language. They are just a naming convention: if you name a method or attribute with a single leading underscore, like _update(), that is a sign to other people "Don't use this". It means that you reserve the right to remove the _update() method with no warning, or make it do something else. In short, as a Python programmer using classes or functions from a library, you should NEVER use anything that starts with an underscore. As a Python programmer, the only time you might use something with an underscore is if you are writing your own classes. > The last question is about the storage of the data. For a given data, > like 1 or '1', what's the form when python saves it in the memory? To > be more specific, I wanna know the number of the parts we use to > enclose it. For example, python uses 3 parts to save it. One is for > the value. The second for the type of the data, ie, inter,str,etc. The > last is for the pointer or id to show the place where it is stored. That depends on which Python interpreter you are using, and which version of Python. But all values in Python are objects. How the object is defined in memory will depend on which interpreter, which version, and which object, but they would usually have at least two internal fields: - the type of the object (an int, float, str, list, dict, etc) - the value of the object (depends on what type it is). You cannot directly access these fields from Python code. You can get the type of the object with the type() function: py> type(lassie) # remember this from before? py> type(42) py> type("hello world") Hope these answer your questions. Regards, Steve From steve at pearwood.info Sat Nov 26 07:34:43 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Nov 2016 23:34:43 +1100 Subject: [Tutor] inquiry In-Reply-To: References: Message-ID: <20161126123443.GD3365@ando.pearwood.info> Hi Phoenix, welcome! On Sat, Nov 26, 2016 at 12:59:37PM +0800, zxjhust1 wrote: > I have some questions about memory mechanism of python. Do the > elements of the parent go into the namespace of the subclass > when we define subclass? I don't quite understand your question. I *think* you are asking if the parent's attributes are copied into the subclass. The answer to that is no, they are not: py> class Parent: ... member = 'leg' ... py> class Child(Parent): ... pass ... py> print(Child.member) leg py> print('member' in vars(Child)) False The vars() function returns the namespace of the argument, so there is no attribute "member" inside the Child namespace, instead the attribute is looked up when needed. > As far as I'm concerned, they do go into the namespace of the > subclass. Because when we use dir(), we can see all the elements. But > there is only one 'update' name. I think the function of the subclass > override the parent's. In this situation , when we instantiate the > subclass, we just need one argument, that is to say, the parent's > update function do the work. It confuses me. Your question confuses me. What "update" name? Can you show a SMALL example that explains what you are talking about? The dir() function shows attribute and method names of the object, its class, and its parent classes. > According to my understanding, as there is no 'super' key word, the > 'self' should inference to the instance of the subclass when we > initiate the subclass. So self.__update should inference to function > of the subclass. I don't know what you mean by "self.__update" here, but there is an added complication when the method name starts with two underscores: name mangling. The interpreter will insert the name of the class at the front of the method. Name mangling is intended as a simple form of method protection, but in my experience it causes more problems than it solves. I'm happy to talk about name mangling more if you like, but as a beginner you will probably be much happier if you forget all about it until you have more experience. There is no "super" keyword, but there is a super() function. But beware: in Python 2 it is complicated to get right. Suppose I say: class Animal: def grow(self): print(self, 'is growing') class Mammal(Animal): pass class Dog(Mammal): pass lassie = Dog() # an instance lassie.grow() then I get something like this: <__main__.Dog object at 0xb79d0a4c> is growing So it doesn't matter which class the method is actually defined in, the instance is still a Dog instance. > Another quesion is about the meaning of the private variables. What > condition shall we use them? In other word, I wanna know the purpose > of introducing the private variables. The above-mentioned example, I > think, is not enough to explain it, because when we change the > __update to update, there is no change except for using update rather > than _Mapping__update to inference it. In some languages, like Java, programmers make a big deal about private variables. The languages enforces them as private, and then programmers typically spend hours trying to fight the language to bypass the protection. In Python, private variables are not enforced by the language. They are just a naming convention: if you name a method or attribute with a single leading underscore, like _update(), that is a sign to other people "Don't use this". It means that you reserve the right to remove the _update() method with no warning, or make it do something else. In short, as a Python programmer using classes or functions from a library, you should NEVER use anything that starts with an underscore. As a Python programmer, the only time you might use something with an underscore is if you are writing your own classes. > The last question is about the storage of the data. For a given data, > like 1 or '1', what's the form when python saves it in the memory? To > be more specific, I wanna know the number of the parts we use to > enclose it. For example, python uses 3 parts to save it. One is for > the value. The second for the type of the data, ie, inter,str,etc. The > last is for the pointer or id to show the place where it is stored. That depends on which Python interpreter you are using, and which version of Python. But all values in Python are objects. How the object is defined in memory will depend on which interpreter, which version, and which object, but they would usually have at least two internal fields: - the type of the object (an int, float, str, list, dict, etc) - the value of the object (depends on what type it is). You cannot directly access these fields from Python code. You can get the type of the object with the type() function: py> type(lassie) # remember this from before? py> type(42) py> type("hello world") Hope these answer your questions. Regards, Steve From alan.gauld at yahoo.co.uk Sat Nov 26 14:00:55 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sat, 26 Nov 2016 19:00:55 +0000 Subject: [Tutor] Help with Python Queue In-Reply-To: References: Message-ID: On 26/11/16 09:07, anish singh wrote: > I have below code but it is giving this error: > AttributeError: Queue instance has no attribute 'taskdone' Please post the full error not just a summary. Also please post the actual code... > import threading > from Queue import Queue I get an import error here with no module named Queue. Which Queue module are you using? Or should it be spelled queue? > def worker(q): > while True: > dataset = q.get() > print("q is taken out") > q.taskdone() Assuming you meant the standard queue module then that should be q.task_done() When you get an attribute error it's worth trying dir() on the offending object: >>> from queue import Queue as Q >>> dir(Q) ...., task_done,.... >>> help(Q.task_done) ... 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 anish.tambe.lists at gmail.com Sat Nov 26 08:22:43 2016 From: anish.tambe.lists at gmail.com (Anish Tambe) Date: Sat, 26 Nov 2016 18:52:43 +0530 Subject: [Tutor] Help with Python Queue In-Reply-To: References: Message-ID: > AttributeError: Queue instance has no attribute 'taskdone' Method name is task_done (not taskdone) https://docs.python.org/2/library/queue.html#Queue.Queue.task_done From Joaquin.Alzola at lebara.com Sat Nov 26 18:45:37 2016 From: Joaquin.Alzola at lebara.com (Joaquin Alzola) Date: Sat, 26 Nov 2016 23:45:37 +0000 Subject: [Tutor] Help with Python Queue In-Reply-To: References: Message-ID: >I have below code but it is giving this error: >AttributeError: Queue instance has no attribute 'taskdone' >import threading >from Queue import Queue >def worker(q): > while True: > dataset = q.get() > print("q is taken out") > q.taskdone() Per documentation it is task_done (I suppose you are using python 3+) https://docs.python.org/3.5/library/queue.html This email is confidential and may be subject to privilege. If you are not the intended recipient, please do not copy or disclose its content but contact the sender immediately upon receipt. From steve at pearwood.info Sun Nov 27 12:03:08 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Nov 2016 04:03:08 +1100 Subject: [Tutor] how to move an executable into path In-Reply-To: References: Message-ID: <20161127170306.GE3365@ando.pearwood.info> On Tue, Nov 22, 2016 at 06:33:35PM -0600, Benjamin Fishbein wrote: > Everything was going fine with my selenium webdriver programs, but > then today I updated to Firefox 50. Everything stopped working. That's what happens when you upgrade Firefox -- you get something which does more of the things you don't want, less of the things you do want, may or may not fix some security vulnerabilities, but absolutely will introduce new ones. That's called "progress". > So I updated to selenium 3, hoping this would work. But apparently I > need something called geckodriver. "Something"? Care to give a hint what it is? I'm assuming it isn't a Python library. > I managed to download this, but it?s in the wrong place: in my downloads folder. [...] > WebDriverException: Message: 'geckodriver' executable needs to be in PATH. That's not talking about the PYTHONPATH, which is the set of folders that Python looks for modules and libraries, but in your operating system's PATH, which is where the OS looks for executable programs, system libraries, and other goodies. Does Mac offer some sort of officially supported package management? If so, you should use that. On Linux, I would firstly try: sudo yum install geckodriver or sudo apt-get install geckodriver which (hopefully) would install the officially supported version. (Which, of course, might not be the version that Selenium and Firefox 50 require. There's that progress again.) But I fear that being on a Mac, any official package management is going to support Apple software and very little else. You might try googling for "Homebrew", I think that's some sort of third-party package manager for OS X. See if you can use that to install geckodriver. If not, well, things will start getting complicated fast. It depends on whether you have downloaded a binary library or the source code for geckodriver. You could try right-clicking on the file and seeing what sort of file the Finder thinks it is. Wait, Mac's don't support right-click by default. Control-click perhaps? *If* you have downloaded the source code, it will probably be in a tarball or zip file. You'll need to expand the zip file. Hopefully there will be a READ ME file in the zip file with decent instructions. If it is anything like Linux, you'll probably be told to open a shell window, cd into the directory containing the geckodriver source code, then run a series of commands like: ./configure make sudo make install Those three commands will prepare the source code, compile it, and (hopefully) place it somewhere in the PATH. If its not like Linux, well, it could be anything. (Sorry, I haven't seriously used a Mac since System 7.) On the other hand, if you have downloaded the binary library, then no compilation is required. All you need to do is insert the file in one of the system directories that is on the PATH. I have no idea how to do that on OS X. > So I?m not sure where the geckodriver file needs to go. Can it be > anywhere on the path? could I just put it in the site-packages folder > for example? No, not site-packages, because that's for Python modules, not system libraries. > And here?s the big problem: all of these folders are hidden, and I > have no idea how to get into them. Start with this: open a terminal or shell window. You will see a prompt, probably a $ sign or maybe a % sign. If you see a >>> prompt, you're in the Python interpreter. You don't want that. Type this command, and press the ENTER key: echo $PATH This will(?) print the current value of the system PATH. (At least it will on Linux -- on Mac, who knows?) Copy and paste the results here. -- Steve From alan.gauld at yahoo.co.uk Sun Nov 27 13:28:09 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 27 Nov 2016 18:28:09 +0000 Subject: [Tutor] how to move an executable into path In-Reply-To: References: Message-ID: On 23/11/16 00:33, Benjamin Fishbein wrote: > I should probably learn how to handle paths and file systems, etc., You definitely should if you intend doing any serious programming on MacOS. Learn to drive the Terminal tool and the basic Unix command line tools and you will have much more control over your Mac. Read Steve's reply because, despite its mild(?!) snarkiness about Macs (and firefox), it is full of good advice. But as a quick fix if you drag the Gecko-thingummy binary into your Applications folder it should be on your path. But that's probably not the optimal place to keep it, but it might just get you running quickly... -- 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 Sun Nov 27 19:26:33 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Nov 2016 11:26:33 +1100 Subject: [Tutor] how to move an executable into path In-Reply-To: References: Message-ID: <20161128002632.GF3365@ando.pearwood.info> On Sun, Nov 27, 2016 at 06:28:09PM +0000, Alan Gauld via Tutor wrote: > On 23/11/16 00:33, Benjamin Fishbein wrote: > > > I should probably learn how to handle paths and file systems, etc., > > You definitely should if you intend doing any serious programming > on MacOS. Learn to drive the Terminal tool and the basic Unix > command line tools and you will have much more control over > your Mac. > > Read Steve's reply because, despite its mild(?!) snarkiness > about Macs (and firefox), it is full of good advice. I fully admit some snark about Firefox. Any snarkiness about Macs were completely unintentional. I used to really like Macs, and as far as OS X goes, I don't know enough about it to justify any snarkiness. -- Steve From akleider at sonic.net Sun Nov 27 20:49:20 2016 From: akleider at sonic.net (Alex Kleider) Date: Sun, 27 Nov 2016 17:49:20 -0800 Subject: [Tutor] how to move an executable into path In-Reply-To: <20161128002632.GF3365@ando.pearwood.info> References: <20161128002632.GF3365@ando.pearwood.info> Message-ID: <9d65dd72be579f82726b903a899df925@sonic.net> On 2016-11-27 16:26, Steven D'Aprano wrote: snip.. > I fully admit some snark about Firefox. snip.. I've been using Firefox on Ubuntu for years and haven't recognized any difficulties although I don't use it for much other than email, searching, and occasionally shopping. I would be interested in knowing your browser of choice- obviously not Safari! Alex From steve at pearwood.info Sun Nov 27 21:57:03 2016 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Nov 2016 13:57:03 +1100 Subject: [Tutor] how to move an executable into path In-Reply-To: <9d65dd72be579f82726b903a899df925@sonic.net> References: <20161128002632.GF3365@ando.pearwood.info> <9d65dd72be579f82726b903a899df925@sonic.net> Message-ID: <20161128025703.GG3365@ando.pearwood.info> On Sun, Nov 27, 2016 at 05:49:20PM -0800, Alex Kleider wrote: > On 2016-11-27 16:26, Steven D'Aprano wrote: > > snip.. > > >I fully admit some snark about Firefox. > > snip.. > > I've been using Firefox on Ubuntu for years and haven't recognized any > difficulties although I don't use it for much other than email, > searching, and occasionally shopping. > > I would be interested in knowing your browser of choice- obviously not > Safari! Firefox is like democracy: its the worst browser in the world, except for all the others. I keep coming back to it because every time I change to another browser, its worse. I hate the rapid pace of upgrades that change basic functionality. A rapid pace for security upgrades is necessary. Changing the look and feel of the browser and the features, not so much. I hate that every time I upgrade Firefox, something breaks. I hate how slow and memory hungry it is, at the way that it eats memory and CPU cycles even when quitely sitting in the background, and how a single rogue website can kill the entire application. In theory, Chrome is better, since each tab exists in its own process that can be killed independently of the rest, but in practice I find that to be false advertising: I've still had the entire Chrome application crash and die. But, really, its not so much Firefox as the entire web ecosystem. I'm unhappy that people want to do everything in the browser, often poorly. I'm sad that web applications' user-interfaces are so poor. I'm angry at the large number of sites which are completely unviewable without enabling Javascript and allowing random websites to track your move. I'm sick of web adverts and tracking cookies and more nefarious tricks done by advertisers and the way that we're all supposed to just implicitly trust code downloaded from random people on the internet into our browser. I think that any web site that serves up malware disguised as advertising should be held 100% liable, plus punitive damages, and if that destroys the Internet advertising industry, good. I'd rather a tiny Internet that loses money and is trustworthy than a huge Internet that makes buckets of money for people who cannot be trusted as far as you can throw them. I'm frustrated that even though I have an Internet connection that is hundreds of times faster than I had in the 1990s, browsing is actually *slower* now because pages are hundreds of times bigger, and nearly all of that size is junk: Javascript to load trackers that load other trackers that load other trackers that load more Javascript that loads more trackers. NoScript makes this somewhat more bearable, but it is frustrating whenever I come across a page that will not load without disabling NoScript or enabling a dozen or more foreign trackers. At least Flash is on the way out. -- Steve From juan0christian at gmail.com Mon Nov 28 16:53:53 2016 From: juan0christian at gmail.com (Juan C.) Date: Mon, 28 Nov 2016 19:53:53 -0200 Subject: [Tutor] Help on Software Design decisions Message-ID: I'm a student and my university uses Moodle as their learning management system (LMS). They don't have Moodle Web Services enabled and won't be enabling it anytime soon, at least for students. The university programs have the following structure, for example: 1. Bachelor's Degree in Computer Science (duration: 8 semesters) 1.1. Unit 01: Mathematics Fundamental (duration: 1 semester) 1.1.1. Algebra I (first 3 months) 1.1.2. Algebra II (first 3 months) 1.1.3. Calculus I (last 3 months) 1.1.4. Calculus II (last 3 months) 1.1.5. Unit Project (throughout the semester) 1.2. Unit 02: Programming (duration: 1 semester) 1.2.1. Programming Logic (first 3 months) 1.2.2. Data Modelling with UML (first 3 months) 1.2.3. Python I (last 3 months) 1.2.4. Python II (last 3 months) 1.2.5. Unit Project (throughout the semester) Each course/project have a bunch of assignments + one final assignment. This goes on, totalizing 8 (eight) units, which will make up for a 4-year program. I have to build my own Moodle API to be consumed by my program, currently I'm using 'requests' + 'bs4' to do the job. I'm not here for coding help, instead I have some python software design doubts. Some information I have in mind: - I was thinking about having the following classes: Program, Unit, Course, Assignment, User. - User would handle auth + session, the rest is pretty straightforward, program would handle programs, unit would handles units, and so on. - Inside Program init there would be attributes title, id and units; inside Unit init there would be attributes title, id and courses; inside Course init there would be attributes title, id, due_date, submitted, grade. Should I call the site using requests and do all the parsing for everything using bs4 as soon as I create a new instance of User? For example: user = User('john.smith', 'password') # will get all data needed user.program # cs = user.program cs.units # , , etc. prog = cs.units[1] prog.assignments # , , , , [...], as03 = cs.assignments[2] as03.title # ''Assignment 03" as03.id # 202 as03.due_date # 2016-11-30T21:21:00+00:00 (ISO 8601) Is this a good Pythonic design? If not, how could it be better? From alan.gauld at yahoo.co.uk Mon Nov 28 20:33:24 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 29 Nov 2016 01:33:24 +0000 Subject: [Tutor] Help on Software Design decisions In-Reply-To: References: Message-ID: On 28/11/16 21:53, Juan C. wrote: > I'm a student and my university uses Moodle as their learning management > system (LMS). Never heard of it but hopefully that doesn't matter :-) > 1. Bachelor's Degree in Computer Science (duration: 8 semesters) > > 1.1. Unit 01: Mathematics Fundamental (duration: 1 semester) > 1.1.1. Algebra I (first 3 months) > 1.2. Unit 02: Programming (duration: 1 semester) > 1.2.1. Programming Logic (first 3 months) > > Each course/project have a bunch of assignments + one final assignment. > This goes on, totalizing 8 (eight) units, which will make up for a 4-year > program. > I have to build my own Moodle API to be consumed by my program, Do you have any requirements defined? APIs exist to do something, what operations does your API enable? Until you know that you can't design anything very useful. > - I was thinking about having the following classes: Program, Unit, Course, > Assignment, User. > - User would handle auth + session, the rest is pretty straightforward, > program would handle programs, unit would handles units, and so on. OK, Have you heard of CRC cards? These might be helpful here in helping you understand and express what each of these classes does. "pretty straightforward" is not helpful in designing a program, you need to give more thought to what the program actually does. And that means what each class is responsible for. > - Inside Program init there would be attributes title, id and units; inside > Unit init there would be attributes title, id and courses; inside Course > init there would be attributes title, id, due_date, submitted, grade. The attributes are there to support the operations. What are the operations (ie the responsibilities) of the classes. That will tell you what attributes you need to store, which to derive and which are references to other (user defined) objects. And which turn out not to be needed at all... > Should I call the site using requests and do all the parsing for everything > using bs4 as soon as I create a new instance of User? For example: My personal opinion here is that objects should be constructed into discrete attributes as quickly as possible so I'd vote yes. Get the parsing done early. You can always define a method to reconstruct the string if that proves necessary. BTW you are talking about calling the site but your API (as I understand the assignment) is on the server side so have you thought about how those requests will be received and dispatched? Do you need more classes to deal with that? Or is that something Moodle can do for you? > user = User('john.smith', 'password') # will get all data needed > user.program # I'm not sure what you are trying to show us here. The first line is a valid assignment statement but you are passing in valid data, no parsing required. The second line does nothing useful. > Is this a good Pythonic design? If not, how could it be better? Mainly you are asking about general OOP/OOD rather than anything Pythonic. That is not a bad thing, just a different question. -- 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 juan0christian at gmail.com Mon Nov 28 21:02:58 2016 From: juan0christian at gmail.com (Juan C.) Date: Tue, 29 Nov 2016 00:02:58 -0200 Subject: [Tutor] Help on Software Design decisions In-Reply-To: References: Message-ID: On Mon, Nov 28, 2016 at 11:33 PM, Alan Gauld via Tutor wrote: > > On 28/11/16 21:53, Juan C. wrote: > > I'm a student and my university uses Moodle as their learning management > > system (LMS). > > Never heard of it but hopefully that doesn't matter :-) > > > 1. Bachelor's Degree in Computer Science (duration: 8 semesters) > > > > 1.1. Unit 01: Mathematics Fundamental (duration: 1 semester) > > 1.1.1. Algebra I (first 3 months) > > 1.2. Unit 02: Programming (duration: 1 semester) > > 1.2.1. Programming Logic (first 3 months) > > > > Each course/project have a bunch of assignments + one final assignment. > > This goes on, totalizing 8 (eight) units, which will make up for a 4-year > > program. > > > I have to build my own Moodle API to be consumed by my program, > > Do you have any requirements defined? > APIs exist to do something, what operations does your API enable? > Until you know that you can't design anything very useful. Well, basically get program information like title, id and units, within units get title, id and courses, within courses get title, id, assignments, and within assignments get title, id, due date and grade. I'm working on a program to automate the process of getting assignments data and putting them on Trello and keep them up-to-date. (I'm using a Trello API from PyPi, but that doesn't matter for my script) > > > - I was thinking about having the following classes: Program, Unit, Course, > > Assignment, User. > > - User would handle auth + session, the rest is pretty straightforward, > > program would handle programs, unit would handles units, and so on. > > OK, Have you heard of CRC cards? These might be helpful here in > helping you understand and express what each of these classes does. > "pretty straightforward" is not helpful in designing a program, you > need to give more thought to what the program actually does. > And that means what each class is responsible for. No, never heard about it... > > > - Inside Program init there would be attributes title, id and units; inside > > Unit init there would be attributes title, id and courses; inside Course > > init there would be attributes title, id, due_date, submitted, grade. > > The attributes are there to support the operations. What are the > operations (ie the responsibilities) of the classes. That will > tell you what attributes you need to store, which to derive > and which are references to other (user defined) objects. > And which turn out not to be needed at all... Those classes won't have any methods right now, just atributes (title, id, due date, etc), their job is mainly hold data from Moodle in a convenient way, so I can use it whenever I like. > > > Should I call the site using requests and do all the parsing for everything > > using bs4 as soon as I create a new instance of User? For example: > > My personal opinion here is that objects should be > constructed into discrete attributes as quickly as possible so > I'd vote yes. Get the parsing done early. You can always define > a method to reconstruct the string if that proves necessary. > > BTW you are talking about calling the site but your API (as I understand > the assignment) is on the server side so have you > thought about how those requests will be received and > dispatched? Do you need more classes to deal with that? > Or is that something Moodle can do for you? > > > user = User('john.smith', 'password') # will get all data needed > > user.program # > > I'm not sure what you are trying to show us here. > The first line is a valid assignment statement but you are passing > in valid data, no parsing required. The second line does nothing > useful. Well, I'm trying to illustrate how the program would work. The parse would occur inside User, there I would call the site using requests and scrap data from it using bs4. I would get the username and password provided and use requests + bs4 inside User to login and keep session. The second line, and all of them for that matter, are just illustration. I already have a working version of the script, I'm just fixing some bugs and I will post it here. > > > Is this a good Pythonic design? If not, how could it be better? > > Mainly you are asking about general OOP/OOD rather than > anything Pythonic. That is not a bad thing, just a different > question. > > -- > 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 yahoo.co.uk Tue Nov 29 04:12:26 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 29 Nov 2016 09:12:26 +0000 Subject: [Tutor] Help on Software Design decisions In-Reply-To: References: Message-ID: On 29/11/16 02:02, Juan C. wrote: >>> I have to build my own Moodle API to be consumed by my program, I just noticed the last bit. Is this a client side API or a server side API? In other words are you building a set of services on the server or are you building a module that makes it easy for client side programs to access the server? I had assumed the first but your responses make me think it is probably the second. > Well, basically get program information like title, id and units, within > units get title, id and courses, within courses get title, id, assignments, > and within assignments get title, id, due date and grade. For a client side API where you just populate the data that's not unreasonable, the operations are more likely to be things like open(), close(), read(), write()(), refresh(), etc. > program to automate the process of getting assignments data and putting > them on Trello and keep them up-to-date. I've no idea what Trello is. >> OK, Have you heard of CRC cards? These might be helpful here in > > No, never heard about it... They are a simple and concise way of recording requirements (and some design) details for an OOP system. They may be less useful in your scenario where you probably wind up with one class doing most of the work and the others using it. >>> - Inside Program init there would be attributes title, id and units; > inside >>> Unit init there would be attributes title, id and courses; inside Course >>> init there would be attributes title, id, due_date, submitted, grade. >> >> The attributes are there to support the operations. What are the >> operations (ie the responsibilities) of the classes. It doesn't sound like you know that yet. Once you have a program to build using these classes you can add operations to them. At the moment you are in the unfortunate position of building a dumb API to some data. The functionality you are hiding is infrastructure not application level. >>> user = User('john.smith', 'password') # will get all data needed >>> user.program # > Well, I'm trying to illustrate how the program would work. The parse would > occur inside User, there I would call the site using requests and scrap > data from it using bs4. I would get the username and password provided and > use requests + bs4 inside User to login and keep session. OK, In that case you possibly want to call your class Users since you seem to intend to fetch all User objects at once? Or is the User ID doing double duty as a security token for the server and as a key into the data? Or should it look like: user = User(loginID, passwd, userID) > The second line, > and all of them for that matter, are just illustration. The problem is that they don't do anything. In the interactive interpreter they would print the values but in a real script the line user.program Does nothing useful, it would need to be part of an assignment: program = user.program But since program is itself a class do you need to go back to the server to fetch that program data? Or are you going to slurp it all up with the call to the top level user? If you fetch it as needed then your program attribute probably needs to become a method program = user.program() Where the method fetches the program details from the server and returns a Program object. -- 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 juan0christian at gmail.com Tue Nov 29 12:17:42 2016 From: juan0christian at gmail.com (Juan C.) Date: Tue, 29 Nov 2016 15:17:42 -0200 Subject: [Tutor] Help on Software Design decisions Message-ID: On Tue, Nov 29, 2016 at 7:12 AM, Alan Gauld via Tutor wrote: > I just noticed the last bit. > Is this a client side API or a server side API? > In other words are you building a set of services on the > server or are you building a module that makes it easy > for client side programs to access the server? I had > assumed the first but your responses make me think it > is probably the second. Client side. I'm building a python package to make it easier for my programs to get data from Moodle. > OK, In that case you possibly want to call your class > Users since you seem to intend to fetch all User objects at once? > Or is the User ID doing double duty as a security token for > the server and as a key into the data? Or should it look like: I just need username and password to login, nothing else. I'm passing 'program_id' as an argument to make it easier for me, but I intend to automatically get it in the future. Here's my working code: package moodle/ user.py #!/usr/bin/env python # -*- coding: utf-8 -*- from .program import Program import requests class User: _AUTH_URL = 'http://lms.university.edu/moodle/login/index.php' def __init__(self, username, password, program_id): self.username = username self.password = password session = requests.session() session.post(self._AUTH_URL, {"username": username, "password": password}) self.program = Program(program_id=program_id, session=session) def __str__(self): return self.username + ':' + self.password def __repr__(self): return '' % self.username def __eq__(self, other): if isinstance(other, self): return self.username == other.username else: return False ========== program.py #!/usr/bin/env python # -*- coding: utf-8 -*- from .unit import Unit from bs4 import BeautifulSoup class Program: _PATH = 'http://lms.university.edu/moodle/course/index.php?categoryid=' def __init__(self, program_id, session): response = session.get(self._PATH + str(program_id)) soup = BeautifulSoup(response.text, 'html.parser') self.name = soup.find('ul', class_='breadcrumb').find_all('li')[-2].text.replace('/', '').strip() self.id = program_id self.units = [Unit(int(item['data-categoryid']), session) for item in soup.find_all('div', {'class': 'category'})] def __str__(self): return self.name def __repr__(self): return '' % (self.name, self.id) def __eq__(self, other): if isinstance(other, self): return self.id == other.id else: return False ========== unit.py #!/usr/bin/env python # -*- coding: utf-8 -*- from .course import Course from bs4 import BeautifulSoup class Unit: _PATH = 'http://lms.university.edu/moodle/course/index.php?categoryid=' def __init__(self, unit_id, session): response = session.get(self._PATH + str(unit_id)) soup = BeautifulSoup(response.text, 'html.parser') self.name = soup.find('ul', class_='breadcrumb').find_all('li')[-1].text.replace('/', '').strip() self.id = unit_id self.courses = [Course(int(item['data-courseid']), session) for item in soup.find_all('div', {'class': 'coursebox'})] def __str__(self): return self.name def __repr__(self): return '' % (self.name, self.id) def __eq__(self, other): if isinstance(other, self): return self.id == other.id else: return False ========== course.py #!/usr/bin/env python # -*- coding: utf-8 -*- from .assignment import Assignment import re from bs4 import BeautifulSoup class Course: _PATH = 'http://lms.university.edu/moodle/course/view.php?id=' def __init__(self, course_id, session): response = session.get(self._PATH + str(course_id)) soup = BeautifulSoup(response.text, 'html.parser') self.name = soup.find('h1').text self.id = course_id self.assignments = [Assignment(int(item['href'].split('id=')[-1]), session) for item in soup.find_all('a', href=re.compile(r'http://lms \.university\.edu/moodle/mod/assign/view.php\?id=.*'))] def __str__(self): return self.name def __repr__(self): return '' % (self.name, self.id) def __eq__(self, other): if isinstance(other, self): return self.id == other.id else: return False ========== assignment.py #!/usr/bin/env python # -*- coding: utf-8 -*- from bs4 import BeautifulSoup class Assignment: _PATH = 'http://lms.university.edu/moodle/mod/assign/view.php?id=' def __init__(self, assignment_id, session): response = session.get(self._PATH + str(assignment_id)) soup = BeautifulSoup(response.text, 'html.parser') self.name = soup.find('h2').text self.id = assignment_id def __str__(self): return self.name def __repr__(self): return '' % (self.name, self.id) def __eq__(self, other): if isinstance(other, self): return self.id == other.id else: return False ========== test.py #!/usr/bin/env python # -*- coding: utf-8 -*- from moodle.user import User my_user = User('john.smith', '3uper$secret', 12) print(my_user) # print: john.smith:3uper$secret print(my_user.program) # print: Computer Science print(my_user.program.units) # print: [, ] print(my_user.program.units[-1].courses) # print: [, , , , ] print(my_user.program.units[-1].courses[-1].assignments) # print: [, , , , , ] From pewatteau at gmail.com Tue Nov 29 21:29:02 2016 From: pewatteau at gmail.com (Parish Watteau) Date: Tue, 29 Nov 2016 20:29:02 -0600 Subject: [Tutor] Ran into a problem: Tried many different methods Message-ID: The Springfork Amateur Golf Club has a tournament every weekend. The club president has asked you to write two programs: A program that will read each player?s name and golf score as keyboard input, and then save these as records in a file named golf.txt. (Each record will have a field for the player?s name and a field for the player?s score.) I attempted to solve it but ran into some errors from using some methods from a different python version but it didn't turn out the right way. Now I am stuck without a program and no where to start. Any help would be appreciated From alan.gauld at yahoo.co.uk Wed Nov 30 04:28:45 2016 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 30 Nov 2016 09:28:45 +0000 Subject: [Tutor] Ran into a problem: Tried many different methods In-Reply-To: References: Message-ID: On 30/11/16 02:29, Parish Watteau wrote: > A program that will read each player?s name and golf score as > keyboard input, and then save these as records in a file named golf.txt. > (Each record will have a field for the player?s name and a field for the > player?s score.) > > I attempted to solve it but ran into some errors from using some methods > from a different python version but it didn't turn out the right way. OK, that tells us almost nothing. Be specific. What errors did you get? Cut 'n paste the entire error message into your email. Which particular methods were you using that gave problems? What problems? Which Python version are you using (and which OS)? What does "it didn't turn out" mean? What happened? What did you expect to happen? > am stuck without a program and no where to start. Start with the basic problem and build up: Can you write code that reads a player's name and prints it on screen? Can you write code that reads a player's score and prints it on screen? Can you write a program that does both of the above. Can you write a program that reads say, 5 name and score pairs, printing as it goes? Can you write a program that repeatedly reads name and score pairs, printing as it goes, until some end condition is reached (an empty name say)? Can you write a program that writes a string to a text file called 'golf.txt'? Can you write a program that writes two strings to a text file called 'golf.txt'? Once you can do all of the above part-solutions you just need to combine them. Now tell us again what your specific problem is and we'll try to help you out. But be as specific as you can, the more detail you provide the easier it is for us to give you specific answers. -- 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 juan0christian at gmail.com Wed Nov 30 04:24:25 2016 From: juan0christian at gmail.com (Juan C.) Date: Wed, 30 Nov 2016 07:24:25 -0200 Subject: [Tutor] Ran into a problem: Tried many different methods In-Reply-To: References: Message-ID: On Wed, Nov 30, 2016 at 12:29 AM, Parish Watteau wrote: > A program that will read each player?s name and golf score as > keyboard input, and then save these as records in a file named golf.txt. > (Each record will have a field for the player?s name and a field for the > player?s score.) I believe you are totally covered by input() and open(). I suggest you to write data like a csv inside golf.txt to make it easier for write and read, like that: name,score bob donovan,50 mike smith,43 ana lyn,39 > I attempted to solve it but ran into some errors from using some methods > from a different python version but it didn't turn out the right way. Now I > am stuck without a program and no where to start. Any help would be > appreciated Well, it would be better if you provided your old script and error traceback, so we can see what you were thinking. Anyway, a good start would be to first create the logic to keep getting data from user input until the user tell you "I'm done", after you got it done you can go and start thinking about writing to file. To tell you the truth that's a quite easy script to do, I won't be posting the code here already because it would make no sense. Hope you got the general idea and can start your code.