From illusiontechniques at gmail.com Fri Aug 1 00:14:08 2014 From: illusiontechniques at gmail.com (C Smith) Date: Thu, 31 Jul 2014 18:14:08 -0400 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: References: <53DAA8BF.9020603@salesinq.com> Message-ID: Even when I am using: re.sub('/s', '\\/s', filename) I am still getting the same output, even trying to assign the above to a new variable doesn't work (as I wasn't sure if re.sub returned a new value or changed filename in place, I tried both with) Does the Python interpreter strip off backslashes or something with strings? On Thu, Jul 31, 2014 at 5:53 PM, C Smith wrote: >>Change: > > >>subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) > >>to: > >>subprocess.call(['ffmpeg', '-i', '"%s"' % filename, str(track)+'.mp3']) > > I still get the same errors, the filenames are passed to the shell > without escaping the spaces. > >>Why not using ffmpeg without jumping into Python. It's well documented, check Google. > > I guess you mean that the ability to change multiple files with ffmpeg > is possible. I hadn't considered that but I would rather do it with > Python, just for the practice. > > On Thu, Jul 31, 2014 at 4:36 PM, Emile wrote: >> On 7/31/2014 1:19 PM, C Smith wrote: >>> >>> I get >>> TypeError: unsupported operand type(s) for %: 'int' and 'str >>> I am not understanding the use of the list inside the subprocess.call(). >>> I tried all of the following >>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3']) % filename >>> --gives type error stated above >>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3'] % filename) >>> --same >>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3' % filename]) >>> -- TypeError: not all arguments converted during string formatting >>> and tried all three with the triple quotes, just to be sure. >>> >>> On Thu, Jul 31, 2014 at 4:04 PM, Emile van Sebille wrote: >>>> >>>> You might try using '"%s"' % filename so that the name is within quotes >>>> for the shell environment. >> >> >> Change: >> >> >> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >> >> to: >> >> subprocess.call(['ffmpeg', '-i', '"%s"' % filename, str(track)+'.mp3']) >> >> Emile >> >> >> From illusiontechniques at gmail.com Fri Aug 1 00:20:35 2014 From: illusiontechniques at gmail.com (C Smith) Date: Thu, 31 Jul 2014 18:20:35 -0400 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: References: <53DAA8BF.9020603@salesinq.com> Message-ID: Okay I messed up with slash instead of backslash, so the re.sub() works, but I am still curious about the previous question. On Thu, Jul 31, 2014 at 6:14 PM, C Smith wrote: > Even when I am using: > re.sub('/s', '\\/s', filename) > I am still getting the same output, even trying to assign the above to > a new variable doesn't work (as I wasn't sure if re.sub returned a new > value or changed filename in place, I tried both with) > Does the Python interpreter strip off backslashes or something with strings? > > On Thu, Jul 31, 2014 at 5:53 PM, C Smith wrote: >>>Change: >> >> >>>subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >> >>>to: >> >>>subprocess.call(['ffmpeg', '-i', '"%s"' % filename, str(track)+'.mp3']) >> >> I still get the same errors, the filenames are passed to the shell >> without escaping the spaces. >> >>>Why not using ffmpeg without jumping into Python. It's well documented, check Google. >> >> I guess you mean that the ability to change multiple files with ffmpeg >> is possible. I hadn't considered that but I would rather do it with >> Python, just for the practice. >> >> On Thu, Jul 31, 2014 at 4:36 PM, Emile wrote: >>> On 7/31/2014 1:19 PM, C Smith wrote: >>>> >>>> I get >>>> TypeError: unsupported operand type(s) for %: 'int' and 'str >>>> I am not understanding the use of the list inside the subprocess.call(). >>>> I tried all of the following >>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3']) % filename >>>> --gives type error stated above >>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3'] % filename) >>>> --same >>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3' % filename]) >>>> -- TypeError: not all arguments converted during string formatting >>>> and tried all three with the triple quotes, just to be sure. >>>> >>>> On Thu, Jul 31, 2014 at 4:04 PM, Emile van Sebille wrote: >>>>> >>>>> You might try using '"%s"' % filename so that the name is within quotes >>>>> for the shell environment. >>> >>> >>> Change: >>> >>> >>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>> >>> to: >>> >>> subprocess.call(['ffmpeg', '-i', '"%s"' % filename, str(track)+'.mp3']) >>> >>> Emile >>> >>> >>> From illusiontechniques at gmail.com Fri Aug 1 00:34:41 2014 From: illusiontechniques at gmail.com (C Smith) Date: Thu, 31 Jul 2014 18:34:41 -0400 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: References: <53DAA8BF.9020603@salesinq.com> Message-ID: Actually, I can get re.sub() to print the filenames where they look like they would be in the correct format for the shell, like this: 10\ track \number \ten.flac but the shell still says that no such file exists, and I am sure I am operating on them in the right place because I can modify them. So, I am still wondering about that too. On Thu, Jul 31, 2014 at 6:20 PM, C Smith wrote: > Okay I messed up with slash instead of backslash, so the re.sub() > works, but I am still curious about the previous question. > > On Thu, Jul 31, 2014 at 6:14 PM, C Smith wrote: >> Even when I am using: >> re.sub('/s', '\\/s', filename) >> I am still getting the same output, even trying to assign the above to >> a new variable doesn't work (as I wasn't sure if re.sub returned a new >> value or changed filename in place, I tried both with) >> Does the Python interpreter strip off backslashes or something with strings? >> >> On Thu, Jul 31, 2014 at 5:53 PM, C Smith wrote: >>>>Change: >>> >>> >>>>subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>> >>>>to: >>> >>>>subprocess.call(['ffmpeg', '-i', '"%s"' % filename, str(track)+'.mp3']) >>> >>> I still get the same errors, the filenames are passed to the shell >>> without escaping the spaces. >>> >>>>Why not using ffmpeg without jumping into Python. It's well documented, check Google. >>> >>> I guess you mean that the ability to change multiple files with ffmpeg >>> is possible. I hadn't considered that but I would rather do it with >>> Python, just for the practice. >>> >>> On Thu, Jul 31, 2014 at 4:36 PM, Emile wrote: >>>> On 7/31/2014 1:19 PM, C Smith wrote: >>>>> >>>>> I get >>>>> TypeError: unsupported operand type(s) for %: 'int' and 'str >>>>> I am not understanding the use of the list inside the subprocess.call(). >>>>> I tried all of the following >>>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3']) % filename >>>>> --gives type error stated above >>>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3'] % filename) >>>>> --same >>>>> subprocess.call(['ffmpeg', '-i', '%s', str(track)+'.mp3' % filename]) >>>>> -- TypeError: not all arguments converted during string formatting >>>>> and tried all three with the triple quotes, just to be sure. >>>>> >>>>> On Thu, Jul 31, 2014 at 4:04 PM, Emile van Sebille wrote: >>>>>> >>>>>> You might try using '"%s"' % filename so that the name is within quotes >>>>>> for the shell environment. >>>> >>>> >>>> Change: >>>> >>>> >>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>>> >>>> to: >>>> >>>> subprocess.call(['ffmpeg', '-i', '"%s"' % filename, str(track)+'.mp3']) >>>> >>>> Emile >>>> >>>> >>>> From steve at pearwood.info Fri Aug 1 00:35:34 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 1 Aug 2014 08:35:34 +1000 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: References: Message-ID: <20140731223533.GA4525@ando> You may have already have solved your problem, unfortunately my emails are coming in slowly and out of order, but I have a suggestion: On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote: > I am on OSX, which needs to escape spaces in filenames with a backslash. Same as any other Unix, or Linux, or, indeed, Windows. > There are multiple files within one directory that all have the same > structure, one or more characters with zero or more spaces in the > filename, like this: > 3 Song Title XYZ.flac. > I want to use Python to call ffmpeg to convert each file to an .mp3. > So far this is what I was trying to use: > import os, subprocess > track = 1 > for filename in os.listdir('myDir'): > subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) > track += 1 I believe that your problem is *not* the spaces, but that you're passing just the filename and not the directory. subprocess will escape the spaces for you. Also, let Python count the track number for you. Try this: directory = '/path/to/the/directory' for track, filename in enumerate(os.listdir(directory), 1): pathname = os.path.join(directory, filename) subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) I expect something like that will work. You should be able to pass either an absolute path (beginning with /) or a relative path starting from the current working directory. If this doesn't work, please show the full error that you receive. If it is a Python traceback, copy and paste the whole thing, if it's an ffmpeg error, give as much information as you can. -- Steven From steve at pearwood.info Fri Aug 1 00:43:28 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 1 Aug 2014 08:43:28 +1000 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: <20140731223533.GA4525@ando> References: <20140731223533.GA4525@ando> Message-ID: <20140731224328.GC4525@ando> Oops, a silly bug: On Fri, Aug 01, 2014 at 08:35:34AM +1000, Steven D'Aprano wrote: > directory = '/path/to/the/directory' > for track, filename in enumerate(os.listdir(directory), 1): > pathname = os.path.join(directory, filename) > subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) That should be pathname, of course: subprocess.call(['ffmpeg', '-i', pathname, str(track)+'.mp3']) Also, be aware that the order of files coming from listdir is not guaranteed to be sorted in any specific fashion, so if you're renaming files like "3 blah blah blah.flac" to "7.mp3" you may end up a little confused :-) -- Steven From illusiontechniques at gmail.com Fri Aug 1 00:55:07 2014 From: illusiontechniques at gmail.com (C Smith) Date: Thu, 31 Jul 2014 18:55:07 -0400 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: <20140731223533.GA4525@ando> References: <20140731223533.GA4525@ando> Message-ID: >for track, filename in enumerate(os.listdir(directory), 1): It seems kinda counter-intuitive to have track then filename as variables, but enumerate looks like it gets passed the filename then track number. Is that correct and just the way enumerate works, a typo, or am I missing something else here? It is an ffmpeg error I am getting. ffmpeg just gives its usual build information and the error is (for each song title in the directory): songTitleIsHere.flac: no such file or directory So it looks like it is close to working because it finds the correct file names, but doesn't recognize it for some reason. Here is how I put in your code import os, subprocess directory = '/absolute/path/goes/here' for track, filename in enumerate(os.listdir(directory), 1): pathname = os.path.join(directory, filename) subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) So it goes to the right place, because every song title is listed out, ffmpeg or the shell just don't recognize them correctly. On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano wrote: > You may have already have solved your problem, unfortunately my > emails are coming in slowly and out of order, but I have a suggestion: > > On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote: >> I am on OSX, which needs to escape spaces in filenames with a backslash. > > Same as any other Unix, or Linux, or, indeed, Windows. > >> There are multiple files within one directory that all have the same >> structure, one or more characters with zero or more spaces in the >> filename, like this: >> 3 Song Title XYZ.flac. >> I want to use Python to call ffmpeg to convert each file to an .mp3. >> So far this is what I was trying to use: >> import os, subprocess >> track = 1 >> for filename in os.listdir('myDir'): >> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >> track += 1 > > I believe that your problem is *not* the spaces, but that you're passing > just the filename and not the directory. subprocess will escape the > spaces for you. Also, let Python count the track number for you. Try > this: > > > directory = '/path/to/the/directory' > for track, filename in enumerate(os.listdir(directory), 1): > pathname = os.path.join(directory, filename) > subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) > > > I expect something like that will work. You should be able to pass > either an absolute path (beginning with /) or a relative path starting > from the current working directory. > > If this doesn't work, please show the full error that you receive. If it > is a Python traceback, copy and paste the whole thing, if it's an ffmpeg > error, give as much information as you can. > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From illusiontechniques at gmail.com Fri Aug 1 00:57:05 2014 From: illusiontechniques at gmail.com (C Smith) Date: Thu, 31 Jul 2014 18:57:05 -0400 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: References: <20140731223533.GA4525@ando> Message-ID: woops, I see it pathname != filename On Thu, Jul 31, 2014 at 6:55 PM, C Smith wrote: >>for track, filename in enumerate(os.listdir(directory), 1): > It seems kinda counter-intuitive to have track then filename as > variables, but enumerate looks like it gets passed the filename then > track number. Is that correct and just the way enumerate works, a > typo, or am I missing something else here? > > It is an ffmpeg error I am getting. > ffmpeg just gives its usual build information and the error is (for > each song title in the directory): > songTitleIsHere.flac: no such file or directory > > So it looks like it is close to working because it finds the correct > file names, but doesn't recognize it for some reason. > Here is how I put in your code > import os, subprocess > directory = '/absolute/path/goes/here' > for track, filename in enumerate(os.listdir(directory), 1): > pathname = os.path.join(directory, filename) > subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) > > So it goes to the right place, because every song title is listed out, > ffmpeg or the shell just don't recognize them correctly. > > On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano wrote: >> You may have already have solved your problem, unfortunately my >> emails are coming in slowly and out of order, but I have a suggestion: >> >> On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote: >>> I am on OSX, which needs to escape spaces in filenames with a backslash. >> >> Same as any other Unix, or Linux, or, indeed, Windows. >> >>> There are multiple files within one directory that all have the same >>> structure, one or more characters with zero or more spaces in the >>> filename, like this: >>> 3 Song Title XYZ.flac. >>> I want to use Python to call ffmpeg to convert each file to an .mp3. >>> So far this is what I was trying to use: >>> import os, subprocess >>> track = 1 >>> for filename in os.listdir('myDir'): >>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>> track += 1 >> >> I believe that your problem is *not* the spaces, but that you're passing >> just the filename and not the directory. subprocess will escape the >> spaces for you. Also, let Python count the track number for you. Try >> this: >> >> >> directory = '/path/to/the/directory' >> for track, filename in enumerate(os.listdir(directory), 1): >> pathname = os.path.join(directory, filename) >> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >> >> >> I expect something like that will work. You should be able to pass >> either an absolute path (beginning with /) or a relative path starting >> from the current working directory. >> >> If this doesn't work, please show the full error that you receive. If it >> is a Python traceback, copy and paste the whole thing, if it's an ffmpeg >> error, give as much information as you can. >> >> >> >> -- >> Steven >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor From illusiontechniques at gmail.com Fri Aug 1 00:57:57 2014 From: illusiontechniques at gmail.com (C Smith) Date: Thu, 31 Jul 2014 18:57:57 -0400 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: References: <20140731223533.GA4525@ando> Message-ID: Works now, thanks! On Thu, Jul 31, 2014 at 6:57 PM, C Smith wrote: > woops, I see it pathname != filename > > On Thu, Jul 31, 2014 at 6:55 PM, C Smith wrote: >>>for track, filename in enumerate(os.listdir(directory), 1): >> It seems kinda counter-intuitive to have track then filename as >> variables, but enumerate looks like it gets passed the filename then >> track number. Is that correct and just the way enumerate works, a >> typo, or am I missing something else here? >> >> It is an ffmpeg error I am getting. >> ffmpeg just gives its usual build information and the error is (for >> each song title in the directory): >> songTitleIsHere.flac: no such file or directory >> >> So it looks like it is close to working because it finds the correct >> file names, but doesn't recognize it for some reason. >> Here is how I put in your code >> import os, subprocess >> directory = '/absolute/path/goes/here' >> for track, filename in enumerate(os.listdir(directory), 1): >> pathname = os.path.join(directory, filename) >> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >> >> So it goes to the right place, because every song title is listed out, >> ffmpeg or the shell just don't recognize them correctly. >> >> On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano wrote: >>> You may have already have solved your problem, unfortunately my >>> emails are coming in slowly and out of order, but I have a suggestion: >>> >>> On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote: >>>> I am on OSX, which needs to escape spaces in filenames with a backslash. >>> >>> Same as any other Unix, or Linux, or, indeed, Windows. >>> >>>> There are multiple files within one directory that all have the same >>>> structure, one or more characters with zero or more spaces in the >>>> filename, like this: >>>> 3 Song Title XYZ.flac. >>>> I want to use Python to call ffmpeg to convert each file to an .mp3. >>>> So far this is what I was trying to use: >>>> import os, subprocess >>>> track = 1 >>>> for filename in os.listdir('myDir'): >>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>>> track += 1 >>> >>> I believe that your problem is *not* the spaces, but that you're passing >>> just the filename and not the directory. subprocess will escape the >>> spaces for you. Also, let Python count the track number for you. Try >>> this: >>> >>> >>> directory = '/path/to/the/directory' >>> for track, filename in enumerate(os.listdir(directory), 1): >>> pathname = os.path.join(directory, filename) >>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>> >>> >>> I expect something like that will work. You should be able to pass >>> either an absolute path (beginning with /) or a relative path starting >>> from the current working directory. >>> >>> If this doesn't work, please show the full error that you receive. If it >>> is a Python traceback, copy and paste the whole thing, if it's an ffmpeg >>> error, give as much information as you can. >>> >>> >>> >>> -- >>> Steven >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> https://mail.python.org/mailman/listinfo/tutor From illusiontechniques at gmail.com Fri Aug 1 01:02:35 2014 From: illusiontechniques at gmail.com (C Smith) Date: Thu, 31 Jul 2014 19:02:35 -0400 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: References: <20140731223533.GA4525@ando> Message-ID: Huh, that is quite an annoyance about changing the order though. Any ideas about that? I will look into it further in the meantime... On Thu, Jul 31, 2014 at 6:57 PM, C Smith wrote: > Works now, thanks! > > On Thu, Jul 31, 2014 at 6:57 PM, C Smith wrote: >> woops, I see it pathname != filename >> >> On Thu, Jul 31, 2014 at 6:55 PM, C Smith wrote: >>>>for track, filename in enumerate(os.listdir(directory), 1): >>> It seems kinda counter-intuitive to have track then filename as >>> variables, but enumerate looks like it gets passed the filename then >>> track number. Is that correct and just the way enumerate works, a >>> typo, or am I missing something else here? >>> >>> It is an ffmpeg error I am getting. >>> ffmpeg just gives its usual build information and the error is (for >>> each song title in the directory): >>> songTitleIsHere.flac: no such file or directory >>> >>> So it looks like it is close to working because it finds the correct >>> file names, but doesn't recognize it for some reason. >>> Here is how I put in your code >>> import os, subprocess >>> directory = '/absolute/path/goes/here' >>> for track, filename in enumerate(os.listdir(directory), 1): >>> pathname = os.path.join(directory, filename) >>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>> >>> So it goes to the right place, because every song title is listed out, >>> ffmpeg or the shell just don't recognize them correctly. >>> >>> On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano wrote: >>>> You may have already have solved your problem, unfortunately my >>>> emails are coming in slowly and out of order, but I have a suggestion: >>>> >>>> On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote: >>>>> I am on OSX, which needs to escape spaces in filenames with a backslash. >>>> >>>> Same as any other Unix, or Linux, or, indeed, Windows. >>>> >>>>> There are multiple files within one directory that all have the same >>>>> structure, one or more characters with zero or more spaces in the >>>>> filename, like this: >>>>> 3 Song Title XYZ.flac. >>>>> I want to use Python to call ffmpeg to convert each file to an .mp3. >>>>> So far this is what I was trying to use: >>>>> import os, subprocess >>>>> track = 1 >>>>> for filename in os.listdir('myDir'): >>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>>>> track += 1 >>>> >>>> I believe that your problem is *not* the spaces, but that you're passing >>>> just the filename and not the directory. subprocess will escape the >>>> spaces for you. Also, let Python count the track number for you. Try >>>> this: >>>> >>>> >>>> directory = '/path/to/the/directory' >>>> for track, filename in enumerate(os.listdir(directory), 1): >>>> pathname = os.path.join(directory, filename) >>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>>> >>>> >>>> I expect something like that will work. You should be able to pass >>>> either an absolute path (beginning with /) or a relative path starting >>>> from the current working directory. >>>> >>>> If this doesn't work, please show the full error that you receive. If it >>>> is a Python traceback, copy and paste the whole thing, if it's an ffmpeg >>>> error, give as much information as you can. >>>> >>>> >>>> >>>> -- >>>> Steven >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> https://mail.python.org/mailman/listinfo/tutor From illusiontechniques at gmail.com Fri Aug 1 01:13:32 2014 From: illusiontechniques at gmail.com (C Smith) Date: Thu, 31 Jul 2014 19:13:32 -0400 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: References: <20140731223533.GA4525@ando> Message-ID: thanks, got it import os, subprocess, re directory = 'abs/path' for track, filename in enumerate(os.listdir(directory), 1): pathname = os.path.join(directory, filename) subprocess.call(['ffmpeg', '-i', pathname, filename+str(track)+'.mp3']) On Thu, Jul 31, 2014 at 7:02 PM, C Smith wrote: > Huh, that is quite an annoyance about changing the order though. Any > ideas about that? I will look into it further in the meantime... > > On Thu, Jul 31, 2014 at 6:57 PM, C Smith wrote: >> Works now, thanks! >> >> On Thu, Jul 31, 2014 at 6:57 PM, C Smith wrote: >>> woops, I see it pathname != filename >>> >>> On Thu, Jul 31, 2014 at 6:55 PM, C Smith wrote: >>>>>for track, filename in enumerate(os.listdir(directory), 1): >>>> It seems kinda counter-intuitive to have track then filename as >>>> variables, but enumerate looks like it gets passed the filename then >>>> track number. Is that correct and just the way enumerate works, a >>>> typo, or am I missing something else here? >>>> >>>> It is an ffmpeg error I am getting. >>>> ffmpeg just gives its usual build information and the error is (for >>>> each song title in the directory): >>>> songTitleIsHere.flac: no such file or directory >>>> >>>> So it looks like it is close to working because it finds the correct >>>> file names, but doesn't recognize it for some reason. >>>> Here is how I put in your code >>>> import os, subprocess >>>> directory = '/absolute/path/goes/here' >>>> for track, filename in enumerate(os.listdir(directory), 1): >>>> pathname = os.path.join(directory, filename) >>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>>> >>>> So it goes to the right place, because every song title is listed out, >>>> ffmpeg or the shell just don't recognize them correctly. >>>> >>>> On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano wrote: >>>>> You may have already have solved your problem, unfortunately my >>>>> emails are coming in slowly and out of order, but I have a suggestion: >>>>> >>>>> On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote: >>>>>> I am on OSX, which needs to escape spaces in filenames with a backslash. >>>>> >>>>> Same as any other Unix, or Linux, or, indeed, Windows. >>>>> >>>>>> There are multiple files within one directory that all have the same >>>>>> structure, one or more characters with zero or more spaces in the >>>>>> filename, like this: >>>>>> 3 Song Title XYZ.flac. >>>>>> I want to use Python to call ffmpeg to convert each file to an .mp3. >>>>>> So far this is what I was trying to use: >>>>>> import os, subprocess >>>>>> track = 1 >>>>>> for filename in os.listdir('myDir'): >>>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>>>>> track += 1 >>>>> >>>>> I believe that your problem is *not* the spaces, but that you're passing >>>>> just the filename and not the directory. subprocess will escape the >>>>> spaces for you. Also, let Python count the track number for you. Try >>>>> this: >>>>> >>>>> >>>>> directory = '/path/to/the/directory' >>>>> for track, filename in enumerate(os.listdir(directory), 1): >>>>> pathname = os.path.join(directory, filename) >>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>>>> >>>>> >>>>> I expect something like that will work. You should be able to pass >>>>> either an absolute path (beginning with /) or a relative path starting >>>>> from the current working directory. >>>>> >>>>> If this doesn't work, please show the full error that you receive. If it >>>>> is a Python traceback, copy and paste the whole thing, if it's an ffmpeg >>>>> error, give as much information as you can. >>>>> >>>>> >>>>> >>>>> -- >>>>> Steven >>>>> _______________________________________________ >>>>> Tutor maillist - Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> https://mail.python.org/mailman/listinfo/tutor From illusiontechniques at gmail.com Fri Aug 1 01:23:55 2014 From: illusiontechniques at gmail.com (C Smith) Date: Thu, 31 Jul 2014 19:23:55 -0400 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: References: <20140731223533.GA4525@ando> Message-ID: or more accurately import os, subprocess, re directory = '/abs/path' for track, filename in enumerate(os.listdir(directory), 1): pathname = os.path.join(directory, filename) subprocess.call(['ffmpeg', '-i', pathname, filename[:-5]+'.mp3']) On Thu, Jul 31, 2014 at 7:13 PM, C Smith wrote: > thanks, got it > import os, subprocess, re > directory = 'abs/path' > for track, filename in enumerate(os.listdir(directory), 1): > pathname = os.path.join(directory, filename) > subprocess.call(['ffmpeg', '-i', pathname, filename+str(track)+'.mp3']) > > On Thu, Jul 31, 2014 at 7:02 PM, C Smith wrote: >> Huh, that is quite an annoyance about changing the order though. Any >> ideas about that? I will look into it further in the meantime... >> >> On Thu, Jul 31, 2014 at 6:57 PM, C Smith wrote: >>> Works now, thanks! >>> >>> On Thu, Jul 31, 2014 at 6:57 PM, C Smith wrote: >>>> woops, I see it pathname != filename >>>> >>>> On Thu, Jul 31, 2014 at 6:55 PM, C Smith wrote: >>>>>>for track, filename in enumerate(os.listdir(directory), 1): >>>>> It seems kinda counter-intuitive to have track then filename as >>>>> variables, but enumerate looks like it gets passed the filename then >>>>> track number. Is that correct and just the way enumerate works, a >>>>> typo, or am I missing something else here? >>>>> >>>>> It is an ffmpeg error I am getting. >>>>> ffmpeg just gives its usual build information and the error is (for >>>>> each song title in the directory): >>>>> songTitleIsHere.flac: no such file or directory >>>>> >>>>> So it looks like it is close to working because it finds the correct >>>>> file names, but doesn't recognize it for some reason. >>>>> Here is how I put in your code >>>>> import os, subprocess >>>>> directory = '/absolute/path/goes/here' >>>>> for track, filename in enumerate(os.listdir(directory), 1): >>>>> pathname = os.path.join(directory, filename) >>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>>>> >>>>> So it goes to the right place, because every song title is listed out, >>>>> ffmpeg or the shell just don't recognize them correctly. >>>>> >>>>> On Thu, Jul 31, 2014 at 6:35 PM, Steven D'Aprano wrote: >>>>>> You may have already have solved your problem, unfortunately my >>>>>> emails are coming in slowly and out of order, but I have a suggestion: >>>>>> >>>>>> On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote: >>>>>>> I am on OSX, which needs to escape spaces in filenames with a backslash. >>>>>> >>>>>> Same as any other Unix, or Linux, or, indeed, Windows. >>>>>> >>>>>>> There are multiple files within one directory that all have the same >>>>>>> structure, one or more characters with zero or more spaces in the >>>>>>> filename, like this: >>>>>>> 3 Song Title XYZ.flac. >>>>>>> I want to use Python to call ffmpeg to convert each file to an .mp3. >>>>>>> So far this is what I was trying to use: >>>>>>> import os, subprocess >>>>>>> track = 1 >>>>>>> for filename in os.listdir('myDir'): >>>>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>>>>>> track += 1 >>>>>> >>>>>> I believe that your problem is *not* the spaces, but that you're passing >>>>>> just the filename and not the directory. subprocess will escape the >>>>>> spaces for you. Also, let Python count the track number for you. Try >>>>>> this: >>>>>> >>>>>> >>>>>> directory = '/path/to/the/directory' >>>>>> for track, filename in enumerate(os.listdir(directory), 1): >>>>>> pathname = os.path.join(directory, filename) >>>>>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>>>>> >>>>>> >>>>>> I expect something like that will work. You should be able to pass >>>>>> either an absolute path (beginning with /) or a relative path starting >>>>>> from the current working directory. >>>>>> >>>>>> If this doesn't work, please show the full error that you receive. If it >>>>>> is a Python traceback, copy and paste the whole thing, if it's an ffmpeg >>>>>> error, give as much information as you can. >>>>>> >>>>>> >>>>>> >>>>>> -- >>>>>> Steven >>>>>> _______________________________________________ >>>>>> Tutor maillist - Tutor at python.org >>>>>> To unsubscribe or change subscription options: >>>>>> https://mail.python.org/mailman/listinfo/tutor From __peter__ at web.de Fri Aug 1 01:37:32 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 01 Aug 2014 01:37:32 +0200 Subject: [Tutor] Using subprocess on a series of files with spaces References: <20140731223533.GA4525@ando> Message-ID: C Smith wrote: I'd throw in a check to verify that filename is indeed a flac: > or more accurately > import os, subprocess, re > directory = '/abs/path' > for track, filename in enumerate(os.listdir(directory), 1): > pathname = os.path.join(directory, filename) if filename.endswith(".flac"): subprocess.call(['ffmpeg', '-i', pathname, filename[:-5]+'.mp3']) From illusiontechniques at gmail.com Fri Aug 1 01:47:28 2014 From: illusiontechniques at gmail.com (C Smith) Date: Thu, 31 Jul 2014 19:47:28 -0400 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: References: <20140731223533.GA4525@ando> Message-ID: Nice, these are useful tools. I have been building something with just basic stuff and avoiding learning any libraries. If I wanted to get some insight on a larger program that is about 1000 lines, would that be doable here? On Thu, Jul 31, 2014 at 7:37 PM, Peter Otten <__peter__ at web.de> wrote: > C Smith wrote: > > I'd throw in a check to verify that filename is indeed a flac: > >> or more accurately >> import os, subprocess, re >> directory = '/abs/path' >> for track, filename in enumerate(os.listdir(directory), 1): >> pathname = os.path.join(directory, filename) > if filename.endswith(".flac"): > subprocess.call(['ffmpeg', '-i', pathname, filename[:-5]+'.mp3']) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From cs at zip.com.au Fri Aug 1 03:42:50 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 1 Aug 2014 11:42:50 +1000 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: <20140731223533.GA4525@ando> References: <20140731223533.GA4525@ando> Message-ID: <20140801014250.GA50373@cskk.homeip.net> On 01Aug2014 08:35, Steven D'Aprano wrote: [...] >> I want to use Python to call ffmpeg to convert each file to an .mp3. >> So far this is what I was trying to use: >> import os, subprocess >> track = 1 >> for filename in os.listdir('myDir'): >> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >> track += 1 This is basicly ok, except that as others have mentioned you need to put "myDir/" on the front of filename, because the file is in the subdirectory. probably also with the mp3 output filename depending what you intend. >I believe that your problem is *not* the spaces, but that you're passing >just the filename and not the directory. subprocess will escape the >spaces for you. I wish people would not say this. subprocess DOES NOT escape the spaces, nor does it need to. The only reason the OP imagines he needs to escape spaces it that he is probably testing his ffmpeg command in a shell (entirely reasonable). And in a shell you need to escape the spaces to prevent the shell deciding that they are separating words. An entirely syntactic issue. However, the subprocess call above uses a list for the command, and that form DOES NOT pass anything to the shell. The command gets executed directly. And therefore no spaces need escaping at all. Just getting this out before we further confuse the OP. Cheers, Cameron Simpson From memilanuk at gmail.com Fri Aug 1 04:56:23 2014 From: memilanuk at gmail.com (memilanuk) Date: Thu, 31 Jul 2014 19:56:23 -0700 Subject: [Tutor] dict.get() vs. dict.get Message-ID: What is the difference between dict.get() and dict.get as shown in the code below: counts = dict() for line in input_file: words = line.split() if len(words) == 0: continue else: if words[0] != 'From:': continue else: counts[words[1]] = counts.get(words[1], 0) + 1 max_key = max(counts, key=counts.get) max_value = counts[max_key] print max_key, max_value I know the former (counts.get()) is supposed to return a value for a key if it exists, or else return the default value (in this case '0'). That part of the code is checking to see if the value contained in words[1] exists as a key in the dictionary counts or not; either way increment the associated value by +1. The latter (counts.get) reflects some code I found online [1]: print max(d.keys(), key=lambda x: d[x]) or even shorter (from comment): print max(d, key=d.get) that is to replace manually looping through the dict to find the max value like this: max_value = None max_key = None for key, value in counts.items(): if max_value is None or max_value < value: max_value = value max_key = key print max_key, max_value So... the similarity between dict.get() and dict.get as used here is kinda confusing me. When I do a search for 'dict.get' in the python docs or on google all I normally find is stuff referring to 'dict.get()'. Any pointers would be much appreciated. [1] http://stackoverflow.com/questions/12402015/print-the-key-of-the-max-value-in-a-dictionary-the-pythonic-way -- Shiny! Let's be bad guys. Reach me @ memilanuk (at) gmail dot com From ben+python at benfinney.id.au Fri Aug 1 05:22:11 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 01 Aug 2014 13:22:11 +1000 Subject: [Tutor] Python functions are first-class citizens (was: dict.get() vs. dict.get) References: Message-ID: <85tx5wdhcs.fsf@benfinney.id.au> memilanuk writes: > What is the difference between dict.get() and dict.get The ?foo()? syntax calls ?foo?. ?dict.get? is the function (an attribute of the ?dict? type), and you can call that function by specifying parameters in parens ?()?. > counts[words[1]] = counts.get(words[1], 0) + 1 This line is calling the ?get? method of the ?counts? object. Since that object likely doesn't have its own ?get? attribute, this will be the ?dict.get? function (since ?coutns? is an instance of ?dict?). That part of the expression ? ?counts.get(words[1], 0)? ? will evaluate to whatever is the return value of that call. > max_key = max(counts, key=counts.get) This specifies ?counts.get?, without calling it. The expression ?counts.get? evaluates to that function object. That value is then used as the value for the ?key? parameter when calling ?max? here. > So... the similarity between dict.get() and dict.get as used here is > kinda confusing me. I hope that helps. They are the same function; but the former is *calling* the function object, and optionally using the return value; the latter is referring to the function object *as* a value. > Any pointers would be much appreciated. This use of functions and other callable objects as values, is sometimes referred to as the fact Python has ?first-class functions? . -- \ ?What we usually pray to God is not that His will be done, but | `\ that He approve ours.? ?Helga Bergold Gross | _o__) | Ben Finney From steve at pearwood.info Fri Aug 1 05:36:58 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 1 Aug 2014 13:36:58 +1000 Subject: [Tutor] dict.get() vs. dict.get In-Reply-To: References: Message-ID: <20140801033657.GD4525@ando> On Thu, Jul 31, 2014 at 07:56:23PM -0700, memilanuk wrote: > What is the difference between dict.get() and dict.get as shown in the > code below: Depending on how you look at it, the difference is either "nothing at all", or "the round brackets ()". And I'm not trying to be funny. Experimenting at the interactive interpreter may shed some light on this: py> d = {1: 'a', 2: 'b'} py> d.get So dict.get returns the "get" method of dict objects, but without actually calling it yet. It doesn't get called until add parentheses (round brackets) to it: py> method = d.get # Don't call it yet, just grab the method. py> print method py> method(2) # Now call it. 'b' py> method(3, 'ZZZ') 'ZZZ' So adding brackets to the method object calls it. We can do the same with *any* function or method, not just "get": py> len py> len([]) 0 Now, what's the difference between d.get and dict.get? The first one is *bound* to an instance, in this case d, while the second one is not. Let me explain. Most methods operate on a specific instance. These two calls to "get" do different things, because the instance they are calling on are different: instance1 = {1: "a", 2: "b"} instance2 = {1: "AAA", 2: "BBB"} instance1.get(1) # returns "a" instance2.get(1) # returns "AAA" Pretty obvious, right? And the same thing happens if you grab the method, it remembers which instance it came from: method = instance2.get # Don't call the method yet! method(2) # returns "BBB" So far so good. But what happens if you access the method, not from an instance, but directly from the class? method = dict.get # comes from dict, not from instance1 or instance2 You still get a method, but now you get a method that doesn't know which instance to operate on. If the earlier examples were bound to an instance, this one is called an *unbound* method. So when you call it, you have to provide the instance first! method(instance1, 2) # returns "b" method(instance2, 2) # returns "BBB" To look at it another way, when you define a method, you write it with a "self" argument: class MyClass: def do_something(self, x, y, z): ... instance = MyClass() instance.do_something(x, y, z) In this case, Python sees that you're calling the method from instance, and automatically provides that as the "self" argument. But if you do this: MyClass.do_something there's no "self" yet, so you have to manually provide it. And that's the difference between bound and unbound methods. Does help explain what is going on? Feel free to ask more questions if needed. -- Steven From memilanuk at gmail.com Fri Aug 1 07:12:49 2014 From: memilanuk at gmail.com (memilanuk) Date: Thu, 31 Jul 2014 22:12:49 -0700 Subject: [Tutor] Python functions are first-class citizens In-Reply-To: <85tx5wdhcs.fsf@benfinney.id.au> References: <85tx5wdhcs.fsf@benfinney.id.au> Message-ID: <53DB21D1.3000704@gmail.com> On 07/31/2014 08:22 PM, Ben Finney wrote: > memilanuk writes: >> So... the similarity between dict.get() and dict.get as used here is >> kinda confusing me. > > I hope that helps. They are the same function; but the former is > *calling* the function object, and optionally using the return value; > the latter is referring to the function object *as* a value. Conceptually, that makes sense. Practically... having a little trouble getting my head around it - see below. >> max_key = max(counts, key=counts.get) > > This specifies ?counts.get?, without calling it. The expression > ?counts.get? evaluates to that function object. > > That value is then used as the value for the ?key? parameter when > calling ?max? here. Been reading a bit more in the mean time, trying to grok that 'key' parameter for max()... and of course the python docs for max(iterable, key=) refer to the docs for list.sort() ;) Kind of diverging off the original question a bit... but since it did include the max() code in it... I'm having a bit of difficulty with the whole 'key=' parameter when combined with counts.get here. So counts is the iterable, and counts.get is the key used to iterate through it? I guess I'm not getting how the whole key, function object bit works here in actual practice. if we have counts = {'a':1, 'b':22, 'c':100} then counts.get('b') should return 22. I got that much. And counts.get is just an uncalled version of that: foo = counts.get foo('b') should return 22 as well. Think I got that as well. Where things are going pear-shaped is how counts.get can function as a 'key' when we don't actually supply () (or anything inside them) to specify what k,v pair we want, and how that relates back to the iterable for max(), counts? Monte -- Shiny! Let's be bad guys. Reach me @ memilanuk (at) gmail dot com From memilanuk at gmail.com Fri Aug 1 07:12:49 2014 From: memilanuk at gmail.com (memilanuk) Date: Thu, 31 Jul 2014 22:12:49 -0700 Subject: [Tutor] Python functions are first-class citizens In-Reply-To: <85tx5wdhcs.fsf@benfinney.id.au> References: <85tx5wdhcs.fsf@benfinney.id.au> Message-ID: <53DB21D1.3000704@gmail.com> On 07/31/2014 08:22 PM, Ben Finney wrote: > memilanuk writes: >> So... the similarity between dict.get() and dict.get as used here is >> kinda confusing me. > > I hope that helps. They are the same function; but the former is > *calling* the function object, and optionally using the return value; > the latter is referring to the function object *as* a value. Conceptually, that makes sense. Practically... having a little trouble getting my head around it - see below. >> max_key = max(counts, key=counts.get) > > This specifies ?counts.get?, without calling it. The expression > ?counts.get? evaluates to that function object. > > That value is then used as the value for the ?key? parameter when > calling ?max? here. Been reading a bit more in the mean time, trying to grok that 'key' parameter for max()... and of course the python docs for max(iterable, key=) refer to the docs for list.sort() ;) Kind of diverging off the original question a bit... but since it did include the max() code in it... I'm having a bit of difficulty with the whole 'key=' parameter when combined with counts.get here. So counts is the iterable, and counts.get is the key used to iterate through it? I guess I'm not getting how the whole key, function object bit works here in actual practice. if we have counts = {'a':1, 'b':22, 'c':100} then counts.get('b') should return 22. I got that much. And counts.get is just an uncalled version of that: foo = counts.get foo('b') should return 22 as well. Think I got that as well. Where things are going pear-shaped is how counts.get can function as a 'key' when we don't actually supply () (or anything inside them) to specify what k,v pair we want, and how that relates back to the iterable for max(), counts? Monte -- Shiny! Let's be bad guys. Reach me @ memilanuk (at) gmail dot com From alan.gauld at btinternet.com Fri Aug 1 08:32:22 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 01 Aug 2014 07:32:22 +0100 Subject: [Tutor] Python functions are first-class citizens In-Reply-To: <53DB21D1.3000704@gmail.com> References: <85tx5wdhcs.fsf@benfinney.id.au> <53DB21D1.3000704@gmail.com> Message-ID: On 01/08/14 06:12, memilanuk wrote: > counts = {'a':1, 'b':22, 'c':100} > > then counts.get('b') should return 22. I got that much. > > And counts.get is just an uncalled version of that: > > foo = counts.get > foo('b') > > should return 22 as well. Think I got that as well. Well done, thats the crux of it. > Where things are going pear-shaped is how counts.get can function as a > 'key' when we don't actually supply () (or anything inside them) The max() function calls the key function internally. Here is a trivial example (untested code!) >>> def f(aFunc): for n in range(3): print("Your function returns",aFunc(n),"with input",n) >>> >>> def g(n): return n+2 >>> >>> f(g) Your function returns 2 with input 0 Your function returns 3 with input 1 Your function returns 4 with input 2 So f calls aFunc using n internally. The specification of f requires that you pass it a function that accepts a single argument max and sort etc work the same way. They call your function internally. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From ben+python at benfinney.id.au Fri Aug 1 08:46:38 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 01 Aug 2014 16:46:38 +1000 Subject: [Tutor] Python functions are first-class citizens References: <85tx5wdhcs.fsf@benfinney.id.au> <53DB21D1.3000704@gmail.com> Message-ID: <85lhr8d7w1.fsf@benfinney.id.au> memilanuk writes: > On 07/31/2014 08:22 PM, Ben Finney wrote: > >> max_key = max(counts, key=counts.get) > > > > This specifies ?counts.get?, without calling it. The expression > > ?counts.get? evaluates to that function object. > > > > That value is then used as the value for the ?key? parameter when > > calling ?max? here. > > Been reading a bit more in the mean time, trying to grok that 'key' > parameter for max()... and of course the python docs for max(iterable, > key=) refer to the docs for list.sort() ;) The ?max? function can be told how to determine the ordering of items, by specifying a key parameter. The parameter is specified by giving a value; that value is a function. The ?max? implementation uses the ?key? parameter by calling it. So in this way, you can specify any behaviour you like, by making a function that determines ordering however you like. Generally, though, there are existing functions you can use; and a dictionary's ?get? method is one of them. This is all intentional, and is why the fact functions are first-class in Python is such a strength. > So counts is the iterable More accurately, it is a collection. Whether it is iterable isn't relevant to ?max?. > and counts.get is the key used to iterate through it? No, ?max? does not necessarily iterate; it computes (in whatever way makes sense) which item is the largest. You're specifying how items are to be compared. Iteration is irrelevant to this. > Where things are going pear-shaped is how counts.get can function as a > key' when we don't actually supply () (or anything inside them) to > specify what k,v pair we want, and how that relates back to the > iterable for max(), counts? A function is itself a value. That may take a little thinking to get your head around, but all of this merely follows as a consequence. You may also need to spend time distinguishing between syntax and value. ?foo? and ?foo()? are different in their syntax; when evaluated in an expression, they have entirely different meanings. But the latter differs only in that an extra function call occurs before evaluating the result. -- \ ?God was invented to explain mystery. God is always invented to | `\ explain those things that you do not understand.? ?Richard P. | _o__) Feynman, 1988 | Ben Finney From memilanuk at gmail.com Fri Aug 1 09:31:42 2014 From: memilanuk at gmail.com (memilanuk) Date: Fri, 01 Aug 2014 00:31:42 -0700 Subject: [Tutor] Python functions are first-class citizens In-Reply-To: <85lhr8d7w1.fsf@benfinney.id.au> References: <85tx5wdhcs.fsf@benfinney.id.au> <53DB21D1.3000704@gmail.com> <85lhr8d7w1.fsf@benfinney.id.au> Message-ID: <53DB425E.4050806@gmail.com> On 07/31/2014 11:46 PM, Ben Finney wrote: > The ?max? function can be told how to determine the ordering of items, > by specifying a key parameter. The parameter is specified by giving a > value; that value is a function. Hmmm... might just have had a break-thru here: so max() iterates thru counts, which because its the only non-keyword argument provided has to be an iterable (if I'm reading this correctly: https://docs.python.org/3/library/functions.html?highlight=max#max). It takes each dict key ('a', 'b', 'c'), feeds them in turn to counts.get() like so: counts.get('a'), counts.get('b'), counts.get('c'), which should return the corresponding dict values (1, 22, 100), and then max() returns the highest value seen. Is that about right? Monte -- Shiny! Let's be bad guys. Reach me @ memilanuk (at) gmail dot com From memilanuk at gmail.com Fri Aug 1 09:31:42 2014 From: memilanuk at gmail.com (memilanuk) Date: Fri, 01 Aug 2014 00:31:42 -0700 Subject: [Tutor] Python functions are first-class citizens In-Reply-To: <85lhr8d7w1.fsf@benfinney.id.au> References: <85tx5wdhcs.fsf@benfinney.id.au> <53DB21D1.3000704@gmail.com> <85lhr8d7w1.fsf@benfinney.id.au> Message-ID: <53DB425E.4050806@gmail.com> On 07/31/2014 11:46 PM, Ben Finney wrote: > The ?max? function can be told how to determine the ordering of items, > by specifying a key parameter. The parameter is specified by giving a > value; that value is a function. Hmmm... might just have had a break-thru here: so max() iterates thru counts, which because its the only non-keyword argument provided has to be an iterable (if I'm reading this correctly: https://docs.python.org/3/library/functions.html?highlight=max#max). It takes each dict key ('a', 'b', 'c'), feeds them in turn to counts.get() like so: counts.get('a'), counts.get('b'), counts.get('c'), which should return the corresponding dict values (1, 22, 100), and then max() returns the highest value seen. Is that about right? Monte -- Shiny! Let's be bad guys. Reach me @ memilanuk (at) gmail dot com From __peter__ at web.de Fri Aug 1 10:12:53 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 01 Aug 2014 10:12:53 +0200 Subject: [Tutor] Using subprocess on a series of files with spaces References: <20140731223533.GA4525@ando> Message-ID: C Smith wrote: > Nice, these are useful tools. I have been building something with just > basic stuff and avoiding learning any libraries. If I wanted to get > some insight on a larger program that is about 1000 lines, would that > be doable here? In general we prefer concrete questions and smaller chunks of code. With 1000 lines you get fewer people to even take a look. You might still try and post a link to the code together with a few questions here... From ben+python at benfinney.id.au Fri Aug 1 10:33:33 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 01 Aug 2014 18:33:33 +1000 Subject: [Tutor] Python functions are first-class citizens References: <85tx5wdhcs.fsf@benfinney.id.au> <53DB21D1.3000704@gmail.com> <85lhr8d7w1.fsf@benfinney.id.au> <53DB425E.4050806@gmail.com> Message-ID: <85fvhgd2xu.fsf@benfinney.id.au> memilanuk writes: > On 07/31/2014 11:46 PM, Ben Finney wrote: > > > The ?max? function can be told how to determine the ordering of > > items, by specifying a key parameter. The parameter is specified by > > giving a value; that value is a function. > > Hmmm... might just have had a break-thru here: so max() iterates thru > counts No. You should not expect ?max? to iterate through anything. All it does is compute, somehow, which item in the collection is largest. Iteration isn't relevant to that. I'm being a stickler on this point because ?iterate? implies something quite specific in Python, and this behaviour is not implied by the purpose of ?max?. Instead, think only ?finds the largest item in the collection?. > which because its the only non-keyword argument provided has to be an > iterable (if I'm reading this correctly: > https://docs.python.org/3/library/functions.html?highlight=max#max). You're reading that right. I consider that document a bit confusing, though; I would prefer instead that it says ?collection?, because whether the collection is iterable shouldn't matter. > It takes each dict key ('a', 'b', 'c') Ah! Now I get a better idea why you're confused. There are two distinct uses of ?key? going on. The dict has a key for each item, so called because the key is used to access a specific item in the dict. The ?max? operation needs a defined algorithm to determine which of two items is larger. It calls this algorithm the ?key function?, because this is the same terminology used when sorting the collection. So ?max? takes an optional function as the ?key function?, which is named ?key?. But those two uses are distinct, and the ?key function? for determining order in a sequence doesn't really relate to the key of a dict item. The terminology in computing often has conflicting uses of the same word; ?key? is unfortunately one of those words. > feeds them in turn to counts.get() like so: counts.get('a'), > counts.get('b'), counts.get('c'), which should return the > corresponding dict values (1, 22, 100), and then max() returns the > highest value seen. > > Is that about right? Roughly, except: * Computing the largest item doesn't imply iteration at all, so it's misleading to think of ?iterate? at all. The ?max? function has as its first argument a collection, whether that collection is iterable or not. * There is no guarantee all the items will be seen. ?max? could very well decide it's got the largest item and return it at any point. It's an implementation detail how it does that. * The ?key function? expected by ?max? in its ?key? parameter has no real relation to the key of a dictionary item, except by coincidence here. Broadly, you should consider the ?max? function a black box. (It's not, though, and if you're *really* curious you can inspect the source code of your particular Python implementation and see one possible way of doing it ? bearing in mind that there's no guarantee it will be implemented the same way anywhere else.) When you call the ?max? function, don't think of it doing any specific sequence of steps. You specify a collection of items; you may specify a key function to be used for determining which of two items is the larger. The result is that ?max? uses the specified key function to compute the largest item from the specified collection, and returns that item. -- \ ?Those who write software only for pay should go hurt some | `\ other field.? ?Erik Naggum, in _gnu.misc.discuss_ | _o__) | Ben Finney From ben+python at benfinney.id.au Fri Aug 1 10:38:09 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 01 Aug 2014 18:38:09 +1000 Subject: [Tutor] Using subprocess on a series of files with spaces References: <20140731223533.GA4525@ando> Message-ID: <85bns4d2q6.fsf@benfinney.id.au> Peter Otten <__peter__ at web.de> writes: > C Smith wrote: > > > Nice, these are useful tools. I have been building something with > > just basic stuff and avoiding learning any libraries. If I wanted to > > get some insight on a larger program that is about 1000 lines, would > > that be doable here? > > In general we prefer concrete questions and smaller chunks of code. > With 1000 lines you get fewer people to even take a look. Right. When attrmpting to learn, keep the examples simple. This will make it easier to focus on the essential points, and also minimise whole categories of error. To get feedback on some code, make it a Short, Self-Contained, Compilable Example . This means we will be able to read the code quickly, run it ourselves, and better see what its purpose is. > You might still try and post a link to the code together with a few > questions here... Not really advised. If the code is too long to discuss in context here, much of the point is lost; we prefer discussions to have the code inline so the public archives contain the code too. That's an important reason to keep it short and self-contained. -- \ ?I bought some batteries, but they weren't included; so I had | `\ to buy them again.? ?Steven Wright | _o__) | Ben Finney From memilanuk at gmail.com Fri Aug 1 11:37:43 2014 From: memilanuk at gmail.com (memilanuk) Date: Fri, 01 Aug 2014 02:37:43 -0700 Subject: [Tutor] Python functions are first-class citizens In-Reply-To: <85fvhgd2xu.fsf@benfinney.id.au> References: <85tx5wdhcs.fsf@benfinney.id.au> <53DB21D1.3000704@gmail.com> <85lhr8d7w1.fsf@benfinney.id.au> <53DB425E.4050806@gmail.com> <85fvhgd2xu.fsf@benfinney.id.au> Message-ID: <53DB5FE7.8020503@gmail.com> On 08/01/2014 01:33 AM, Ben Finney wrote: > Ah! Now I get a better idea why you're confused. There are two distinct > uses of ?key? going on. Ahhh... no. Yes, I realize there were two different uses of 'key' and no, I didn't think they were necessarily the same. > * There is no guarantee all the items will be seen. ?max? could very > well decide it's got the largest item and return it at any point. It's > an implementation detail how it does that. What?!? Are you serious? Under what kind of conditions? > Broadly, you should consider the ?max? function a black box. Yeah, I'm starting to see that... -- Shiny! Let's be bad guys. Reach me @ memilanuk (at) gmail dot com From memilanuk at gmail.com Fri Aug 1 11:37:43 2014 From: memilanuk at gmail.com (memilanuk) Date: Fri, 01 Aug 2014 02:37:43 -0700 Subject: [Tutor] Python functions are first-class citizens In-Reply-To: <85fvhgd2xu.fsf@benfinney.id.au> References: <85tx5wdhcs.fsf@benfinney.id.au> <53DB21D1.3000704@gmail.com> <85lhr8d7w1.fsf@benfinney.id.au> <53DB425E.4050806@gmail.com> <85fvhgd2xu.fsf@benfinney.id.au> Message-ID: <53DB5FE7.8020503@gmail.com> On 08/01/2014 01:33 AM, Ben Finney wrote: > Ah! Now I get a better idea why you're confused. There are two distinct > uses of ?key? going on. Ahhh... no. Yes, I realize there were two different uses of 'key' and no, I didn't think they were necessarily the same. > * There is no guarantee all the items will be seen. ?max? could very > well decide it's got the largest item and return it at any point. It's > an implementation detail how it does that. What?!? Are you serious? Under what kind of conditions? > Broadly, you should consider the ?max? function a black box. Yeah, I'm starting to see that... -- Shiny! Let's be bad guys. Reach me @ memilanuk (at) gmail dot com From steve at pearwood.info Fri Aug 1 16:12:15 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 2 Aug 2014 00:12:15 +1000 Subject: [Tutor] Python functions are first-class citizens In-Reply-To: <53DB5FE7.8020503@gmail.com> References: <85tx5wdhcs.fsf@benfinney.id.au> <53DB21D1.3000704@gmail.com> <85lhr8d7w1.fsf@benfinney.id.au> <53DB425E.4050806@gmail.com> <85fvhgd2xu.fsf@benfinney.id.au> <53DB5FE7.8020503@gmail.com> Message-ID: <20140801141214.GE4525@ando> On Fri, Aug 01, 2014 at 02:37:43AM -0700, memilanuk wrote: > On 08/01/2014 01:33 AM, Ben Finney wrote: > >* There is no guarantee all the items will be seen. ?max? could very > > well decide it's got the largest item and return it at any point. It's > > an implementation detail how it does that. > > What?!? Are you serious? Under what kind of conditions? Imagine a type of list which keeps a record of the largest value currently inside the list. Each time you append a new value, it compares it to the current "largest", and if bigger, changes the largest to the new value. (How you handle deletions is left as an exercise.) With this implementation, max(my_custom_list) is in principle a single, constant-time, lookup. I say in principle because I don't think Python provides any hooks for max() to take short cuts like this. But it could. Or perhaps the list is guaranteed to be sorted, in which case the max value is always the first; or you're scanning a tree, not a list, and you can find the maximum value much more efficiently than inspecting every element. Or you have a parallel processing computer which can compare all N elements and find the maximum in a single machine cycle. The point Ben is making is that one does not usually need to understand the implementation of the function to understand how to use it. Having said this, though, I find myself disagreeing with Ben's strict "ignore the implementation" stance. I sometimes find that I cannot really understand how to use a function until I've understood the algorithm it uses. It's not necessary to understand every last detail of it's implementation, but at least understanding the algorithm is useful. E.g. I don't understand the implementation of Python dicts, but I understand that they are a hash table with (I believe) linear probing, which makes it easy to see that dict look-ups are approximately constant time, degrading to linear time if all the keys have the same hash value. -- Steven From badouglas at gmail.com Fri Aug 1 16:14:38 2014 From: badouglas at gmail.com (bruce) Date: Fri, 1 Aug 2014 10:14:38 -0400 Subject: [Tutor] capturing errors/exceptions.. Message-ID: Hi. Really basic question!! Got a chunk of some test python, trying to figure out a quick/easy way to capture all/any errors/exceptions that get thrown.. For the test process, I need to "ensure" that I capture any/all potential errors.. -Could/Should I wrap the entire func in a try/catch when I call the function from the parent process? -Should I have separate try/catch blocks within the function? -The test py app is being run from the CLI, is there a py command line attribute that auto captures all errors? Any thoughts.. Thanks! A sample of the test code is: def getParseCollegeFacultyList1(url, content): s=content s=s.replace(" ","") if(debug==1): print "s="+s url=url.strip("/") #got the page/data... parse it and get the "schools".. #use the "dept" list as the school # s contains HTML not XML text d = libxml2dom.parseString(s, html=1) ########################################################### #-- #--create the output data file for the registrar/start data #-- #-- ########################################################### #term_in=201336&&sel_subj=ACCT if(debug==1): print "inside parse state/college function \n" #-----------Form------------ #fetch the option val/text for the "depts" which are used #as the dept abbrv/name on the master side #-- the school matches the dept... #-- this results in separate packets for each dept p="//a[contains(@href,'SelectTeacher') and @id='last']//attribute::href" ap="//a[contains(@href,'campusRatings.jsp')]//attribute::href" hpath="//div[@id='profInfo']/ul/li[1]//a/attribute::href" # -get the college website cpath="//div[@id='profInfo']/ul/li[2]/text()" #-get the city,state colpath="//h2/text()" #-college name xpath="//a[contains(@title,'school id:')]/attribute::href" hh_ = d.xpath(hpath) cc_ = d.xpath(cpath) col_ = d.xpath(colpath) ap_ = d.xpath(ap) if(debug==1): print "hhl "+str(len(hh_)) print "ccl "+str(len(cc_)) web="" if (len(hh_)>0): web=hh_[0].textContent city="" if (len(cc_)>0): city=cc_[0].textContent colname="" if (len(col_)>0): colname=col_[0].textContent colname=colname.encode('ascii', 'ignore').strip() # # set up out array # ret={} out={} row={} jrow="" ndx=0 pcount_ = d.xpath(p) if(len(pcount_)==0): #at least one success/entry.. but apparently only a single page.. status=True #count=pcount_[0].textContent.strip() #countp=count.split('&pageNo=') #count=countp[1] #rr=countp[0] if(len(ap_)==1): idd=ap_[0].textContent.strip() idd=idd.split("?sid=") idd=idd[1].split("&") idd=idd[0].strip() nurl=url+"/SelectTeacher.jsp?sid="+idd+"&pageNo=1" #nurl=url+"&pageNo=1" row={} row['WriteData']=True row['tmp5']=web row['tmp6']=city row['tmp7']=colname row['tmp8']=nurl #don't json for now #jrow=simplejson.dumps(row) jrow=row out[ndx]=jrow ndx = ndx+1 else: #at least one success/entry.. set the status status=True count=pcount_[0].textContent.strip() countp=count.split('&pageNo=') count=countp[1] rr=countp[0] if(debug==1): print "c ="+str(count)+"\n" for t in range(1,int(count)+1): nurl=url+rr+"&pageNo="+str(t) if(debug==1): print "nurl = "+nurl+"\n" row={} row['WriteData']=True row['tmp5']=web row['tmp6']=city row['tmp7']=colname row['tmp8']=nurl #don't json for now #jrow=simplejson.dumps(row) jrow=row out[ndx]=jrow ndx = ndx+1 ret['data']=simplejson.dumps(out) ret['count']=ndx ret['status']=status return(ret) From steve at pearwood.info Fri Aug 1 16:38:24 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 2 Aug 2014 00:38:24 +1000 Subject: [Tutor] Python functions are first-class citizens In-Reply-To: <53DB21D1.3000704@gmail.com> References: <85tx5wdhcs.fsf@benfinney.id.au> <53DB21D1.3000704@gmail.com> Message-ID: <20140801143824.GF4525@ando> On Thu, Jul 31, 2014 at 10:12:49PM -0700, memilanuk wrote: > Been reading a bit more in the mean time, trying to grok that 'key' > parameter for max()... and of course the python docs for max(iterable, > key=) refer to the docs for list.sort() ;) > > Kind of diverging off the original question a bit... but since it did > include the max() code in it... I'm having a bit of difficulty with the > whole 'key=' parameter when combined with counts.get here. To understand the key parameter, it helps to know a bit of history. Back in the Dark Ages, list.sort() didn't have a key parameter. It did, however, have a cmp parameter, but I'm going to ignore that because it worked in a completely different way, not relevant to this discussion. Suppose you wanted to do a case-insensitive sort. This was one way: data = ['narwhal', 'cat', 'DOG', 'FOX', 'lion', 'cow', 'APE', 'WALRUS'] # Make a copy of the data, recording the lower-cased values. data2 = [] for item in data: data2.append( (item.lower(), item) ) # Sort this "decorated" version. data2.sort() # Remove the lower-cased values. for i in range(len(data)): data[i] = data2[i][1] which we can write more concisely using list comprehensions: data = ['narwhal', 'cat', 'DOG', 'FOX', 'lion', 'cow', 'APE', 'WALRUS'] # Decorate: data = [(value.lower(), value) for value in data] # Sort: data.sort() # Undecorate: data = [value[1] for value in data] print data => ['APE', 'cat', 'cow', 'DOG', 'FOX', 'lion', 'narwhal', 'WALRUS'] (Wow, that brings back memories...) This is called "Decorate/Sort/Undecorate", or DSU, or sometimes "Schwartzian Transform" after a Perl programmer, Randal L. Schwartz, who popularised it. (The basic idea is *much* older than Perl.) Now, the important part is the "decorate" step. In this case, we decorate the values by calling the str.lower() method on the value. That's the only part of the process which differs depending on the data being compared, everything else: * making the tuples (transform(item), item) * sorting the subsequent list * extracting out the original items again can be handled automatically. So much so that around Python 2.3 or 2.4, list.sort() and the sorted() function gained the ability to perform DSU automatically. All you have to do is provide the transformation function, which by tradition is called a "key function", hence the argument is called "key". data = ['narwhal', 'cat', 'DOG', 'FOX', 'lion', 'cow', 'APE', 'WALRUS'] data.sort(key=str.lower) print data => ['APE', 'cat', 'cow', 'DOG', 'FOX', 'lion', 'narwhal', 'WALRUS'] We can apply this DSU idiom to maximum and minimum as well. Suppose we want to find the string with the maximum length: data = ['narwhal', 'cat', 'DOG', 'FOX', 'lion', 'cow', 'APE', 'WALRUS'] # Decorate: data2 = [(len(s), s) for s in data] # Find the maximum: x = max(data2) # Undecorate: x = x[1] print x => 'narwhal' So, max() and min() have also gained a key argument: max(data, key=len) => 'narwhal' [...] > Where things are going pear-shaped is how counts.get can function as a > 'key' when we don't actually supply () (or anything inside them) to > specify what k,v pair we want, and how that relates back to the iterable > for max(), counts? You don't have to provide the parentheses because Python does so for you. -- Steven From steve at pearwood.info Fri Aug 1 16:54:18 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 2 Aug 2014 00:54:18 +1000 Subject: [Tutor] capturing errors/exceptions.. In-Reply-To: References: Message-ID: <20140801145418.GG4525@ando> On Fri, Aug 01, 2014 at 10:14:38AM -0400, bruce wrote: > Hi. > > Really basic question!! > > Got a chunk of some test python, trying to figure out a quick/easy way > to capture all/any errors/exceptions that get thrown.. Why do you want to do that? The answer to your question will depend on what you expect to do with the exception once you've caught it, and the answer might very well be "don't do that". > For the test process, I need to "ensure" that I capture any/all > potential errors.. Hmmm. I don't quite see the reason for this. If you're running by hand, manually, surely you want to see the exceptions so that you can fix them? If there's an exception, what do you expect to do next? If you're using the unittest module, it already captures the exceptions for you, no need to re-invent the wheel. > -Could/Should I wrap the entire func in a try/catch when I call the > function from the parent process? You mean something like this? try: mymodule.function_being_test(x, y, z) except Exception: do_something_with_exception() Sure. Sounds reasonable, if you have something reasonable to do once you've captured the exception. > -Should I have separate try/catch blocks within the function? No. That means that the function is constrained by the testing regime. > -The test py app is being run from the CLI, is there a py command line > attribute that auto captures all errors? No. How would such a thing work? In general, once an exception occurs, you get a cascade of irrelevant errors: n = lne(some_data) # Oops I meant len m = 2*n + 1 # oops, this fails because n doesn't exist value = something[m] # now this fails because m doesn't exist ... Automatically recovering from an exception and continuing is not practical, hence Python halts after an exception unless you take steps to handle it yourself. -- Steven From illusiontechniques at gmail.com Fri Aug 1 18:09:17 2014 From: illusiontechniques at gmail.com (C Smith) Date: Fri, 1 Aug 2014 12:09:17 -0400 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: <85bns4d2q6.fsf@benfinney.id.au> References: <20140731223533.GA4525@ando> <85bns4d2q6.fsf@benfinney.id.au> Message-ID: >However, the subprocess call above uses a list for the command, and that form DOES NOT pass anything to the shell. The >command gets executed directly. And therefore no spaces need escaping at all. That makes more sense to me now. In terms of the code review, I found that stackexchange has a code review site, in case anyone else is curious: https://codereview.stackexchange.com It would be hard to post a sscc example since the parts I am curious about reference other class variables that would be unclear out of context, I think. Much appreciated... On Fri, Aug 1, 2014 at 4:38 AM, Ben Finney wrote: > Peter Otten <__peter__ at web.de> writes: > >> C Smith wrote: >> >> > Nice, these are useful tools. I have been building something with >> > just basic stuff and avoiding learning any libraries. If I wanted to >> > get some insight on a larger program that is about 1000 lines, would >> > that be doable here? >> >> In general we prefer concrete questions and smaller chunks of code. >> With 1000 lines you get fewer people to even take a look. > > Right. When attrmpting to learn, keep the examples simple. This will > make it easier to focus on the essential points, and also minimise whole > categories of error. > > To get feedback on some code, make it a Short, Self-Contained, > Compilable Example . This means we will be able > to read the code quickly, run it ourselves, and better see what its > purpose is. > >> You might still try and post a link to the code together with a few >> questions here... > > Not really advised. If the code is too long to discuss in context here, > much of the point is lost; we prefer discussions to have the code inline > so the public archives contain the code too. That's an important reason > to keep it short and self-contained. > > -- > \ ?I bought some batteries, but they weren't included; so I had | > `\ to buy them again.? ?Steven Wright | > _o__) | > Ben Finney > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From badouglas at gmail.com Fri Aug 1 18:36:58 2014 From: badouglas at gmail.com (bruce) Date: Fri, 1 Aug 2014 12:36:58 -0400 Subject: [Tutor] capturing errors/exceptions.. In-Reply-To: <20140801145418.GG4525@ando> References: <20140801145418.GG4525@ando> Message-ID: Clarification. The test py app is being invoked via a system function from a separate app, and not stacktrace gets created. All I have is in the /var/log/messages, an indication that the pyTest app generated an error.. This is noted by the abrtd process, but I have no other data to go on.. Which is why I'm interested in implementing some basic "capture/display" all/any error approach to get a feel for what's happening.. On Fri, Aug 1, 2014 at 10:54 AM, Steven D'Aprano wrote: > On Fri, Aug 01, 2014 at 10:14:38AM -0400, bruce wrote: >> Hi. >> >> Really basic question!! >> >> Got a chunk of some test python, trying to figure out a quick/easy way >> to capture all/any errors/exceptions that get thrown.. > > Why do you want to do that? The answer to your question will depend on > what you expect to do with the exception once you've caught it, and the > answer might very well be "don't do that". > > >> For the test process, I need to "ensure" that I capture any/all >> potential errors.. > > Hmmm. I don't quite see the reason for this. > > If you're running by hand, manually, surely you want to see the > exceptions so that you can fix them? If there's an exception, what do > you expect to do next? > > If you're using the unittest module, it already captures the exceptions > for you, no need to re-invent the wheel. > > >> -Could/Should I wrap the entire func in a try/catch when I call the >> function from the parent process? > > You mean something like this? > > try: > mymodule.function_being_test(x, y, z) > except Exception: > do_something_with_exception() > > > Sure. Sounds reasonable, if you have something reasonable to do once > you've captured the exception. > > >> -Should I have separate try/catch blocks within the function? > > No. That means that the function is constrained by the testing regime. > > >> -The test py app is being run from the CLI, is there a py command line >> attribute that auto captures all errors? > > No. How would such a thing work? In general, once an exception occurs, > you get a cascade of irrelevant errors: > > n = lne(some_data) # Oops I meant len > m = 2*n + 1 # oops, this fails because n doesn't exist > value = something[m] # now this fails because m doesn't exist > ... > > Automatically recovering from an exception and continuing is not > practical, hence Python halts after an exception unless you take steps > to handle it yourself. > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From fomcl at yahoo.com Fri Aug 1 22:23:08 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 1 Aug 2014 13:23:08 -0700 Subject: [Tutor] Using subprocess on a series of files with spaces Message-ID: <1406924588.81498.BPMail_high_noncarrier@web163802.mail.gq1.yahoo.com> ------------------------------ On Fri, Aug 1, 2014 12:35 AM CEST Steven D'Aprano wrote: >You may have already have solved your problem, unfortunately my >emails are coming in slowly and out of order, but I have a suggestion: > >On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote: >> I am on OSX, which needs to escape spaces in filenames with a backslash. > >Same as any other Unix, or Linux, or, indeed, Windows. > >> There are multiple files within one directory that all have the same >> structure, one or more characters with zero or more spaces in the >> filename, like this: >> 3 Song Title XYZ.flac. >> I want to use Python to call ffmpeg to convert each file to an .mp3. >> So far this is what I was trying to use: >> import os, subprocess >> track = 1 >> for filename in os.listdir('myDir'): >> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >> track += 1 > >I believe that your problem is *not* the spaces, but that you're passing >just the filename and not the directory. subprocess will escape the >spaces for you. Also, let Python count the track number for you. Try >this: > > >directory = '/path/to/the/directory' >for track, filename in enumerate(os.listdir(directory), 1): > pathname = os.path.join(directory, filename) > subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) Won't that write the mp3 to the current working dir? (Is that the dir where the .py lives? Or even the Python bin dir? Perhaps the cwd parameter of call() will be good? From illusiontechniques at gmail.com Fri Aug 1 22:38:57 2014 From: illusiontechniques at gmail.com (C Smith) Date: Fri, 1 Aug 2014 16:38:57 -0400 Subject: [Tutor] Using subprocess on a series of files with spaces In-Reply-To: <1406924588.81498.BPMail_high_noncarrier@web163802.mail.gq1.yahoo.com> References: <1406924588.81498.BPMail_high_noncarrier@web163802.mail.gq1.yahoo.com> Message-ID: >Won't that write the mp3 to the current working dir? (Is that the dir where the .py lives? Or even the Python bin dir? Perhaps >the cwd parameter of call() will be good? Yeah, it just wrote the mp3's to my desktop, where I had the .py script. But that was fine for my purposes. Just for curiosity's sake, would you put cwd outside the list and inside the parens of the subprocess.call()? On Fri, Aug 1, 2014 at 4:23 PM, Albert-Jan Roskam wrote: > > > > ------------------------------ > On Fri, Aug 1, 2014 12:35 AM CEST Steven D'Aprano wrote: > >>You may have already have solved your problem, unfortunately my >>emails are coming in slowly and out of order, but I have a suggestion: >> >>On Thu, Jul 31, 2014 at 03:53:48PM -0400, C Smith wrote: >>> I am on OSX, which needs to escape spaces in filenames with a backslash. >> >>Same as any other Unix, or Linux, or, indeed, Windows. >> >>> There are multiple files within one directory that all have the same >>> structure, one or more characters with zero or more spaces in the >>> filename, like this: >>> 3 Song Title XYZ.flac. >>> I want to use Python to call ffmpeg to convert each file to an .mp3. >>> So far this is what I was trying to use: >>> import os, subprocess >>> track = 1 >>> for filename in os.listdir('myDir'): >>> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) >>> track += 1 >> >>I believe that your problem is *not* the spaces, but that you're passing >>just the filename and not the directory. subprocess will escape the >>spaces for you. Also, let Python count the track number for you. Try >>this: >> >> >>directory = '/path/to/the/directory' >>for track, filename in enumerate(os.listdir(directory), 1): >> pathname = os.path.join(directory, filename) >> subprocess.call(['ffmpeg', '-i', filename, str(track)+'.mp3']) > > Won't that write the mp3 to the current working dir? (Is that the dir where the .py lives? Or even the Python bin dir? Perhaps the cwd parameter of call() will be good? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Fri Aug 1 23:26:22 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 01 Aug 2014 22:26:22 +0100 Subject: [Tutor] Python functions are first-class citizens In-Reply-To: <85fvhgd2xu.fsf@benfinney.id.au> References: <85tx5wdhcs.fsf@benfinney.id.au> <53DB21D1.3000704@gmail.com> <85lhr8d7w1.fsf@benfinney.id.au> <53DB425E.4050806@gmail.com> <85fvhgd2xu.fsf@benfinney.id.au> Message-ID: On 01/08/14 09:33, Ben Finney wrote: > I'm being a stickler on this point because ?iterate? implies something > quite specific in Python, and this behaviour is not implied by the > purpose of ?max?. > > Instead, think only ?finds the largest item in the collection?. Nope, think the largest in an iterator. The docs say iterator not collection. The max function works with generators which are not collections. Here is an example: >>> def mycount(first,limit): ... n=first ... while n < limit: ... yield n ... n += 1 ... >>> for x in mycount(1,5): ... print x ... 1 2 3 4 >>> max(mycount(2,5)) 4 >>> You don't need a collection to call max() > though; I would prefer instead that it says ?collection?, because > whether the collection is iterable shouldn't matter. But the docs say it does matter. The specification of max() is what the docs say, and they say it should be an iterable. I don't know what happens if you pass a non-iterable collection but the docs do say it should be iterable and assuming that it might work with a non-iterable is the mistake... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From varunaseneviratna at gmail.com Sat Aug 2 15:02:31 2014 From: varunaseneviratna at gmail.com (Varuna Seneviratna) Date: Sat, 2 Aug 2014 18:32:31 +0530 Subject: [Tutor] How to check the word size of the platform(OS)? Message-ID: What is the way to check the word size of the platform(OS), and also int size and character size, are they the same. I searched on line But couldn't get an answer -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Aug 2 19:04:55 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 02 Aug 2014 18:04:55 +0100 Subject: [Tutor] How to check the word size of the platform(OS)? In-Reply-To: References: Message-ID: On 02/08/14 14:02, Varuna Seneviratna wrote: > What is the way to check the word size of the platform(OS), and also int > size and character size, are they the same. I searched on line But > couldn't get an answer You need to give us more context. Word size usually depends on CPU architecture. It could be anything from 8 bit to 128 bit (and possibly more). int size and char size depend on the compiler/interpreter. For example in the TinyC compiler both int and char are 8 bits. But several C++ compilers have settings/pragmas so you can change the sizes within the limits of the target CPU. If you are talking about Python (and this is, after all, a Python list!) then int size is effectively unlimited. char size depends on the Unicode encoding you choose. It can be anything from 8 bits to 32 bits What exactly do you need to know? How do you plan on using it? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Sun Aug 3 05:41:15 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 3 Aug 2014 13:41:15 +1000 Subject: [Tutor] How to check the word size of the platform(OS)? In-Reply-To: References: Message-ID: <20140803034114.GK4525@ando> On Sat, Aug 02, 2014 at 06:32:31PM +0530, Varuna Seneviratna wrote: > What is the way to check the word size of the platform(OS), and also int > size and character size, are they the same. I searched on line But couldn't > get an answer You can get some platform details from the platform module: https://docs.python.org/2/library/platform.html but why do you need these details? Python is a high-level object-oriented language, not a low-level language like C, and native machine types aren't very often relevant. For example, Python ints are not the same as native ints, they are "Big Num" objects of unlimited size: py> sys.getsizeof(23) # returns number of bytes used 12 py> sys.getsizeof(2**30000) 4014 Just about the only things I can think of where I might want to know these sorts of low-level platform details can be handled by the struct module: https://docs.python.org/2/library/struct.html If you explain what you want to do in more detail, perhaps we can help with a better answer. -- Steven From badouglas at gmail.com Sun Aug 3 16:29:23 2014 From: badouglas at gmail.com (bruce) Date: Sun, 3 Aug 2014 10:29:23 -0400 Subject: [Tutor] try/exception - error block Message-ID: Hi. I have a long running process, it generates calls to a separate py app. The py app appears to generate errors, as indicated in the /var/log/messages file for the abrtd daemon.. The errors are intermittent. So, to quickly capture all possible exceptions/errors, I decided to wrap the entire "main" block of the test py func in a try/exception block. This didn't work, as I'm not getting any output in the err file generated in the exception block. I'm posting the test code I'm using. Pointers/comments would be helpful/useful. //////////////////// the if that gets run is the fac1 logic which operates on the input packet/data.. elif (level=='collegeFaculty1'): #getClasses(url, college, termVal,termName,deptName,deptAbbrv) ret=getParseCollegeFacultyList1(url,content) //////////////////// Thanks. if __name__ == "__main__": # main app try: #college="asu" #url="https://webapp4.asu.edu/catalog" #termurl="https://webapp4.asu.edu/catalog/TooltipTerms.ext" #termVal=2141 # # get the input struct, parse it, determine the level # #cmd='cat /apps/parseapp2/asuclass1.dat' #print "cmd= "+cmd #proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) #content=proc.communicate()[0].strip() #print content #sys.exit() #s=getClasses(content) #print "arg1 =",sys.argv[0] if(len(sys.argv)<2): print "error\n" sys.exit() a=sys.argv[1] aaa=a # # data is coming from the parentApp.php # data has been rawurlencode(json_encode(t)) # -reverse/split the data.. # -do the fetch, # -save the fetched page/content if any # -create the returned struct # -echo/print/return the struct to the # calling parent/call # ##print urllib.unquote_plus(a).decode('utf8') #print "\n" #print simplejson.loads(urllib.unquote_plus(a)) z=simplejson.loads(urllib.unquote_plus(a)) ##z=simplejson.loads(urllib.unquote(a).decode('utf8')) #z=simplejson.loads(urllib2.unquote(a).decode('utf8')) #print "aa \n" print z #print "\n bb \n" # #-passed in # url=str(z['currentURL']) level=str(z['level']) cname=str(z['parseContentFileName']) # # need to check the contentFname # -should have been checked in the parentApp # -check it anyway, return err if required # -if valid, get/import the content into # the "content" var for the function/parsing # ##cmd='echo ${yolo_clientFetchOutputDir}/' cmd='echo ${yolo_clientParseInputDir}/' #print "cmd= "+cmd proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) cpath=proc.communicate()[0].strip() cname=cpath+cname #print "cn = "+cname+"\n" #sys.exit() cmd='test -e '+cname+' && echo 1' #print "cmd= "+cmd proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) c1=proc.communicate()[0].strip() if(not c1): #got an error - process it, return print "error in parse" # # we're here, no err.. got content # #fff= "sdsu2.dat" with open(cname,"r") as myfile: content=myfile.read() myfile.close() #-passed in #college="louisville" #url="http://htmlaccess.louisville.edu/classSchedule/" #termVal="4138" #print "term = "+str(termVal)+"\n" #print "url = "+url+"\n" #jtest() #sys.exit() #getTerm(url,college,termVal) ret={} # null it out to start if (level=='rState'): #ret=getTerm(content,termVal) ret=getParseStates(content) elif (level=='stateCollegeList'): #getDepts(url,college, termValue,termName) ret=getParseStateCollegeList(url,content) elif (level=='collegeFaculty1'): #getClasses(url, college, termVal,termName,deptName,deptAbbrv) ret=getParseCollegeFacultyList1(url,content) elif (level=='collegeFaculty2'): #getClasses(url, college, termVal,termName,deptName,deptAbbrv) ret=getParseCollegeFacultyList2(content) # # the idea of this section.. we have the resulting # fetched content/page... # a={} status=False if(ret['status']==True): s=ascii_strip(ret['data']) if(((s.find("-1) or (s.find("-1)) and ((s.find("-1) or (s.find("-1)) and level=='classSectionDay'): status=True #print "herh" #sys.exit() # # build the returned struct # # a['Status']=True a['recCount']=ret['count'] a['data']=ret['data'] a['nextLevel']='' a['timestamp']='' a['macAddress']='' elif(ret['status']==False): a['Status']=False a['recCount']=0 a['data']='' a['nextLevel']='' a['timestamp']='' a['macAddress']='' res=urllib.quote(simplejson.dumps(a)) ##print res name=subprocess.Popen('uuidgen -t', shell=True,stdout=subprocess.PIPE) name=name.communicate()[0].strip() name=name.replace("-","_") ## if status==True: name2=tmpParseDir+"/rr_"+name+".dat" ofile1=open(name2,"w+") ofile1.write(res) ofile1.close() print name2 if status==False: sname=tmpParseDir+"/serr_"+name+".dat" ofile1=open(sname,"w+") ofile1.write(aaa) ofile1.close() sys.exit() print "term = "+str(termVal)+"\n" print "url = "+url+"\n" getTerm(url,college,termVal) print "exit" sys.exit() except Exception, e: print e print "pycolFac1 - error!! \n"; name=subprocess.Popen('uuidgen -t', shell=True,stdout=subprocess.PIPE) name=name.communicate()[0].strip() name=name.replace("-","_") name2="/home/ihubuser/parseErrTest/pp_"+name+".dat" ofile1=open(name2,"w+") ofile1.write(e) ofile1.write(aaa) ofile1.close() sys.exit() From steve at pearwood.info Sun Aug 3 17:47:37 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 4 Aug 2014 01:47:37 +1000 Subject: [Tutor] try/exception - error block In-Reply-To: References: Message-ID: <20140803154737.GM4525@ando> On Sun, Aug 03, 2014 at 10:29:23AM -0400, bruce wrote: > Hi. > > I have a long running process, it generates calls to a separate py > app. The py app appears to generate errors, as indicated in the > /var/log/messages file for the abrtd daemon.. The errors are > intermittent. Well, what do the errors say? > So, to quickly capture all possible exceptions/errors, I decided to > wrap the entire "main" block of the test py func in a try/exception > block. I don't understand what you mean here. You're using abbreviations I don't understand -- are you just being a lazy typist, or do they have some specific meaning I'm missing? What's a "test py func"? How does it relate to the long running process (written in what language?) and the "py app" that is generating errors? Where does the "abrtd daemon" fit into this? I'm sure your code is really familiar to you, but it isn't familiar to us, so taking shortcuts and abbreviations when describing it will just lead to confusion. We don't know your code, and we don't know your level of knowledge. Since this is a mailing list for beginners, it's natural to assume that you must be a beginner too, so when you call something a "daemon", does that mean it actually is a Unix daemon, or are you just using the wrong word? > This didn't work, as I'm not getting any output in the err file > generated in the exception block. I see your except block tries printing some things. Do they appear anywhere? I wouldn't expect so, if it actually is running as a daemon, since daemons have no access to stdout and stderr. > I'm posting the test code I'm using. Pointers/comments would be helpful/useful. For starters, cut out all the old, long dead code. We don't need, or want, to see the fossilised remains of your code as it was six versions back, we want to see how it is *now*. That includes comments which no longer have any relevance to your code. Secondly, you should try to reduce the problem to the smallest possible amount of code. Simplify, simplify, simplify: cut out everything which is not relevant to the actual issue at hand. > //////////////////// > the if that gets run is the fac1 logic which operates on the input > packet/data.. > elif (level=='collegeFaculty1'): > #getClasses(url, college, termVal,termName,deptName,deptAbbrv) > ret=getParseCollegeFacultyList1(url,content) > //////////////////// I'm afraid I don't have the foggiest idea of what you're trying to say here. > if __name__ == "__main__": > # main app > > try: [deleting lots of commented out code] > if(len(sys.argv)<2): > print "error\n" > sys.exit() You really should raise an exception on errors, but if you insist on doing things this way, you should print to stderr, not stdout, and you should exit with a non-zero status: print >>sys.stdout, "descriptive error messages are better\n" sys.exit(101) > a=sys.argv[1] > aaa=a A minor stylistic thing: you can write this as: a = aaa = sys.argv[1] but of course you really ought to use descriptive variable names rather than cryptic "a" and "aaa" and "z" and other meaningless names. [deleting more fossil code] > z=simplejson.loads(urllib.unquote_plus(a)) > print z > url=str(z['currentURL']) > level=str(z['level']) > cname=str(z['parseContentFileName']) > cmd='echo ${yolo_clientParseInputDir}/' > proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) > cpath=proc.communicate()[0].strip() Hmmm. Are you trying to read the value of an environment variable using subprocess? If so, then try this instead: cpath = os.getenv('yolo_clientParseInputDir') If not, then sorry for the noise. Perhaps you could explain what your call to echo in the shell is meant to do? > cname=cpath+cname > cmd='test -e '+cname+' && echo 1' > proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) > c1=proc.communicate()[0].strip() And here I think you're trying to test whether a file exists? os.path.exists(cname) > if(not c1): > #got an error - process it, return > print "error in parse" Um, surely not? Surely the error is that the file doesn't exist, not that it is a parsing error? > with open(cname,"r") as myfile: > content=myfile.read() > myfile.close() If you use the "with open" form, there is no need to manually close the file, it will be automatically closed for you. with open(cname,"r") as myfile: content = myfile.read() is all you need (assuming you have permission to open the file, and that it still exists). [lots more fossils deleted] > ret={} # null it out to start > if (level=='rState'): > ret=getParseStates(content) > elif (level=='stateCollegeList'): > ret=getParseStateCollegeList(url,content) > elif (level=='collegeFaculty1'): > ret=getParseCollegeFacultyList1(url,content) > elif (level=='collegeFaculty2'): > ret=getParseCollegeFacultyList2(content) I'm not really sure if any of that code is relevant to the problem you're having. > a={} > status=False > if(ret['status']==True): > s=ascii_strip(ret['data']) > if(((s.find("-1) or (s.find("-1)) and > ((s.find("-1) or (s.find("-1)) and > level=='classSectionDay'): > status=True > a['Status']=True > a['recCount']=ret['count'] > a['data']=ret['data'] > a['nextLevel']='' > a['timestamp']='' > a['macAddress']='' > elif(ret['status']==False): > a['Status']=False > a['recCount']=0 > a['data']='' > a['nextLevel']='' > a['timestamp']='' > a['macAddress']='' > res=urllib.quote(simplejson.dumps(a)) Your code will be much, much, much more readable if you use a reasonable indent between levels. Four spaces rather than two, or a tab. I'm finding it quite difficult to keep track of the levels when they are so close together. > name=subprocess.Popen('uuidgen -t', shell=True,stdout=subprocess.PIPE) > name=name.communicate()[0].strip() > name=name.replace("-","_") > name2=tmpParseDir+"/rr_"+name+".dat" > ofile1=open(name2,"w+") > ofile1.write(res) > ofile1.close() > print name2 So does this file get written to? Does name2 get printed? > if status==False: > sname=tmpParseDir+"/serr_"+name+".dat" > ofile1=open(sname,"w+") > ofile1.write(aaa) > ofile1.close() How about this one? Does it get written to? > sys.exit() Since you exit here, the rest of the code in the block is never executed: > print "term = "+str(termVal)+"\n" > print "url = "+url+"\n" > getTerm(url,college,termVal) > print "exit" > sys.exit() That's all dead code. I hope it isn't important. > except Exception, e: > print e > print "pycolFac1 - error!! \n"; Does that get printed? > name=subprocess.Popen('uuidgen -t', shell=True,stdout=subprocess.PIPE) > name=name.communicate()[0].strip() > name=name.replace("-","_") > name2="/home/ihubuser/parseErrTest/pp_"+name+".dat" > ofile1=open(name2,"w+") > ofile1.write(e) > ofile1.write(aaa) > ofile1.close() > sys.exit() That's awfully ambitious code for an except clause that you're not even sure is working. Simplify, simplify, simplify. except Exception, e: with open("/tmp/myerror.txt", "w") as f: f.write("%r" % e) sys.exit(102) Now you should be able to see the error written to the file, which you should have write privileges to unless you're doing something very unusual. -- Steven From badouglas at gmail.com Sun Aug 3 19:52:13 2014 From: badouglas at gmail.com (bruce) Date: Sun, 3 Aug 2014 13:52:13 -0400 Subject: [Tutor] try/exception - error block In-Reply-To: References: Message-ID: chris.. my bad.. I wasnt intending to mail you personally. Or I wouldn't have inserted the "thanks guys"! > thanks guys... > > but in all that.. no one could tell me .. why i'm not getting any > errs/exceptions in the err file which gets created on the exception!!! > > but thanks for the information on posting test code! Don't email me privately - respond to the list :) Also, please don't top-post. ChrisA On Sun, Aug 3, 2014 at 10:29 AM, bruce wrote: > Hi. > > I have a long running process, it generates calls to a separate py > app. The py app appears to generate errors, as indicated in the > /var/log/messages file for the abrtd daemon.. The errors are > intermittent. > > So, to quickly capture all possible exceptions/errors, I decided to > wrap the entire "main" block of the test py func in a try/exception > block. > > This didn't work, as I'm not getting any output in the err file > generated in the exception block. > > I'm posting the test code I'm using. Pointers/comments would be helpful/useful. > > //////////////////// > the if that gets run is the fac1 logic which operates on the input > packet/data.. > elif (level=='collegeFaculty1'): > #getClasses(url, college, termVal,termName,deptName,deptAbbrv) > ret=getParseCollegeFacultyList1(url,content) > //////////////////// > > Thanks. > > if __name__ == "__main__": > # main app > > try: > #college="asu" > #url="https://webapp4.asu.edu/catalog" > #termurl="https://webapp4.asu.edu/catalog/TooltipTerms.ext" > > > #termVal=2141 > # > # get the input struct, parse it, determine the level > # > > #cmd='cat /apps/parseapp2/asuclass1.dat' > #print "cmd= "+cmd > #proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) > #content=proc.communicate()[0].strip() > #print content > #sys.exit() > > #s=getClasses(content) > > #print "arg1 =",sys.argv[0] > if(len(sys.argv)<2): > print "error\n" > sys.exit() > > a=sys.argv[1] > aaa=a > > # > # data is coming from the parentApp.php > # data has been rawurlencode(json_encode(t)) > # -reverse/split the data.. > # -do the fetch, > # -save the fetched page/content if any > # -create the returned struct > # -echo/print/return the struct to the > # calling parent/call > # > > ##print urllib.unquote_plus(a).decode('utf8') > #print "\n" > #print simplejson.loads(urllib.unquote_plus(a)) > z=simplejson.loads(urllib.unquote_plus(a)) > ##z=simplejson.loads(urllib.unquote(a).decode('utf8')) > #z=simplejson.loads(urllib2.unquote(a).decode('utf8')) > > #print "aa \n" > print z > #print "\n bb \n" > > # > #-passed in > # > url=str(z['currentURL']) > level=str(z['level']) > cname=str(z['parseContentFileName']) > > > # > # need to check the contentFname > # -should have been checked in the parentApp > # -check it anyway, return err if required > # -if valid, get/import the content into > # the "content" var for the function/parsing > # > > ##cmd='echo ${yolo_clientFetchOutputDir}/' > cmd='echo ${yolo_clientParseInputDir}/' > #print "cmd= "+cmd > proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) > cpath=proc.communicate()[0].strip() > > cname=cpath+cname > #print "cn = "+cname+"\n" > #sys.exit() > > > cmd='test -e '+cname+' && echo 1' > #print "cmd= "+cmd > proc=subprocess.Popen(cmd, shell=True,stdout=subprocess.PIPE) > c1=proc.communicate()[0].strip() > > if(not c1): > #got an error - process it, return > print "error in parse" > > # > # we're here, no err.. got content > # > > #fff= "sdsu2.dat" > with open(cname,"r") as myfile: > content=myfile.read() > myfile.close() > > > #-passed in > #college="louisville" > #url="http://htmlaccess.louisville.edu/classSchedule/" > #termVal="4138" > > > #print "term = "+str(termVal)+"\n" > #print "url = "+url+"\n" > > #jtest() > #sys.exit() > > #getTerm(url,college,termVal) > > > ret={} # null it out to start > if (level=='rState'): > #ret=getTerm(content,termVal) > ret=getParseStates(content) > > elif (level=='stateCollegeList'): > #getDepts(url,college, termValue,termName) > ret=getParseStateCollegeList(url,content) > > elif (level=='collegeFaculty1'): > #getClasses(url, college, termVal,termName,deptName,deptAbbrv) > ret=getParseCollegeFacultyList1(url,content) > > elif (level=='collegeFaculty2'): > #getClasses(url, college, termVal,termName,deptName,deptAbbrv) > ret=getParseCollegeFacultyList2(content) > > > > # > # the idea of this section.. we have the resulting > # fetched content/page... > # > > a={} > status=False > if(ret['status']==True): > > s=ascii_strip(ret['data']) > if(((s.find("-1) or (s.find("-1)) and > ((s.find("-1) or (s.find("-1)) and > level=='classSectionDay'): > > status=True > #print "herh" > #sys.exit() > > # > # build the returned struct > # > # > > a['Status']=True > a['recCount']=ret['count'] > a['data']=ret['data'] > a['nextLevel']='' > a['timestamp']='' > a['macAddress']='' > elif(ret['status']==False): > a['Status']=False > a['recCount']=0 > a['data']='' > a['nextLevel']='' > a['timestamp']='' > a['macAddress']='' > > res=urllib.quote(simplejson.dumps(a)) > ##print res > > name=subprocess.Popen('uuidgen -t', shell=True,stdout=subprocess.PIPE) > name=name.communicate()[0].strip() > name=name.replace("-","_") > > > ## if status==True: > name2=tmpParseDir+"/rr_"+name+".dat" > ofile1=open(name2,"w+") > ofile1.write(res) > ofile1.close() > print name2 > > if status==False: > sname=tmpParseDir+"/serr_"+name+".dat" > ofile1=open(sname,"w+") > ofile1.write(aaa) > ofile1.close() > > > sys.exit() > > > > > print "term = "+str(termVal)+"\n" > print "url = "+url+"\n" > > getTerm(url,college,termVal) > > > print "exit" > sys.exit() > > except Exception, e: > print e > print "pycolFac1 - error!! \n"; > name=subprocess.Popen('uuidgen -t', shell=True,stdout=subprocess.PIPE) > name=name.communicate()[0].strip() > name=name.replace("-","_") > name2="/home/ihubuser/parseErrTest/pp_"+name+".dat" > ofile1=open(name2,"w+") > ofile1.write(e) > ofile1.write(aaa) > ofile1.close() > > sys.exit() From badouglas at gmail.com Sun Aug 3 23:33:06 2014 From: badouglas at gmail.com (bruce) Date: Sun, 3 Aug 2014 17:33:06 -0400 Subject: [Tutor] try/exception - error block In-Reply-To: References: Message-ID: Hi Alan. Yep, the err file in the exception block gets created. and the weird thing is it matches the time of the abrtd information in the /var/log/messages log.. Just nothing in the file! On Sun, Aug 3, 2014 at 4:01 PM, Alan Gauld wrote: > On 03/08/14 18:52, bruce wrote: > >>> but in all that.. no one could tell me .. why i'm not getting any >>> errs/exceptions in the err file which gets created on the exception!!! > > > Does the file actually get created? > Do you see the print statement output - are they what you expect? > > Did you try the things Steven suggested. > > >>> except Exception, e: >>> print e >>> print "pycolFac1 - error!! \n"; >>> name=subprocess.Popen('uuidgen -t', >>> shell=True,stdout=subprocess.PIPE) >>> name=name.communicate()[0].strip() >>> name=name.replace("-","_") > > > This is usually a bad idea. You are using name for the process and its > output. Use more names... > What about: > > uuid=subprocess.Popen('uuidgen -t',shell=True,stdout=subprocess.PIPE) > output=uuid.communicate()[0].strip() > name=output.replace("-","_") > >>> name2="/home/ihubuser/parseErrTest/pp_"+name+".dat" > > > This would be a good place to insert a print > > print name2 > >>> ofile1=open(name2,"w+") > > > Why are you using w+ mode? You are only writing. > Keep life as simple as possible. > >>> ofile1.write(e) > > > e is quite likely to be empty > >>> ofile1.write(aaa) > > > Are you sure aaa exists at this point? Remember you are catching all errors > so if an error happens prior to aaa being created this will > fail. > >>> ofile1.close() > > > You used the with form earlier, why not here too. > It's considered better style... > > Some final comments. > 1) You call sys.exit() several times inside > the try block. sys.exit will not be caught by your except block, > is that what you expect?. > > 2) The combination of confusing naming of variables, > reuse of names and poor code layout and excessive commented > code makes it very difficult to read your code. > That makes it hard to figure out what might be going on. > - Use sensible variable names not a,aaa,z, etc > - use 3 or 4 level indentation not 2 > - use a version control system (RCS,CVS, SVN,...) instead > of commenting out big blocks > - use consistent code style > eg with f as ... or open(f)/close(f) but not both > - use the os module (and friends) instead of subprocess if possible > > 3) Have you tried deleting all the files in the > /home/ihubuser/parseErrTest/ folder and starting again, > just to be sure that your current code is actually > producing the empty files? > > 4) You use tmpParseDir in a couple of places but I don't > see it being set anywhere? > > > That's about the best I can offer based on the > information available. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > -- > https://mail.python.org/mailman/listinfo/python-list From mccombs at imperium.org Mon Aug 4 17:20:41 2014 From: mccombs at imperium.org (P McCombs) Date: Mon, 4 Aug 2014 08:20:41 -0700 Subject: [Tutor] Need help with python script In-Reply-To: References: <943FD0A7C6E2C346A4658BE83E1B1BFF49787C2E@MAWSSEXCH3.mawss.com> Message-ID: Sorry, I missed copying this to the list. On Aug 4, 2014 8:13 AM, "P McCombs" wrote: > > > On Jul 31, 2014 4:50 PM, "McKinley, Brett D." wrote: > > > > I would like to see if someone can help me with a python script. I?m trying to export a file geodatabase feature class to csv file. This is what I have so far: > > Does the code you attached execute successfully? > Are you running this as a tool, or from the command line? > Be cautioned that arcpy is outside the scope of this mailing list, but it won't have much to do with your questions at first. > > > > > > > import arcpy > > > > import os > > > > import csv > > > > import domainvalues > > > > > > > > > > > > def export_to_csv(dataset, output, dialect): > > > > """Output the data to a CSV file""" > > > > # create the output writer > > > > out_writer = csv.writer(open(output, 'wb'), dialect=dialect) > > > > # return the list of field names and field values > > > > header, rows = domainvalues.header_and_iterator(dataset) > > > > > > > > # write the field names and values to the csv file > > > > out_writer.writerow(map(domainvalues._encodeHeader, header)) > > > > for row in rows: > > > > out_writer.writerow(map(domainvalues._encode, row)) > > > > > > > > if __name__ == "__main__": > > > > # Get parameters > > > > dataset_name = arcpy.GetParameterAsText(0) > > > > output_file = arcpy.GetParameterAsText(1) > > > > delim = arcpy.GetParameterAsText(2).lower() > > > > dialect = 'excel' > > > > if delim == 'comma': > > > > pass > > > > else: > > > > dialect = 'excel-tab' > > > > try: > > > > export_to_csv(dataset_name, output_file, dialect) > > > > except Exception as err: > > > > arcpy.AddError('Error: {0}'.format(err)) > > > > > > > > > > > > I would like for the script to export only certain fields and also export only the newest records. As for now, it?s exporting everything. > > > > It is best to try to add one new feature on your own and attach the result. You will get the best feedback that way. > > > > > > > Thanks > > > > Brett McKinley > > > > > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > >https://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Aug 4 18:28:13 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 4 Aug 2014 12:28:13 -0400 Subject: [Tutor] Need help with python script In-Reply-To: References: <943FD0A7C6E2C346A4658BE83E1B1BFF49787C2E@MAWSSEXCH3.mawss.com> Message-ID: On Mon, Aug 4, 2014 at 11:20 AM, P McCombs wrote: > Sorry, I missed copying this to the list. > > On Aug 4, 2014 8:13 AM, "P McCombs" wrote: > > >> >> >> On Jul 31, 2014 4:50 PM, "McKinley, Brett D." wrote: >> > >> > I would like to see if someone can help me with a python script. I?m >> > trying to export a file geodatabase feature class to csv file. This is what >> > I have so far: >> >> Does the code you attached execute successfully? >> Are you running this as a tool, or from the command line? >> Be cautioned that arcpy is outside the scope of this mailing list, but it >> won't have much to do with your questions at first. > >> >> > >> > >> > import arcpy >> > >> > import os >> > >> > import csv >> > >> > import domainvalues >> > >> > >> > >> > >> > >> > def export_to_csv(dataset, output, dialect): >> > >> > """Output the data to a CSV file""" >> > >> > # create the output writer >> > >> > out_writer = csv.writer(open(output, 'wb'), dialect=dialect) >> > >> > # return the list of field names and field values >> > >> > header, rows = domainvalues.header_and_iterator(dataset) >> > >> > >> > >> > # write the field names and values to the csv file >> > >> > out_writer.writerow(map(domainvalues._encodeHeader, header)) >> > >> > for row in rows: before you write row, you need to examine the appropriate fields to filter out the fields you don't want, and order the rows by whichever field determines newness. Also, you probably want to output your header row to only include columns you wish to write >> > >> > out_writer.writerow(map(domainvalues._encode, row)) >> > >> > >> > >> > if __name__ == "__main__": >> > >> > # Get parameters >> > >> > dataset_name = arcpy.GetParameterAsText(0) >> > >> > output_file = arcpy.GetParameterAsText(1) >> > >> > delim = arcpy.GetParameterAsText(2).lower() >> > >> > dialect = 'excel' >> > >> > if delim == 'comma': >> > >> > pass >> > >> > else: >> > >> > dialect = 'excel-tab' >> > >> > try: >> > >> > export_to_csv(dataset_name, output_file, dialect) >> > >> > except Exception as err: >> > >> > arcpy.AddError('Error: {0}'.format(err)) >> > >> > >> > >> > >> > >> > I would like for the script to export only certain fields and also >> > export only the newest records. As for now, it?s exporting everything. >> > >> >> It is best to try to add one new feature on your own and attach the >> result. You will get the best feedback that way. >> >> > >> > >> > Thanks >> > >> > Brett McKinley >> > >> > >> > >> > >> > >> > >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > To unsubscribe or change subscription options: >> >https://mail.python.org/mailman/listinfo/tutor >> > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From greg.markham at gmail.com Mon Aug 4 19:28:54 2014 From: greg.markham at gmail.com (Greg Markham) Date: Mon, 4 Aug 2014 10:28:54 -0700 Subject: [Tutor] New to Python - print function - invalid syntax Message-ID: Hello, I'm extremely new to Python having only just started learning this week. I'm slowly plodding through a book, Python Programming for the Absolute Beginner, 3rd ed by Michael Dawson. Code is provided for all the scripts found throughout the book (found here ), but I'm running into a syntax error when running one of the unmodified programs. On line 14, which reads: *print("Here", end=" ")* I'm receiving a *syntax error* which points to the *end *parameter. In order to confirm this, I modified the code to read: *print("Here ")* ...which runs without incident. My best guess is that there's a minor difference between the version of Python I'm using (3.4.1) and that which was in use at the time the book was written (3.1.x) that is responsible for this error. Thanks and my apologies for the "greenness" of this question. Sincerely, Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From rnmathieu254 at gmail.com Mon Aug 4 16:10:31 2014 From: rnmathieu254 at gmail.com (=?UTF-8?Q?Ren=C3=A9_Mathieu?=) Date: Mon, 4 Aug 2014 16:10:31 +0200 Subject: [Tutor] Python; webcam Message-ID: Hello there I'm writing a Python program and I would like to display a video device (webcam). How should I write in the program? thank you very much MATHIEU Ren? -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Aug 4 20:52:25 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 4 Aug 2014 14:52:25 -0400 Subject: [Tutor] New to Python - print function - invalid syntax In-Reply-To: References: Message-ID: On Mon, Aug 4, 2014 at 1:28 PM, Greg Markham wrote: > Hello, > > I'm extremely new to Python having only just started learning this week. > I'm slowly plodding through a book, Python Programming for the Absolute > Beginner, 3rd ed by Michael Dawson. > > Code is provided for all the scripts found throughout the book (found here), > but I'm running into a syntax error when running one of the unmodified > programs. On line 14, which reads: > > print("Here", end=" ") > > I'm receiving a syntax error which points to the end parameter. In order to > confirm this, I modified the code to read: > > print("Here ") > > ...which runs without incident. My best guess is that there's a minor > difference between the version of Python I'm using (3.4.1) and that which > was in use at the time the book was written (3.1.x) that is responsible for > this error. Welcome to the group. I think you made a typo. Your code should run. I just tried this: >>> print("hi", end=" ") hi >>> A couple of things that will make it easier to help: 1. send mail as plain text. Rich text causes some readers problems 2. copy and paste the code and complete traceback. retyping things make it more likely that what is in your code isn't exactly what you typed > > Thanks and my apologies for the "greenness" of this question. No apologies necessary -- ask away > > Sincerely, > > Greg > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From dyoo at hashcollision.org Mon Aug 4 22:38:29 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 4 Aug 2014 13:38:29 -0700 Subject: [Tutor] New to Python - print function - invalid syntax In-Reply-To: References: Message-ID: > > but I'm running into a syntax error when running one of the unmodified > > programs. On line 14, which reads: > > > > print("Here", end=" ") > > > > I'm receiving a syntax error which points to the end parameter. I'd like to also support Joel's suggestion to provide detailed output of the error message. It will help. > > difference between the version of Python I'm using (3.4.1) and that which > > was in use at the time the book was written (3.1.x) that is responsible for > > this error. Just to double check: how are you confirming what version of Python you're using? Best of wishes! -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Mon Aug 4 22:55:36 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 4 Aug 2014 13:55:36 -0700 Subject: [Tutor] Python; webcam In-Reply-To: References: Message-ID: On Mon, Aug 4, 2014 at 7:10 AM, Ren? Mathieu wrote: > Hello there > > I'm writing a Python program and I would like to display a video device > (webcam). How should I write in the program? Hi Mathieu Ren?, I'm unsure because I have no direct experience with this. You might want to check the general Python mailing list if you don't get other answers from the tutors here. There is no built-in support in the Standard LIbrary to a webcam; however, there appear to be external libraries that provide access to a webcam. From a web search, it looks like the Pygame library might be applicable: http://www.pygame.org/docs/tut/camera/CameraIntro.html. You might also be able to look into the PythonCV library: http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html From vipul.sharma20 at gmail.com Mon Aug 4 23:05:29 2014 From: vipul.sharma20 at gmail.com (Vipul Sharma) Date: Tue, 5 Aug 2014 02:35:29 +0530 Subject: [Tutor] Python; webcam In-Reply-To: References: Message-ID: You should try Computer Vision libraries for python like OpenCV and SimpleCV. They are best for playing with the camera, videos and for image processing tasks. My personal favorite is OpenCV you should definitely try it. https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_setup/py_intro/py_intro.html#intro On Tue, Aug 5, 2014 at 2:25 AM, Danny Yoo wrote: > On Mon, Aug 4, 2014 at 7:10 AM, Ren? Mathieu > wrote: > > Hello there > > > > I'm writing a Python program and I would like to display a video device > > (webcam). How should I write in the program? > > > Hi Mathieu Ren?, > > I'm unsure because I have no direct experience with this. You might > want to check the general Python mailing list if you don't get other > answers from the tutors here. > > There is no built-in support in the Standard LIbrary to a webcam; > however, there appear to be external libraries that provide access to > a webcam. From a web search, it looks like the Pygame library might > be applicable: > http://www.pygame.org/docs/tut/camera/CameraIntro.html. You might > also be able to look into the PythonCV library: > > http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Vipul Sharma Jabalpur Engineering College +91-8827931450 -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Tue Aug 5 00:55:53 2014 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 5 Aug 2014 08:55:53 +1000 Subject: [Tutor] New to Python - print function - invalid syntax In-Reply-To: References: Message-ID: <20140804225553.GA60412@cskk.homeip.net> On 04Aug2014 13:38, Danny Yoo wrote: >> > difference between the version of Python I'm using (3.4.1) and that which >> > was in use at the time the book was written (3.1.x) that is responsible >> > for this error. > >Just to double check: how are you confirming what version of Python you're >using? In particular, Python 2 will produce a syntax error for your print statement; Python 3 should work. Show a short transcript which also shows your ptyhon version. Example: $ python Python 2.7.8 (default, Jul 13 2014, 17:11:32) [GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print("hi", end=" ") File "", line 1 print("hi", end=" ") ^ SyntaxError: invalid syntax Versus: $ python3.4 Python 3.4.1 (default, May 21 2014, 01:39:38) [GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print("hi", end=" ") hi >>> The "$" is my prompt. Any Python 3 should accept your print() call. The default system "python" on most platforms is still Python 2; that may be misleading you. In particular, if you're running a script you may need to ensure it is run with the correct Python version. It is perfectly fine to have multiple Python versions installed, BTW. Just make sure you're using what you intend. Cheers, Cameron Simpson From greg.markham at gmail.com Tue Aug 5 01:21:53 2014 From: greg.markham at gmail.com (Greg Markham) Date: Mon, 4 Aug 2014 16:21:53 -0700 Subject: [Tutor] New to Python - print function - invalid syntax In-Reply-To: <6a5af6bdc2c8009c65cf628c52d9938b@sonic.net> References: <6a5af6bdc2c8009c65cf628c52d9938b@sonic.net> Message-ID: On Mon, Aug 4, 2014 at 12:37 PM, Alex Kleider wrote: > On 2014-08-04 10:28, Greg Markham wrote: > >> Hello, >> >> I'm extremely new to Python having only just started learning this week. >> I'm slowly plodding through a book, Python Programming for the Absolute >> Beginner, 3rd ed >> > Edition/dp/1435455002/ref=sr_1_5?ie=UTF8&qid=1407049249&sr= >> 8-5&keywords=learning+python> >> >> by Michael Dawson. >> >> Code is provided for all the scripts found throughout the book (found here >> > 1435455002/downloads/py3e_source.zip>), >> >> but I'm running into a syntax error when running one of the unmodified >> programs. On line 14, which reads: >> >> *print("Here", end=" ")* >> > try > > print("Here", end="") > > (no space between the quotes) > The end parameter defaults to newline. > If you change it to the empty string, there'll be no output of a newline > character. > As I understand it, newline is inferred unless the "end" parameter is used. This program is designed merely to illustrate the flexibility of the print function. As you'll see below, the output from the line in which I was receiving an error is intended to read as, "Here it is..." For clarity, the full program reads as follows: # Game Over - Version 2 # Demonstrates the use of quotes in strings # Python Programming for the Absolute Beginner, 3rd ed - Ch 2 # Greg Markham - Aug 04, 2014 print("Program 'Game Over' 2.0") print("Same", "message", "as before") print("Just", "a bit", "bigger") print("Here", end=" ") print("it is...") print( """ _____ ___ ___ ___ _____ / ___| / | / |/ | | ___| | | / /| | / /| /| | | |__ | | _ / ___ | / / |__/ | | | __| | |_| | / / | | / / | | | |___ \_____/ /_/ |_| /_/ |_| |_____| _____ _ _ _____ _____ / _ \ | | / / | ___| | _ \ | | | | | | / / | |__ | |_| | | | | | | | / / | __| | _ / | |_| | | |/ / | |___ | | \ \ \_____/ |___/ |_____| |_| \_\ """ ) input("\n\nPress the enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg.markham at gmail.com Tue Aug 5 01:24:02 2014 From: greg.markham at gmail.com (Greg Markham) Date: Mon, 4 Aug 2014 16:24:02 -0700 Subject: [Tutor] Fwd: New to Python - print function - invalid syntax In-Reply-To: References: Message-ID: On Mon, Aug 4, 2014 at 1:38 PM, Danny Yoo wrote: > > > > but I'm running into a syntax error when running one of the unmodified > > > programs. On line 14, which reads: > > > > > > print("Here", end=" ") > > > > > > I'm receiving a syntax error which points to the end parameter. > > I'd like to also support Joel's suggestion to provide detailed output of > the error message. It will help. > Here is the full context of the error message: File "I:\Programming\Scripts\Learning\Chapter02\game_over2.py", line 14 print("Here", end=" ") #Modified from: print("Here", end=" ") ^ SyntaxError: invalid syntax > > > difference between the version of Python I'm using (3.4.1) and that > which > > > was in use at the time the book was written (3.1.x) that is > responsible for > > > this error. > > Just to double check: how are you confirming what version of Python you're > using? > >From command line, C:\> python -V > Best of wishes! > -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg.markham at gmail.com Tue Aug 5 01:44:46 2014 From: greg.markham at gmail.com (Greg Markham) Date: Mon, 4 Aug 2014 16:44:46 -0700 Subject: [Tutor] New to Python - print function - invalid syntax In-Reply-To: References: Message-ID: On Mon, Aug 4, 2014 at 11:52 AM, Joel Goldstick wrote: > On Mon, Aug 4, 2014 at 1:28 PM, Greg Markham > wrote: > > Hello, > > > > I'm extremely new to Python having only just started learning this week. > > I'm slowly plodding through a book, Python Programming for the Absolute > > Beginner, 3rd ed by Michael Dawson. > > > > Code is provided for all the scripts found throughout the book (found > here), > > but I'm running into a syntax error when running one of the unmodified > > programs. On line 14, which reads: > > > > print("Here", end=" ") > > > > I'm receiving a syntax error which points to the end parameter. In > order to > > confirm this, I modified the code to read: > > > > print("Here ") > > > > ...which runs without incident. My best guess is that there's a minor > > difference between the version of Python I'm using (3.4.1) and that which > > was in use at the time the book was written (3.1.x) that is responsible > for > > this error. > > Welcome to the group. I think you made a typo. Your code should run. > I just tried this: > >>> print("hi", end=" ") > hi >>> > Ok, when I try this from the Shell window, it works. When executing the full program from command line, it does not. Python versions from both shell and command line are 3.4.1 (confirmed via command: "python -V"). Full error msg output when run from cmd line reads: File "I:\Programming\Scripts\Learning\chapter02\game_over2.py", line 14 print("Here", end=" ") ^ SyntaxError: invalid syntax A couple of things that will make it easier to help: > > 1. send mail as plain text. Rich text causes some readers problems > Thanks for the tip. I'll keep this in mind for future queries & replies. > 2. copy and paste the code and complete traceback. retyping things > make it more likely that what is in your code isn't exactly what you > typed > Apologies, but what is a traceback? Is this a debugging feature found in the shell? (I looked, but didn't see it) Thanks, Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Aug 5 02:13:46 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 05 Aug 2014 01:13:46 +0100 Subject: [Tutor] New to Python - print function - invalid syntax In-Reply-To: References: <6a5af6bdc2c8009c65cf628c52d9938b@sonic.net> Message-ID: On 05/08/14 00:21, Greg Markham wrote: > but I'm running into a syntax error As others have said you are getting the expected error when running Python v3 code under Python v2. How exactly are you running the program? It looks like somehow you are picking up Python v2 when you run the script even though your python -V is showing v3. BTW. Which OS are you using? It shouldn't affect the cause but it helps with the debugging! > For clarity, the full program reads as follows: > > > # Game Over - Version 2 > # Demonstrates the use of quotes in strings > # Python Programming for the Absolute Beginner, 3rd ed - Ch 2 > # Greg Markham - Aug 04, 2014 > > print("Program 'Game Over' 2.0") > > print("Same", "message", "as before") > > print("Just", > "a bit", > "bigger") Does all of the above print out correctly? Can you send us a cut n paste of the exact output of the program? > > print("Here", end=" ") > print("it is...") > > print( > """ > _____ ___ ___ ___ _____ > / ___| / | / |/ | | ___| > | | / /| | / /| /| | | |__ > | | _ / ___ | / / |__/ | | | __| > | |_| | / / | | / / | | | |___ > \_____/ /_/ |_| /_/ |_| |_____| > > _____ _ _ _____ _____ > / _ \ | | / / | ___| | _ \ > | | | | | | / / | |__ | |_| | > | | | | | | / / | __| | _ / > | |_| | | |/ / | |___ | | \ \ > \_____/ |___/ |_____| |_| \_\ > > """ > ) > > input("\n\nPress the enter key to exit.") finally you could try putting the following at the very top of your program: import sys print(sys.version) That will definitively prove that you are actually running v3 on the file... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Tue Aug 5 04:38:05 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 5 Aug 2014 12:38:05 +1000 Subject: [Tutor] New to Python - print function - invalid syntax In-Reply-To: References: Message-ID: <20140805023805.GR4525@ando> On Mon, Aug 04, 2014 at 04:44:46PM -0700, Greg Markham wrote: > Ok, when I try this from the Shell window, it works. When executing the > full program from command line, it does not. Python versions from both > shell and command line are 3.4.1 (confirmed via command: "python -V"). I'm a little confused, because I consider "the shell" and "command line" to more or less be synonymous. Perhaps if you explain step-by-step what you do. Here's my guess of what you mean by "command line": Click on Start Menu. Choose "Run" command. Enter "cmd.exe" Enter "python I:\Programming\Scripts\Learning\chapter02\game_over2.py" Am I close? > Full error msg output when run from cmd line reads: > > File "I:\Programming\Scripts\Learning\chapter02\game_over2.py", line 14 > print("Here", end=" ") > ^ > SyntaxError: invalid syntax That definitely looks like a Python 2 error, but it should work in any version of Python 3. This is a most perplexing error, I can only imagine that you have both Python 2 and 3 installed and somehow, for some unknown reason, you're sometimes getting one and sometimes getting the other. > > 2. copy and paste the code and complete traceback. retyping things > > make it more likely that what is in your code isn't exactly what you > > typed > > > > Apologies, but what is a traceback? Is this a debugging feature found in > the shell? (I looked, but didn't see it) A traceback is the text Python prints when an error occurs. It normally starts with the word "Traceback" and ends with the kind of error (SyntaxError, NameError, ImportError, etc.) and usually an error message. For example: Traceback (most recent call last): File "", line 1, in File "", line 2, in function TypeError: object of type 'int' has no len() or similar. The details will differ slightly (e.g. sometimes Python can print the offending lines of code) but the important thing is that there is a lot of useful information available in the traceback, if you show us the entire thing, from start to finish. SyntaxError is quite exceptional, in that it normally doesn't start with the word "Traceback", for technical reasons[1]. Technically, I suppose, it's not really a traceback, but we tend to call it such regardless. [1] SyntaxError normally occurs at compile-time, while Python is parsing the source code, and before execution starts, so there's no chain of calling functions and no traceback. But we normally don't care about the technical details. -- Steven From greg.markham at gmail.com Tue Aug 5 02:48:24 2014 From: greg.markham at gmail.com (Greg Markham) Date: Mon, 4 Aug 2014 17:48:24 -0700 Subject: [Tutor] New to Python - print function - invalid syntax In-Reply-To: References: <6a5af6bdc2c8009c65cf628c52d9938b@sonic.net> Message-ID: On Mon, Aug 4, 2014 at 5:13 PM, Alan Gauld wrote: > On 05/08/14 00:21, Greg Markham wrote: > > but I'm running into a syntax error >> > > As others have said you are getting the expected error when running Python > v3 code under Python v2. > > How exactly are you running the program? It looks like somehow you > are picking up Python v2 when you run the script even though your python > -V is showing v3. > > BTW. Which OS are you using? It shouldn't affect the cause but > it helps with the debugging! > > > For clarity, the full program reads as follows: >> >> >> # Game Over - Version 2 >> # Demonstrates the use of quotes in strings >> # Python Programming for the Absolute Beginner, 3rd ed - Ch 2 >> # Greg Markham - Aug 04, 2014 >> >> print("Program 'Game Over' 2.0") >> >> print("Same", "message", "as before") >> >> print("Just", >> "a bit", >> "bigger") >> > > Does all of the above print out correctly? Can you send > us a cut n paste of the exact output of the program? > > > >> print("Here", end=" ") >> print("it is...") >> >> print( >> """ >> _____ ___ ___ ___ _____ >> / ___| / | / |/ | | ___| >> | | / /| | / /| /| | | |__ >> | | _ / ___ | / / |__/ | | | __| >> | |_| | / / | | / / | | | |___ >> \_____/ /_/ |_| /_/ |_| |_____| >> >> _____ _ _ _____ _____ >> / _ \ | | / / | ___| | _ \ >> | | | | | | / / | |__ | |_| | >> | | | | | | / / | __| | _ / >> | |_| | | |/ / | |___ | | \ \ >> \_____/ |___/ |_____| |_| \_\ >> >> """ >> ) >> >> input("\n\nPress the enter key to exit.") >> > > finally you could try putting the following at the very top of your > program: > > import sys > print(sys.version) > > That will definitively prove that you are actually > running v3 on the file... Aaaah, brilliant! You were right! I:\Programming\Scripts\Learning\chapter02>game_over2.py 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] I installed ver 2.7.8 initially then some time later installed ver 3.4.1 upon starting the above mentioned book which uses that version. I thought I had handled the problem by renaming the executables to python27.exe and pythonw27.exe as well as modifying the path statement to point to where the latest version was installed, but that appears not to have been enough. To avoid further confusion, I'm uninstalling both versions and reinstalling the latest now so as to reset the file associations which have become a little out of sorts from all my tampering. Thanks for helping me get to the heart of it! --Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg.markham at gmail.com Tue Aug 5 05:13:51 2014 From: greg.markham at gmail.com (Greg Markham) Date: Mon, 4 Aug 2014 20:13:51 -0700 Subject: [Tutor] New to Python - print function - invalid syntax In-Reply-To: <20140805023805.GR4525@ando> References: <20140805023805.GR4525@ando> Message-ID: On Mon, Aug 4, 2014 at 7:38 PM, Steven D'Aprano wrote: > On Mon, Aug 04, 2014 at 04:44:46PM -0700, Greg Markham wrote: > > > Ok, when I try this from the Shell window, it works. When executing the > > full program from command line, it does not. Python versions from both > > shell and command line are 3.4.1 (confirmed via command: "python -V"). > > I'm a little confused, because I consider "the shell" and "command line" > to more or less be synonymous. Perhaps if you explain step-by-step what > you do. Here's my guess of what you mean by "command line": > > Click on Start Menu. > Choose "Run" command. > Enter "cmd.exe" > Enter "python I:\Programming\Scripts\Learning\chapter02\game_over2.py" > > Am I close? > For cmd line, yes that's basically it. When I say "shell", I'm referring to the Python IDLE GUI. > > > Full error msg output when run from cmd line reads: > > > > File "I:\Programming\Scripts\Learning\chapter02\game_over2.py", line 14 > > print("Here", end=" ") > > ^ > > SyntaxError: invalid syntax > > That definitely looks like a Python 2 error, but it should work in any > version of Python 3. This is a most perplexing error, I can only imagine > that you have both Python 2 and 3 installed and somehow, for some > unknown reason, you're sometimes getting one and sometimes getting the > other. > That's correct, I did have two versions installed. I first installed ver 2.7, then later installed ver 3.4 when I began going through the lessons in the aforementioned book. Although I'd taken steps to ensure the latest version was used, I was apparently not thorough enough as when I inserted some code in the program that revealed the version being used, it stated 2.7.4. So, I ended up uninstalling both versions, then reinstalling ver 3.4 which reset the file associations and resolved the issue. Hopefully any further issues I encounter aren't due to misconfigurations and the like. Thanks for your help, Steven. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kabaumgert94 at gmail.com Tue Aug 5 06:02:05 2014 From: kabaumgert94 at gmail.com (Kelvin Baumgart) Date: Mon, 4 Aug 2014 23:02:05 -0500 Subject: [Tutor] Installing Python 2.5.4 on Windows 8 Questions Message-ID: My current OS is Windows 8 unfortunately. I'm definitely desiring to change this however for the time being I require an external DVD burner to obtain backups/OS before I can really progress. For the time being I'm recently someone who has an unparalleled drive towards becoming a programmer. I'd imagine seeing someone attempting to install an older version of Python may be out of the norm. As my ambition to pursue skills I've began an online course on "Introduction to Computer Science and Programming" which is being taught through MIT. Their curriculum is centered on 2.5.4 however any 2.5 or 2.6 versions are allegedly acceptable accordingly to the syllabus. I'm literally what you could consider an absolute novice who's just starting dabbling with this sort of thing, so please look past any naivety that probably engulfs this email. Essentially if you could help get started with installation by giving me professional input towards what OS or anything else relevant to my cause I will be greatly appreciative for your time and effort. Without saying I've browsed through the forms and FAQ yet I've haven't quite seen any particular thread that has these exact variables I face. I hope to hear back from you soon, and look forward to receiving guidance from those with expertise on such a trivial problem. Sincerely Kelvin B -------------- next part -------------- An HTML attachment was scrubbed... URL: From maximesteisel at gmail.com Tue Aug 5 09:48:14 2014 From: maximesteisel at gmail.com (Maxime Steisel) Date: Tue, 5 Aug 2014 09:48:14 +0200 Subject: [Tutor] New to Python - print function - invalid syntax In-Reply-To: References: Message-ID: Le 2014-08-05 02:07, "Greg Markham" a ?crit: > Ok, when I try this from the Shell window, it works. When executing the full program from command line, it does not. Python versions from both shell and command line are 3.4.1 (confirmed via command: "python -V"). > > Full error msg output when run from cmd line reads: > > File "I:\Programming\Scripts\Learning\chapter02\game_over2.py", line 14 > > print("Here", end=" ") > ^ > SyntaxError: invalid syntax > That definitely show that python2 is running. I think this is because on windows, *.py files are associated with py.exe that choose the python version depending on the first line of your file. Putting #!python3 on the first line of game_over2.py should solve it. See PEP 397 [1] for more details about this feature. [1] http://legacy.python.org/dev/peps/pep-0397/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Tue Aug 5 11:17:23 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 05 Aug 2014 19:17:23 +1000 Subject: [Tutor] New to Python - print function - invalid syntax References: <20140805023805.GR4525@ando> Message-ID: <85lhr3b8ik.fsf@benfinney.id.au> Greg Markham writes: > For cmd line, yes that's basically it. When I say "shell", I'm > referring to the Python IDLE GUI. For future reference: the operating system shell presents a command line. The Python shell presents a command line. So ?shell? and ?command line? don't distinguish between those. You might better use the terms ?operating system shell? (?OS shell?) and ?Python shell?. Hope that helps. -- \ ?Never express yourself more clearly than you are able to | `\ think.? ?Niels Bohr | _o__) | Ben Finney From alan.gauld at btinternet.com Tue Aug 5 11:51:40 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 05 Aug 2014 10:51:40 +0100 Subject: [Tutor] Installing Python 2.5.4 on Windows 8 Questions In-Reply-To: References: Message-ID: On 05/08/14 05:02, Kelvin Baumgart wrote: > My current OS is Windows 8 unfortunately. The Windows 8 GUI sucks, but other than that its not a bad OS IMHO... And Classic Shell fixes the UI. > and Programming" which is being taught through MIT. Their curriculum is > centered on 2.5.4 however any 2.5 or 2.6 versions are allegedly > acceptable accordingly to the syllabus. Install v2.6 its a lot closer to the latest version that 2.5. > email. Essentially if you could help get started with installation by > giving me professional input towards what OS or anything else relevant > to my cause I will be greatly appreciative for your time and effort. Just download the Windows installer for Python2.6. https://www.python.org/download/releases/2.6.6/ Make sure you get the right version for your OS (64vbit v 32 bit) If in doubt use the 32bit version as it works on both. Also note the caveat on the web page re security fixes. But this is the last version of 2.6 with a Windows installer so is your best bet. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Tue Aug 5 14:17:27 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 5 Aug 2014 22:17:27 +1000 Subject: [Tutor] Installing Python 2.5.4 on Windows 8 Questions In-Reply-To: References: Message-ID: <20140805121727.GS4525@ando> Hi Kelvin, My responses interleaved between your comments below. On Mon, Aug 04, 2014 at 11:02:05PM -0500, Kelvin Baumgart wrote: > My current OS is Windows 8 unfortunately. I'm definitely desiring to change > this however for the time being I require an external DVD burner to obtain > backups/OS before I can really progress. For the time being I'm recently > someone who has an unparalleled drive towards becoming a programmer. I'd > imagine seeing someone attempting to install an older version of Python may > be out of the norm. Installing an older version is a little unusual, but not unheard of. I myself have versions of Python going back to 0.9 installed. > As my ambition to pursue skills I've began an online > course on "Introduction to Computer Science and Programming" which is being > taught through MIT. Their curriculum is centered on 2.5.4 however any 2.5 > or 2.6 versions are allegedly acceptable accordingly to the syllabus. If you have a choice between 2.5 and 2.6, choose 2.6. > I'm > literally what you could consider an absolute novice who's just starting > dabbling with this sort of thing, so please look past any naivety that > probably engulfs this email. You and half the people on this list :-) > Essentially if you could help get started with > installation by giving me professional input towards what OS or anything > else relevant to my cause I will be greatly appreciative for your time and > effort. If you're familiar with Windows, stick to Windows. But, I think it's probably fair to say that Linux is a better OS for professional Python development than Windows is. That isn't to say that you cannot write Python code on Windows, just that it's a bit harder. With Linux, you have a much wider range of free, professional-quality tools that will make your life as a developer easier. But, as a beginner, don't worry about that. Stick to what you know. You can always experiment later. Do the MIT course notes assume you're using a specific editor? If so, you might like to use that one. Otherwise, you'll want a *good* editor. You can write Python code with Notepad, if you're desperate enough, it's just text, but you'll be more productive with a programmers editors. I'm not a Windows user, so I can't make any personal recommendations, but you can start here: https://wiki.python.org/moin/PythonEditors I've used geany (on Linux, not Windows), and can recommend it. I've also used Spyder (again, on Linux) but the version I used just felt sluggish and too "busy", but many people disagree. The beauty of starting with free, open source software is that it costs you nothing but a little bit of time to try it out. If you have a scientific background, and are used to software like Mathematica that has "notebooks", you should consider using IPython. As far as installing Python goes, you can get a bare-bones Windows installer from here: https://www.python.org/download/releases/2.6.6/ If you feel brave enough to compile your own from source, and have a Windows C compiler, try this: https://www.python.org/download/releases/2.6.8/ but if you have no idea what a C compiler is or how to use it, stick to the first link. Or, you can use a third-party package: http://komodoide.com/komodo-edit/ although I don't know what version(s) of Python it supports. I hear good things about Komodo. > Without saying I've browsed through the forms and FAQ yet I've > haven't quite seen any particular thread that has these exact variables I > face. I hope to hear back from you soon, and look forward to receiving > guidance from those with expertise on such a trivial problem. No problem at all! Feel free to ask any questions you may have. -- Steven From marc.tompkins at gmail.com Tue Aug 5 16:56:21 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 5 Aug 2014 07:56:21 -0700 Subject: [Tutor] New to Python - print function - invalid syntax In-Reply-To: References: Message-ID: On Tue, Aug 5, 2014 at 12:48 AM, Maxime Steisel wrote: > I think this is because on windows, *.py files are associated with py.exe > that choose the python version depending on the first line of your file. No. *ix operating systems (Unix, Linux, OS X, etc.) inspect the first line of a file to determine how to handle it; Windows does NOT. Windows simply looks at the filename extension (.py, .pyw, etc.) and consults its internal registry of file type associations. The way that you, as a user, can edit those associations has changed over the years; in Windows 7 and 8, it's Control Panel\All Control Panel Items\Default Programs\Set Associations. On the other hand, when you start up CMD.EXE and type "python" at the prompt, Windows uses a procedure that goes back to DOS 2 or so: the PATH environment variable. This is similar to, but a little different from, the way that *ixes work; Windows first compares what you've typed with the list of commands built-in to CMD, then with all of the executable files in the current working directory, THEN walks through the directories listed in PATH. The first matching command or executable it finds is the one that runs. > Putting #!python3 on the first line of game_over2.py should solve it. NO. #! has no effect in Windows, because the choice of Python interpreter has already been made by the time anybody gets round to reading the first line of the file. From breamoreboy at yahoo.co.uk Tue Aug 5 17:20:39 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 05 Aug 2014 16:20:39 +0100 Subject: [Tutor] New to Python - print function - invalid syntax In-Reply-To: References: Message-ID: On 05/08/2014 15:56, Marc Tompkins wrote: > On Tue, Aug 5, 2014 at 12:48 AM, Maxime Steisel wrote: >> I think this is because on windows, *.py files are associated with py.exe >> that choose the python version depending on the first line of your file. > > No. *ix operating systems (Unix, Linux, OS X, etc.) inspect the first > line of a file to determine how to handle it; Windows does NOT. > Windows simply looks at the filename extension (.py, .pyw, etc.) and > consults its internal registry of file type associations. The way > that you, as a user, can edit those associations has changed over the > years; in Windows 7 and 8, it's Control Panel\All Control Panel > Items\Default Programs\Set Associations. > > On the other hand, when you start up CMD.EXE and type "python" at the > prompt, Windows uses a procedure that goes back to DOS 2 or so: the > PATH environment variable. This is similar to, but a little different > from, the way that *ixes work; Windows first compares what you've > typed with the list of commands built-in to CMD, then with all of the > executable files in the current working directory, THEN > walks through the directories listed in PATH. The first matching > command or executable it finds is the one that runs. > >> Putting #!python3 on the first line of game_over2.py should solve it. > NO. #! has no effect in Windows, because the choice of Python > interpreter has already been made by the time anybody gets round to > reading the first line of the file. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > Completely wrong, the reference that Maxime gave to PEP 397 that you've snipped was absolutely correct. Windows might not handle shebang lines, Python on Windows does. From zachary.ware+pytut at gmail.com Tue Aug 5 17:23:32 2014 From: zachary.ware+pytut at gmail.com (Zachary Ware) Date: Tue, 5 Aug 2014 10:23:32 -0500 Subject: [Tutor] New to Python - print function - invalid syntax In-Reply-To: References: Message-ID: On Tue, Aug 5, 2014 at 9:56 AM, Marc Tompkins wrote: > On Tue, Aug 5, 2014 at 12:48 AM, Maxime Steisel wrote: >> I think this is because on windows, *.py files are associated with py.exe >> that choose the python version depending on the first line of your file. > > No. *ix operating systems (Unix, Linux, OS X, etc.) inspect the first > line of a file to determine how to handle it; Windows does NOT. Have a look at PEP 397[1]. You are correct, *Windows* does not look at the shebang line. However, Maxime is also correct in that Python 3.3+ installs the Python Launcher for Windows (py.exe) and associates the .py extension with it, and *py.exe* does shebang line handling, spawning the interpreter requested by the shebang line as a subprocess. > Windows simply looks at the filename extension (.py, .pyw, etc.) and > consults its internal registry of file type associations. The way > that you, as a user, can edit those associations has changed over the > years; in Windows 7 and 8, it's Control Panel\All Control Panel > Items\Default Programs\Set Associations. > > On the other hand, when you start up CMD.EXE and type "python" at the > prompt, Windows uses a procedure that goes back to DOS 2 or so: the > PATH environment variable. This is similar to, but a little different > from, the way that *ixes work; Windows first compares what you've > typed with the list of commands built-in to CMD, then with all of the > executable files in the current working directory, THEN > walks through the directories listed in PATH. The first matching > command or executable it finds is the one that runs. > >> Putting #!python3 on the first line of game_over2.py should solve it. > NO. #! has no effect in Windows, because the choice of Python > interpreter has already been made by the time anybody gets round to > reading the first line of the file. "#!python3.4" or "#!C:\Python34\python.exe" or "#!/usr/bin/env python3" should all work if the '.py' extension is properly associated with the py.exe launcher, which it should be if the most recently installed Python was 3.3 or 3.4, installed with default options. -- Zach [1] http://legacy.python.org/dev/peps/pep-0397/ From marc.tompkins at gmail.com Tue Aug 5 18:11:27 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 5 Aug 2014 09:11:27 -0700 Subject: [Tutor] New to Python - print function - invalid syntax In-Reply-To: References: Message-ID: On Tue, Aug 5, 2014 at 8:23 AM, Zachary Ware wrote: > > which it should be if the most recently > installed Python was 3.3 or 3.4, installed with default options. > And there we have my problem with this glorious new "feature". YOU CAN'T RELY ON IT, because it depends on the most recent version having been installed most recently. Much better to depend on the underlying behavior of the operating system. From davea at davea.name Tue Aug 5 18:39:39 2014 From: davea at davea.name (Dave Angel) Date: Tue, 5 Aug 2014 12:39:39 -0400 (EDT) Subject: [Tutor] New to Python - print function - invalid syntax References: Message-ID: Marc Tompkins Wrote in message: > On Tue, Aug 5, 2014 at 8:23 AM, Zachary Ware > wrote: >> >> which it should be if the most recently >> installed Python was 3.3 or 3.4, installed with default options. >> > > And there we have my problem with this glorious new "feature". YOU > CAN'T RELY ON IT, because it depends on the most recent version having > been installed most recently. Much better to depend on the underlying > behavior of the operating system. > Read some more. Once you've got py.exe installed, whether from python 3.3+ or manually, then you just point the path and/or file associations at it. That's done by default when python 3.3+ is installed, and only messed up when you subsequently install an older version using the wrong options. -- DaveA From mmnissanzroadster9 at gmail.com Tue Aug 5 19:35:57 2014 From: mmnissanzroadster9 at gmail.com (Marcus Mravik) Date: Tue, 5 Aug 2014 12:35:57 -0500 Subject: [Tutor] Specifying the selected object number in Blender Message-ID: I am trying to specify a number based on what the selected object number in the scene is. import bpy for obj in bpy.context.selected_objects: bpy.context.scene.objects.active = obj bpy.ops.graph.sound_bake(filepath="C:\\Users\\Marcus\\Music\\Don't Just Stand There (Instrumental).mp3", low=50*(((WHERE OBJECT NUMBER GOES))), high=100+50*(((WHERE OBJECT NUMBER GOES))) (((WHERE THE OBJECT NUMBER GOES))) is not part of the script, it's just where my question comes from. My overall goal is to create a Music Visualizer with Blender and I am trying to automate the selection of the object, applying the variable that goes up by 50 each time, starting with 0 for the low freq and 50 for the high freq. And ending with 7950 low and 8000 high. -- mmnissanzroadster9 at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Aug 6 01:28:33 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 06 Aug 2014 00:28:33 +0100 Subject: [Tutor] Specifying the selected object number in Blender In-Reply-To: References: Message-ID: On 05/08/14 18:35, Marcus Mravik wrote: > My overall goal is to create a Music Visualizer with Blender and I am > trying to automate the selection of the object, applying the variable > that goes up by 50 each time, starting with 0 for the low freq and 50 > for the high freq. And ending with 7950 low and 8000 high. This list is for people learning the Python language and standard library so Blender is a bit off topic. You might be lucky and find someone here who knows but you would likely be better off asking on a Blender forum. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Wed Aug 6 02:15:19 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 06 Aug 2014 02:15:19 +0200 Subject: [Tutor] Specifying the selected object number in Blender References: Message-ID: Marcus Mravik wrote: > I am trying to specify a number based on what the selected object number > in the scene is. > > import bpy > > for obj in bpy.context.selected_objects: > > bpy.context.scene.objects.active = obj > > bpy.ops.graph.sound_bake(filepath="C:\\Users\\Marcus\\Music\\Don't > Just > Stand There (Instrumental).mp3", low=50*(((WHERE OBJECT NUMBER GOES))), > high=100+50*(((WHERE OBJECT NUMBER GOES))) > > (((WHERE THE OBJECT NUMBER GOES))) is not part of the script, it's just > where my question comes from. > > My overall goal is to create a Music Visualizer with Blender and I am > trying to automate the selection of the object, applying the variable that > goes up by 50 each time, starting with 0 for the low freq and 50 for the > high freq. And ending with 7950 low and 8000 high. If "object number" is not a blender-specific term and just 0 for the first, 1 for the second, and 2 for the third object in selected_objects: for index, obj, in enumerate(bpy.context.selected_objects): bpy.context.scene.objects.active = obj bpy.ops.graph.sound_bake( filepath="C:\\Users\\Marcus\\Music\\Don't " "Just Stand There (Instrumental).mp3", low = index * 50, high = (index + 1) * 50) From steve at pearwood.info Wed Aug 6 03:00:49 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 6 Aug 2014 11:00:49 +1000 Subject: [Tutor] Specifying the selected object number in Blender In-Reply-To: References: Message-ID: <20140806010048.GT4525@ando> On Tue, Aug 05, 2014 at 12:35:57PM -0500, Marcus Mravik wrote: > I am trying to specify a number based on what the selected object number in > the scene is. Well, I have no idea about Blender, but if "selected object number" is just an int, starting from 0 (or perhaps 1) and incrementing by 1 each time, you can do that with a simple for-loop: import bpy filename = "C:\\Users\\Marcus\\Music\\Don't Just Stand There (Instrumental).mp3" for selected_object_number in range(0, 160): low = 50*selected_object_number for obj in bpy.context.selected_objects: bpy.context.scene.objects.active = obj bpy.ops.graph.sound_bake(filepath=filename, low=low, high=low+50) -- Steven From sivarm30 at gmail.com Wed Aug 6 07:21:27 2014 From: sivarm30 at gmail.com (Sivaraman.R) Date: Wed, 6 Aug 2014 13:21:27 +0800 Subject: [Tutor] Box plot Message-ID: I want to add a minimum value and maximum value to the box plot. I am findind it difficult to do that. Could you please please help me in that. my code: mport matplotlib.pyplot as plt import pandas as pd check1 = pd.read_csv(r'C:\Users\RamachSi\Desktop\Test_now11.csv') check1.boxplot(column=['VTSPG6RB'], by=['Lot']) -- Sincerely, Sivaraman Ramachandran -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Aug 6 10:19:00 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 06 Aug 2014 09:19:00 +0100 Subject: [Tutor] Box plot In-Reply-To: References: Message-ID: On 06/08/14 06:21, Sivaraman.R wrote: > I want to add a minimum value and maximum value to the box plot. I am > findind it difficult to do that. Could you please please help me in that. > my code: > mport matplotlib.pyplot as plt > import pandas as pd > check1 = pd.read_csv(r'C:\Users\RamachSi\Desktop\Test_now11.csv') > check1.boxplot(column=['VTSPG6RB'], by=['Lot']) This list is for folks learning the Python language and standard library. For SciPy queries (and matplotlib and pandas are part of the WSciPy family) you would be more likely to get responses on the SciPy lists. There are some matplotlib/pandas users here though, so you may get lucky. It would help if you described the errors you are getting and provided a full error message. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Aug 6 11:00:43 2014 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 6 Aug 2014 10:00:43 +0100 Subject: [Tutor] Box plot In-Reply-To: References: Message-ID: <1407315643.40139.YahooMailNeo@web186003.mail.ir2.yahoo.com> Forwarding to list. Please use ReplyAll when responding to the list. ? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos >________________________________ > From: Sivaraman.R >To: Alan Gauld >Sent: Wednesday, 6 August 2014, 9:52 >Subject: Re: [Tutor] Box plot > > > >Thanks for replying, Am not getting a error but I want to add?a line?in the same plot. The boundary is like a range specified in the requirements. The range is max=1e29 and min -1e29. The?attached figure can get you a picture of what am trying to say. >? > > > >On Wed, Aug 6, 2014 at 4:19 PM, Alan Gauld wrote: > >On 06/08/14 06:21, Sivaraman.R wrote: >> >>I want to add a minimum value and maximum value to the box plot. I am >>>findind it difficult to do that. Could you please please help me in that. >>>my code: >>>mport matplotlib.pyplot as plt >>>import pandas as pd >>>check1 = pd.read_csv(r'C:\Users\RamachSi\Desktop\Test_now11.csv') >>>check1.boxplot(column=['VTSPG6RB'], by=['Lot']) >>> >> This list is for folks learning the Python language and standard library. For SciPy queries (and matplotlib and pandas are part >>of the WSciPy family) you would be more likely to get responses >>on the SciPy lists. >> >>There are some matplotlib/pandas users here though, so you may >>get lucky. >> >>It would help if you described the errors you are getting >>and provided a full error message. >> >>-- >>Alan G >>Author of the Learn to Program web site >>http://www.alan-g.me.uk/ >>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 >> > > >-- > >Sincerely, >Sivaraman Ramachandran > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From williamvargas1984 at gmail.com Wed Aug 6 18:29:18 2014 From: williamvargas1984 at gmail.com (William Vargas) Date: Wed, 6 Aug 2014 10:29:18 -0600 Subject: [Tutor] New dealing with Pythong and programming Message-ID: Hello My name is Will, I live in Costa Rica and I really want to learn how to program. In the past, a friend said to me that was really cool but I did not feel the call to learn, but now I was talking to a new friend and he said to me code was really great then I ask what was the best language and he said, well find the best language, find Python which I did. But now here comes the question, I do not know anything about programming, I heard about Integer, float and a bunch of this thing but I do not have a clue what they are. Can you please guide me to find what they are (I know of course there are more). I have installed Python version 2.7.8, my computer is running windows 7 64 bits and I was recommended to install a work editor which I did (DreamPie Python 2.7), this is just in case you think I need to change something. Are all of this things a constant for all the programming languages or are there specific for Python? I would like to start by understanding this concepts otherwise I will be confused I guess. Thank you for your time, this system really rocks, I do appreciate all what you do for us the beginners. Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Wed Aug 6 19:08:21 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 6 Aug 2014 13:08:21 -0400 Subject: [Tutor] New dealing with Pythong and programming In-Reply-To: References: Message-ID: On Wed, Aug 6, 2014 at 12:29 PM, William Vargas wrote: > Hello > > My name is Will, I live in Costa Rica and I really want to learn how to > program. In the past, a friend said to me that was really cool but I did not > feel the call to learn, but now I was talking to a new friend and he said to > me code was really great then I ask what was the best language and he said, > well find the best language, find Python which I did. > > But now here comes the question, I do not know anything about programming, I > heard about Integer, float and a bunch of this thing but I do not have a > clue what they are. Can you please guide me to find what they are (I know of > course there are more). I have installed Python version 2.7.8, my computer > is running windows 7 64 bits and I was recommended to install a work editor > which I did (DreamPie Python 2.7), this is just in case you think I need to > change something. > > Are all of this things a constant for all the programming languages or are > there specific for Python? > > I would like to start by understanding this concepts otherwise I will be > confused I guess. > > Thank you for your time, this system really rocks, I do appreciate all what > you do for us the beginners. > > Thank you You can start by going to python.org. There is a section for beginners. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From dyoo at hashcollision.org Wed Aug 6 20:42:08 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 6 Aug 2014 11:42:08 -0700 Subject: [Tutor] New dealing with Pythong and programming In-Reply-To: References: Message-ID: Hi William, You can take a look at the beginner's guides to Python: https://wiki.python.org/moin/BeginnersGuide If your native language is Spanish, you may want to look at: https://wiki.python.org/moin/SpanishLanguage and see if there are any tutorials there that are easier for you to approach. If you have any questions, please feel free to ask! On Wed, Aug 6, 2014 at 9:29 AM, William Vargas wrote: > Hello > > My name is Will, I live in Costa Rica and I really want to learn how to > program. In the past, a friend said to me that was really cool but I did not > feel the call to learn, but now I was talking to a new friend and he said to > me code was really great then I ask what was the best language and he said, > well find the best language, find Python which I did. > > But now here comes the question, I do not know anything about programming, I > heard about Integer, float and a bunch of this thing but I do not have a > clue what they are. Can you please guide me to find what they are (I know of > course there are more). I have installed Python version 2.7.8, my computer > is running windows 7 64 bits and I was recommended to install a work editor > which I did (DreamPie Python 2.7), this is just in case you think I need to > change something. > > Are all of this things a constant for all the programming languages or are > there specific for Python? > > I would like to start by understanding this concepts otherwise I will be > confused I guess. > > Thank you for your time, this system really rocks, I do appreciate all what > you do for us the beginners. > > Thank you > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From ch.de2.2309 at gmail.com Wed Aug 6 21:59:16 2014 From: ch.de2.2309 at gmail.com (Whees Northbee) Date: Thu, 7 Aug 2014 02:59:16 +0700 Subject: [Tutor] How to save each pixel from image to jagged array in exact coordinate Message-ID: Hello, I try do background subtraction using python, and I have problem to save each pixel to jagged array... *My jagged array is:* m_samples=[] height, width, depth=cap.shape c_black=np.zeros( (height,width), dtype=np.uint8) for i in range(0,NUM_SAMPLES,1): m_samples.append(c_black) *And my code to access each pixel from frame is:* NUM_SAMPLES =18 c_xoff= [-1, 0, 1, -1, 1, -1, 0, 1, 0] c_yoff= [-1, 0, 1, -1, 1, -1, 0, 1, 0] for i in range(0,width,1): for j in range(0,height,1): for k in range(0,NUM_SAMPLES,1): random=numpy.random.randint(0,9) row=i+c_yoff[random] if(row<0): row=0 if(row>=width): row=width-1 col=j+c_xoff[random] if(col<0): col=0 if(col>=height): col=height-1 _____________=getPixel(frame,row,col) what I want to fill in ____ is m_samples[k] in coordinate (i,j), but I don't know how to write it in python? Thanks for your help... -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Thu Aug 7 01:44:59 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 6 Aug 2014 16:44:59 -0700 Subject: [Tutor] Fwd: New dealing with Pythong and programming In-Reply-To: References: Message-ID: Hi William, I'm forwarding this to the tutor mailing list. Currently I'm busy in my day job, so I truly can't look at this now. (I'm currently under a deadline.) But hopefully someone else on the list can take a look. Please use Reply-To-All in your email client when you're asking and answering Tutor-related mail, so that all the helpers there can help. I hope the learning is going well for you! ---------- Forwarded message ---------- From: William Vargas Date: Wed, Aug 6, 2014 at 4:09 PM Subject: Re: [Tutor] New dealing with Pythong and programming To: Danny Yoo Hey Danny your links were really usefull, actually they are guiding me to learn step by step by mean of exercises which I think is the best. But now I have face an example were I got stuck. This may be so fool so you will probably be glad if you could kick me hehehe but I can't jump to the next line. look this is what I want to write: Example: print "Jack and Jill went up a hill" print "to fetch a pail of water;" print "Jack fell down, and broke his crown," print "and Jill came tumbling after." But as soon as I finish the line and I hit enter it executes it and I can write the other part. I found a link in Spanish however most of the best information and practices are in English then I will try to learn on that language, but of course, I would use it if needed. Thank you Danny On Wed, Aug 6, 2014 at 12:42 PM, Danny Yoo wrote: > > Hi William, > > You can take a look at the beginner's guides to Python: > > https://wiki.python.org/moin/BeginnersGuide > > > If your native language is Spanish, you may want to look at: > > https://wiki.python.org/moin/SpanishLanguage > > and see if there are any tutorials there that are easier for you to approach. > > > > If you have any questions, please feel free to ask! > > On Wed, Aug 6, 2014 at 9:29 AM, William Vargas > wrote: > > Hello > > > > My name is Will, I live in Costa Rica and I really want to learn how to > > program. In the past, a friend said to me that was really cool but I did not > > feel the call to learn, but now I was talking to a new friend and he said to > > me code was really great then I ask what was the best language and he said, > > well find the best language, find Python which I did. > > > > But now here comes the question, I do not know anything about programming, I > > heard about Integer, float and a bunch of this thing but I do not have a > > clue what they are. Can you please guide me to find what they are (I know of > > course there are more). I have installed Python version 2.7.8, my computer > > is running windows 7 64 bits and I was recommended to install a work editor > > which I did (DreamPie Python 2.7), this is just in case you think I need to > > change something. > > > > Are all of this things a constant for all the programming languages or are > > there specific for Python? > > > > I would like to start by understanding this concepts otherwise I will be > > confused I guess. > > > > Thank you for your time, this system really rocks, I do appreciate all what > > you do for us the beginners. > > > > Thank you > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > From dyoo at hashcollision.org Thu Aug 7 01:46:56 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 6 Aug 2014 16:46:56 -0700 Subject: [Tutor] New dealing with Pythong and programming In-Reply-To: References: Message-ID: See if: https://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/IDLE_spanish.html is helpful. From ch.de2.2309 at gmail.com Thu Aug 7 13:49:02 2014 From: ch.de2.2309 at gmail.com (Whees Northbee) Date: Thu, 7 Aug 2014 18:49:02 +0700 Subject: [Tutor] Error in get pixel value in coordinate (x, y) using getPixel(x, y) Message-ID: Please help me... I'm using python 2.7.6, numpy 1.8.1, opencv 2.4.9.. I want to get pixel value in one number like 255 not each value like these R(190), G(23), B(45) from coordinate (x,y)... I try these code m_samples[k][i][j]=getPixel(img,row,col) But get error: NameError: name 'getPixel' is not defined If I change the format become: m_samples[k][i][j]=img.getPixel(row,col) Still error: AttributeError: 'numpy.ndarray' object has no attribute 'getpixel' Please help me.. Thanks, Northbee -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Aug 7 20:38:00 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 07 Aug 2014 19:38:00 +0100 Subject: [Tutor] Error in get pixel value in coordinate (x, y) using getPixel(x, y) In-Reply-To: References: Message-ID: On 07/08/14 12:49, Whees Northbee wrote: > Please help me... I'm using python 2.7.6, numpy 1.8.1, opencv 2.4.9.. > I want to get pixel value in one number like 255 not each value like > these R(190), G(23), B(45) from coordinate (x,y)... What do you expect that number to look like? The pixels are represented by the 3 colours RGB. Are you wanting to just join the 3 bytes together to create an arbitrary number? Or do you think this number will mean something? > I try these code > m_samples[k][i][j]=getPixel(img,row,col) > > But get error: > NameError: name 'getPixel' is not defined So the getPixel function doesn't exist in your namespace. Where do you think it comes from? > If I change the format become: > m_samples[k][i][j]=img.getPixel(row,col) > > Still error: > AttributeError: 'numpy.ndarray' object has no attribute 'getpixel' And its not a part of a numpy ndarray - what made you think it was? Arte you just guessing? Or did you saee some code that uses getPixel() somewhere? > Please help me.. The tutor list is for those learning Python and its standard library. Numpy is not part of that, so your question is slightly off list. but your error looks so elementary that we may be able to help if you give us more information. Also, please *always* send full error messages, not just the last line. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From joel.goldstick at gmail.com Thu Aug 7 20:39:20 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 7 Aug 2014 14:39:20 -0400 Subject: [Tutor] Error in get pixel value in coordinate (x, y) using getPixel(x, y) In-Reply-To: References: Message-ID: On Thu, Aug 7, 2014 at 7:49 AM, Whees Northbee wrote: > Please help me... I'm using python 2.7.6, numpy 1.8.1, opencv 2.4.9.. > I want to get pixel value in one number like 255 not each value like these > R(190), G(23), B(45) from coordinate (x,y)... > I try these code > m_samples[k][i][j]=getPixel(img,row,col) > > But get error: > NameError: name 'getPixel' is not defined > > If I change the format become: > m_samples[k][i][j]=img.getPixel(row,col) > > Still error: > AttributeError: 'numpy.ndarray' object has no attribute 'getpixel' > > Please help me.. > > Thanks, > > Northbee > >What module is getPixel from? Do you have that module imported? Its best if you show complete traceback, and other relevant code I'm guessing that img is what you imported from numpy.ndarray. But it looks to me like getPixel comes from pil > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From ch2009 at arcor.de Fri Aug 8 06:57:11 2014 From: ch2009 at arcor.de (Chris) Date: Fri, 08 Aug 2014 06:57:11 +0200 Subject: [Tutor] Python twitter "errors":[{"message":"Could not authenticate you", "code":32 Message-ID: <53E458A7.4060909@arcor.de> Dear All, I'm trying to execute the examples from https://github.com/sixohsix/twitter with the current library version installed by pip install (1.14.3). #!/usr/bin/env python # -- coding: utf-8 -- from twitter import * con_secret='DACs' # "Consumer Secret" con_secret_key='jold' # "Consumer Key" token='2554' # "Access token" token_key='HHSD' # "Access Token Secret" t = Twitter( auth=OAuth(token, token_key, con_secret, con_secret_key)) t.statuses.user_timeline(screen_name="RenateBergmann") The reply is: twitter.api.TwitterHTTPError: Twitter sent status 401 for URL: 1.1/statuses/user_timeline.json using parameters: (oauth_consumer_key=DA...&oauth_nonce=...&oauth_signature_method=HMAC-SHA1&oauth_timestamp=....&oauth_token=....&oauth_version=1.0&screen_name=RenateBergmann&oauth_signature=......) details: {"errors":[{"message":"Could not authenticate you","code":32}]} What's the issue? Have I used the right tokens and keys? The labeling in the script is a bit different from the Twitter api page. Is Python 2.7 the proper version? The documentation said 2.6, but someone told me I had to use 2.7. Is the authentication method correct? It should be, because this is an example from the Github readme. I'm a beginner, so maybe it's only a slight mistake? Thank you in advance. -- Christian From alan.gauld at btinternet.com Fri Aug 8 09:28:52 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 08 Aug 2014 08:28:52 +0100 Subject: [Tutor] Python twitter "errors":[{"message":"Could not authenticate you", "code":32 In-Reply-To: <53E458A7.4060909@arcor.de> References: <53E458A7.4060909@arcor.de> Message-ID: On 08/08/14 05:57, Chris wrote: > I'm trying to execute the examples from > https://github.com/sixohsix/twitter with the current library version > installed by pip install (1.14.3). Since this list is for the core language and standard library this is a bit off list. You might get more response direct from the author or a twitter specific mailing list(if one exists). Failing that maybe the main Python list. However... > con_secret='DACs' # "Consumer Secret" > con_secret_key='jold' # "Consumer Key" > token='2554' # "Access token" > token_key='HHSD' # "Access Token Secret" Example code often uses fictitious security keys. Are you sure these values are genuine values that work if you use them to access twitter directly? > t = Twitter( > auth=OAuth(token, token_key, con_secret, con_secret_key)) > t.statuses.user_timeline(screen_name="RenateBergmann") > > The reply is: > twitter.api.TwitterHTTPError: Twitter sent status 401 for URL: > 1.1/statuses/user_timeline.json using parameters: > (oauth_consumer_key=DA...&oauth_nonce=...&oauth_signature_method=HMAC-SHA1&oauth_timestamp=....&oauth_token=....&oauth_version=1.0&screen_name=RenateBergmann&oauth_signature=......) > details: {"errors":[{"message":"Could not authenticate you","code":32}]} > > What's the issue? Have I used the right tokens and keys? Do you mean you used the same keys as in the example? Or have you tested the keys work via some other method of access? > Is Python 2.7 the proper version? The documentation said 2.6, but > someone told me I had to use 2.7. I doubt the differences between 2.6 and 2.7 are your problem. > Is the authentication method correct? It should be, because this is an > example from the Github readme. I can't help there I know nothing about Twitter, far less its API! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Fri Aug 8 16:25:32 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 9 Aug 2014 00:25:32 +1000 Subject: [Tutor] Error in get pixel value in coordinate (x, y) using getPixel(x, y) In-Reply-To: References: Message-ID: <20140808142532.GX4525@ando> On Thu, Aug 07, 2014 at 06:49:02PM +0700, Whees Northbee wrote: > Please help me... I'm using python 2.7.6, numpy 1.8.1, opencv 2.4.9.. > I want to get pixel value in one number like 255 not each value like these > R(190), G(23), B(45) from coordinate (x,y)... > I try these code > m_samples[k][i][j]=getPixel(img,row,col) > > But get error: > NameError: name 'getPixel' is not defined > > If I change the format become: > m_samples[k][i][j]=img.getPixel(row,col) > > Still error: > AttributeError: 'numpy.ndarray' object has no attribute 'getpixel' > > Please help me.. We cannot help you unless you help us. Where does getPixel come from? What does the documentation for it say? getPixel is not a built-in Python function, and I don't believe it is a standard numpy or opencv function (although I could be wrong). So unless you tell us where getPixel comes from, we have no possible way of telling how to use it. -- Steven From greg.markham at gmail.com Fri Aug 8 10:50:53 2014 From: greg.markham at gmail.com (Greg Markham) Date: Fri, 8 Aug 2014 01:50:53 -0700 Subject: [Tutor] Printing multi-line variables horizontally Message-ID: Hello, Python novice back again. :) I'm making progress in my learning process, but struggling whenever attempting to creatively go beyond what's required in the various chapter assignments. For example, there's a simple random die roller program that looks like the following: # Craps Roller # Demonstrates random number generation import random # generate random numbers 1 - 6 die1 = random.randint(1, 6) die2 = random.randrange(6) + 1 total = die1 + die2 print("You rolled a", die1, "and a", die2, "for a total of", total) input("\n\nPress the enter key to exit.") I wanted to make it a little more interesting by using ascii art representations of the six die. When printing, however, they do so vertically and not horizontally. Here's a snippet of the code: die_1 = """ .-----. | | | o | | | `-----'""" die_2 = """ .-----. |o | | | | o| `-----'""" print(die_1, die_2) So, how would I get this to display horizontally? Like so... .-----. .-----. | | |o | | o | | | | | | o| `-----' `-----' Thanks, Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Aug 8 19:56:41 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 8 Aug 2014 13:56:41 -0400 Subject: [Tutor] Printing multi-line variables horizontally In-Reply-To: References: Message-ID: On Fri, Aug 8, 2014 at 4:50 AM, Greg Markham wrote: > Hello, > > Python novice back again. :) I'm making progress in my learning process, > but struggling whenever attempting to creatively go beyond what's required > in the various chapter assignments. For example, there's a simple random > die roller program that looks like the following: > > > # Craps Roller > # Demonstrates random number generation > > import random > > # generate random numbers 1 - 6 > die1 = random.randint(1, 6) > die2 = random.randrange(6) + 1 > > total = die1 + die2 > > print("You rolled a", die1, "and a", die2, "for a total of", total) > > input("\n\nPress the enter key to exit.") > > > I wanted to make it a little more interesting by using ascii art > representations of the six die. When printing, however, they do so > vertically and not horizontally. Here's a snippet of the code: > > > die_1 = """ > .-----. > | | > | o | > | | > `-----'""" > > die_2 = """ > .-----. > |o | > | | > | o| > `-----'""" > > print(die_1, die_2) > > > So, how would I get this to display horizontally? > > Like so... > .-----. .-----. > | | |o | > | o | | | > | | | o| > `-----' `-----' > This isn't so easy because as you print the first die, your cursor ends up at the bottom of its display. There is a module called curses which lets you manipulate the terminal. It has functions to get the x,y position on the screen, and to set it (i. e. move the cursor). You might want to play with that. If you want to get your feet wet with unicode, you could use the dice characters (see: http://www.unicode.org/charts/PDF/U2600.pdf). >>> dice_1 = '\u2680' >>> print (dice_1) ? >>> print (dice_1, dice_2) ? ? They are pretty small. > Thanks, > > Greg > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From emile at fenx.com Fri Aug 8 19:58:28 2014 From: emile at fenx.com (emile) Date: Fri, 08 Aug 2014 10:58:28 -0700 Subject: [Tutor] Printing multi-line variables horizontally In-Reply-To: References: Message-ID: On 08/08/2014 01:50 AM, Greg Markham wrote: > > > die_1 = """ > .-----. > | | > | o | > | | > `-----'""" > > die_2 = """ > .-----. > |o | > | | > | o| > `-----'""" I'll leave the cleanup as an exercise for you. HTH, Emile From alan.gauld at btinternet.com Fri Aug 8 20:01:19 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 08 Aug 2014 19:01:19 +0100 Subject: [Tutor] Printing multi-line variables horizontally In-Reply-To: References: Message-ID: On 08/08/14 09:50, Greg Markham wrote: > I wanted to make it a little more interesting by using ascii art > representations of the six die. When printing, however, they do so > vertically and not horizontally. Here's a snippet of the code: > > > die_1 = """ > .-----. > | | > | o | > | | > `-----'""" The triple quoted strings have newlines embedded in them. > print(die_1, die_2) > > > So, how would I get this to display horizontally? > > Like so... > .-----. .-----. > | | |o | > | o | | | > | | | o| > `-----' `-----' You can split the strings and print each pair side by side separated by a gap. Sometjing like die_1 = """ .-----. | | | o | | | `-----'""".split() etc... separator = " " for index,line in enumerate(die1): print (line + separator + die2[index]) Untested, but I hope you get the idea. PS. Personally I'd keep the dies in a list(or dict) so you can access die1 as dies[0] and die2 as dies[1] The index/key is then easily determined from the roll value. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Fri Aug 8 20:03:22 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 8 Aug 2014 11:03:22 -0700 Subject: [Tutor] Printing multi-line variables horizontally In-Reply-To: References: Message-ID: On Fri, Aug 8, 2014 at 1:50 AM, Greg Markham wrote: > Hello, > > Python novice back again. :) I'm making progress in my learning process, > but struggling whenever attempting to creatively go beyond what's required > in the various chapter assignments. For example, there's a simple random > die roller program that looks like the following: Hi Greg, It looks like each die has the same dimensions. What I mean is that it looks like each "die" has the same number of lines, and each line is the same width. Is that assumption correct? If so, then that might simplify matters for you. It sounds like you're trying to build a "row" of dice. To do so, you might be able to loop over the lines of both dice at once to get the composite image. That is: row[0] = die_1_lines[0] + die_2_lines[0] row[1] = die_1_lines[1] + die_2_lines[1] ... where we take horizontal slices of each dice and stick them side by side. To make this work, we need to be able to get at individual lines. To break a string into a list of lines, see https://docs.python.org/2/library/stdtypes.html#str.splitlines From breamoreboy at yahoo.co.uk Fri Aug 8 20:50:35 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 08 Aug 2014 19:50:35 +0100 Subject: [Tutor] Printing multi-line variables horizontally In-Reply-To: References: Message-ID: On 08/08/2014 18:56, Joel Goldstick wrote: > On Fri, Aug 8, 2014 at 4:50 AM, Greg Markham wrote: >> Hello, >> >> Python novice back again. :) I'm making progress in my learning process, >> but struggling whenever attempting to creatively go beyond what's required >> in the various chapter assignments. For example, there's a simple random >> die roller program that looks like the following: >> >> >> # Craps Roller >> # Demonstrates random number generation >> >> import random >> >> # generate random numbers 1 - 6 >> die1 = random.randint(1, 6) >> die2 = random.randrange(6) + 1 >> >> total = die1 + die2 >> >> print("You rolled a", die1, "and a", die2, "for a total of", total) >> >> input("\n\nPress the enter key to exit.") >> >> >> I wanted to make it a little more interesting by using ascii art >> representations of the six die. When printing, however, they do so >> vertically and not horizontally. Here's a snippet of the code: >> >> >> die_1 = """ >> .-----. >> | | >> | o | >> | | >> `-----'""" >> >> die_2 = """ >> .-----. >> |o | >> | | >> | o| >> `-----'""" >> >> print(die_1, die_2) >> >> >> So, how would I get this to display horizontally? >> >> Like so... >> .-----. .-----. >> | | |o | >> | o | | | >> | | | o| >> `-----' `-----' >> Does this http://code.activestate.com/recipes/473893-sudoku-solver/ help at all, especially the show function right at the top? > > This isn't so easy because as you print the first die, your cursor > ends up at the bottom of its display. > > There is a module called curses which lets you manipulate the > terminal. It has functions to get the x,y position on the screen, and > to set it (i. e. move the cursor). You might want to play with that. > The Python curses module is *nix only but see this https://pypi.python.org/pypi/UniCurses/1.2 as an alternative for other platforms. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From emile at fenx.com Fri Aug 8 22:09:53 2014 From: emile at fenx.com (emile) Date: Fri, 08 Aug 2014 13:09:53 -0700 Subject: [Tutor] Printing multi-line variables horizontally In-Reply-To: References: Message-ID: On 08/08/2014 10:58 AM, emile wrote: > On 08/08/2014 01:50 AM, Greg Markham wrote: >> >> >> die_1 = """ >> .-----. >> | | >> | o | >> | | >> `-----'""" >> >> die_2 = """ >> .-----. >> |o | >> | | >> | o| >> `-----'""" > Not quite sure how this part was dropped... >>> for line in zip(die_1.split("\n"),die_2.split("\n")): print line ... ('', '') ('.-----.', '.-----.') ('| |', '|o |') ('| o |', '| |') ('| |', '| o|') ("`-----'", "`-----'") > > I'll leave the cleanup as an exercise for you. > > HTH, > > Emile > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From dyoo at hashcollision.org Fri Aug 8 23:11:33 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 8 Aug 2014 14:11:33 -0700 Subject: [Tutor] Pigs can fly? Message-ID: Hi everyone, I'm curious if anyone has encountered: http://codegolf.stackexchange.com/questions/35623/are-pigs-able-to-fly As soon as I saw this problem, I felt strongly compelled to play with this. :P Of course, I can't show any solutions, but I thought the problem might be interesting to others here. Even without the code minimization constraints due to "code golf" I still think it's a worthwhile problem to work out. It's one of those problems that exercises multiple skills for the intermediate Python programmer, such as input/output, parsing, knowing your data structures, and writing good test cases. And it makes a good case that interesting and fun problems can be mathematical, and yet have nothing to do with basic arithmetic. What's really being asked in the problem is a graph traversal in disguise. From steve at pearwood.info Sat Aug 9 05:28:08 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 9 Aug 2014 13:28:08 +1000 Subject: [Tutor] Printing multi-line variables horizontally In-Reply-To: References: Message-ID: <20140809032808.GY4525@ando> On Fri, Aug 08, 2014 at 01:50:53AM -0700, Greg Markham wrote: [...] > So, how would I get this to display horizontally? > > Like so... > .-----. .-----. > | | |o | > | o | | | > | | | o| > `-----' `-----' Nice question! I recommend that you try to solve the problem yourself, if you can, but once you've given it a good solid try, you can have a look at my solution and see if you can understand it. Feel free to ask questions as needed. S P O I L E R S P A C E . . . N O C H E A T I N G def expand(rows, width, height): """Expand a list of strings to exactly width chars and height rows. >>> block = ["abcde", ... "fgh", ... "ijklmno"] >>> result = expand(block, 8, 4) >>> for row in result: ... print (repr(row)) ... 'abcde ' 'fgh ' 'ijklmno ' ' ' """ if len(rows) > height: raise ValueError('too many rows') extra = ['']*(height - len(rows)) rows = rows + extra for i, row in enumerate(rows): if len(row) > width: raise ValueError('row %d is too wide' % i) rows[i] = row + ' '*(width - len(row)) return rows def join(strings, sep=" "): """Join a list of strings side-by-side, returning a single string. >>> a = '''On peut rire de tout, ... mais pas avec tout le ... monde. ... -- Pierre Desproges''' >>> b = '''You can laugh about ... everything, but not ... with everybody.''' >>> values = ["Quote:", a, b] >>> print (join(values, sep=" ")) #doctest:+NORMALIZE_WHITESPACE Quote: On peut rire de tout, You can laugh about mais pas avec tout le everything, but not monde. with everybody. -- Pierre Desproges """ blocks = [s.split('\n') for s in strings] h = max(len(block) for block in blocks) for i, block in enumerate(blocks): w = max(len(row) for row in block) blocks[i] = expand(block, w, h) result = [] for row in zip(*blocks): result.append(sep.join(row)) return '\n'.join(result) -- Steven From kwpolska at gmail.com Sat Aug 9 12:39:37 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sat, 9 Aug 2014 12:39:37 +0200 Subject: [Tutor] Fwd: Printing multi-line variables horizontally In-Reply-To: References: Message-ID: It looks ilke this WONDERFUL mailing list which does not do something as basic as a sane Reply-to header made me send a response to the OP only. Here it is again: ---------- Forwarded message ---------- From: Chris ?Kwpolska? Warrick Date: Fri, Aug 8, 2014 at 7:36 PM Subject: Re: [Tutor] Printing multi-line variables horizontally To: Greg Markham On Aug 8, 2014 7:22 PM, "Greg Markham" wrote: > > Hello, > > Python novice back again. :) I'm making progress in my learning process, but struggling whenever attempting to creatively go beyond what's required in the various chapter assignments. For example, there's a simple random die roller program that looks like the following: > > > # Craps Roller > # Demonstrates random number generation > > import random > > # generate random numbers 1 - 6 > die1 = random.randint(1, 6) > die2 = random.randrange(6) + 1 > > total = die1 + die2 > > print("You rolled a", die1, "and a", die2, "for a total of", total) > > input("\n\nPress the enter key to exit.") > > > I wanted to make it a little more interesting by using ascii art representations of the six die. When printing, however, they do so vertically and not horizontally. Here's a snippet of the code: > > > > die_2 = """ > .-----. > |o | > | | > | o| > `-----'""" > > print(die_1, die_2) > > > So, how would I get this to display horizontally? > > Like so... > .-----. .-----. > | | |o | > | o | | | > | | | o| > `-----' `-----' > > Thanks, > > Greg > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > You would need to do some extra work. Specifically, you must split the string into lines, and print them side-by-side and line-by-line. Like this: die_1 = [ ".-----.", "|o |", "| |", "| o|", "`-----'", ] die_2 = [ ".-----.", "| |", "| o |", "| |", "`-----'", ] for l, r in zip(die_1, die_2): print(l, r) -- Chris ?Kwpolska? Warrick Sent from my SGS3. From steve at pearwood.info Sat Aug 9 13:42:47 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 9 Aug 2014 21:42:47 +1000 Subject: [Tutor] Fwd: Printing multi-line variables horizontally In-Reply-To: References: Message-ID: <20140809114247.GA4525@ando> On Sat, Aug 09, 2014 at 12:39:37PM +0200, Chris ?Kwpolska? Warrick wrote: > It looks ilke this WONDERFUL mailing list which does not do something > as basic as a sane Reply-to header made me send a response to the OP > only. Here it is again: [...] Although I personally agree with you that setting the Reply-To address to the list is more sensible than the alternative, I'll point out that it is not the only "sane" option. http://woozle.org/~neale/papers/reply-to-still-harmful.html I don't agree with all the arguments here, I think the author has jumped to some unjustified conclusions, and I don't think the argument is anywhere near as settled as he thinks. Certainly the mailing list should never override a Reply-To header that has been set by the sender, but that doesn't mean it can't set one where it hasn't been set. In any case, you should be able to set the Reply-To address yourself (either manually, or if your mail client allows it, automatically) and the mailing list will honour it. I have done so in this post, so we'll see what happens. -- Steven From r.kentish at btinternet.com Sun Aug 10 11:32:52 2014 From: r.kentish at btinternet.com (RICHARD KENTISH) Date: Sun, 10 Aug 2014 10:32:52 +0100 Subject: [Tutor] Error message Message-ID: <1407663172.35331.YahooMailNeo@web186002.mail.ir2.yahoo.com> Hi! Ive installed Python 2.7.8 and pygame 1.9.1 onto a macbook pro 10.9.4 Mavericks. The code is taken direct from the 'making games' book. Here it is pasted from idle: import pygame, sys from pygame.locals import * pygame.init() displaysurf = pygame.dispaly.set_mode((400, 300)) pygame.display.set_caption('Hello World!') while True: # main game loop ? ? for event in pygame.event.get(): ? ? ? ? if event.type == quit: ? ? ? ? ? ? pygame.quit() ? ? ? ? ? ? sys.exit() ? ? pygame.display.update() Here is the error I am getting. Python 2.7.8 (v2.7.8:ee879c0ffa11, Jun 29 2014, 21:07:35)? [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================ >>>? Traceback (most recent call last): ? File "/Users/richardkentish/Desktop/Python resources/blankgame.py", line 1, in ? ? import pygame, sys ? File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", line 95, in ? ? from pygame.base import * ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so, 2): no suitable image found. ?Did find: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so: no matching architecture in universal wrapper Thanks for your help. Best wishes, Richard -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Aug 10 13:30:55 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 10 Aug 2014 21:30:55 +1000 Subject: [Tutor] Error message In-Reply-To: <1407663172.35331.YahooMailNeo@web186002.mail.ir2.yahoo.com> References: <1407663172.35331.YahooMailNeo@web186002.mail.ir2.yahoo.com> Message-ID: <20140810113055.GD4525@ando> On Sun, Aug 10, 2014 at 10:32:52AM +0100, RICHARD KENTISH wrote: > Hi! > > Ive installed Python 2.7.8 and pygame 1.9.1 onto a macbook pro 10.9.4 Mavericks. > > The code is taken direct from the 'making games' book. Here it is pasted from idle: Whenever you have a mysterious error in Python that doesn't appear to be an error on your part -- and I admit that as a beginner, it's hard to tell which errors are yours and which aren't -- it's always worth trying again running Python directly. IDEs like IDLE sometimes do funny things to the environment in order to provide an Integrated Development Environment, and occasionally they can interfere with the clean running of Python code. So, just to be sure, I suggest you try running your code again outside of IDLE: * Save your code to a file (which I see you've already done). * Open up a terminal so you have a command line. * Change into the directory where your file is saved. Type this command: cd "/Users/richardkentish/Desktop/Python resources" then press ENTER. * Run the file directly using Python by typing this command: python blankgame.py then press ENTER. If the error goes away, and you either get no error at all, or a different error, then it may be a problem with IDLE. Copy and paste the error here, and we can advise further. Having said all that, looking at the exception you get: > Traceback (most recent call last): > ? File "/Users/richardkentish/Desktop/Python resources/blankgame.py", line 1, in > ? ? import pygame, sys > ? File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", line 95, in > ? ? from pygame.base import * > ImportError: > dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so, > 2): no suitable image found. ?Did find: > /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so: > no matching architecture in universal wrapper it looks to me like perhaps you have a version of Pygame which is not compatible with the Mac. How did you install it? I'm not a Mac expert (it's been about, oh, 17 years since I've used a Mac) but somebody else may be able to advise. -- Steven From beachkidken at gmail.com Sun Aug 10 15:41:03 2014 From: beachkidken at gmail.com (Ken G.) Date: Sun, 10 Aug 2014 09:41:03 -0400 Subject: [Tutor] Error in printing out totalSystolic on paper (1018) Message-ID: <53E7766F.3000406@gmail.com> Receiving the following error from the terminal screen: Traceback (most recent call last): File "Blood Pressure05Print45.py", line 95, in pr.write(totalSystolic) TypeError: expected a character buffer object Portion of strip: ================= pr.write (" "), pr.write (pulse), pr.write ("\n") totalSystolic = totalSystolic + int(systolic) totalDiastolic = totalDiastolic + int(diastolic) totalPulse = totalPulse + int(pulse) file1.close() print print totalSystolic, totalDiastolic, totalPulse # sys.exit() pr.write(totalSystolic) # pr.write(totalDiastolic) # pr.write(totalPulse) ========================== I know that totalSystolic is 1018, totalDiastolic is 469 and totalPulse is 465. I can not figure out why pr.write won't print out 1018 on paper. Using Python 2.7 on Ubuntu 12.04.5 and using Geany to process the strip. Thanks for your suggestion. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun Aug 10 16:49:18 2014 From: __peter__ at web.de (Peter Otten) Date: Sun, 10 Aug 2014 16:49:18 +0200 Subject: [Tutor] Error in printing out totalSystolic on paper (1018) References: <53E7766F.3000406@gmail.com> Message-ID: Ken G. wrote: > Receiving the following error from the terminal screen: > > Traceback (most recent call last): > File "Blood Pressure05Print45.py", line 95, in > pr.write(totalSystolic) > TypeError: expected a character buffer object > > Portion of strip: > ================= > > pr.write (" "), pr.write (pulse), pr.write ("\n") > totalSystolic = totalSystolic + int(systolic) > totalDiastolic = totalDiastolic + int(diastolic) > totalPulse = totalPulse + int(pulse) > file1.close() > print > print totalSystolic, totalDiastolic, totalPulse > > # sys.exit() > > pr.write(totalSystolic) > # pr.write(totalDiastolic) > # pr.write(totalPulse) > > ========================== > > I know that totalSystolic is 1018, totalDiastolic is 469 and > totalPulse is 465. > > I can not figure out why pr.write won't print out 1018 on paper. > > Using Python 2.7 on Ubuntu 12.04.5 and using Geany to process the strip. > > Thanks for your suggestion. Assuming that pr is a file object the write() method accepts only strings. You are passing an integer. To fix your code you can either convert explicitly pr.write(str(totalSystolic)) or implicitly print >> pr, totalSystolic (as usual print appends a newline). From beachkidken at gmail.com Sun Aug 10 16:59:52 2014 From: beachkidken at gmail.com (Ken G.) Date: Sun, 10 Aug 2014 10:59:52 -0400 Subject: [Tutor] Error in printing out totalSystolic on paper (1018) In-Reply-To: <0a58426a608cb126eb47ec7db4524a45@sonic.net> References: <53E7766F.3000406@gmail.com> <0a58426a608cb126eb47ec7db4524a45@sonic.net> Message-ID: <53E788E8.3050404@gmail.com> On 08/10/2014 10:38 AM, Alex Kleider wrote: > On 2014-08-10 06:41, Ken G. wrote: >> Receiving the following error from the terminal screen: >> >> Traceback (most recent call last): >> File "Blood Pressure05Print45.py", line 95, in >> pr.write(totalSystolic) >> TypeError: expected a character buffer object >> >> Portion of strip: >> ================= >> >> pr.write (" "), pr.write (pulse), pr.write ("\n") >> totalSystolic = totalSystolic + int(systolic) >> totalDiastolic = totalDiastolic + int(diastolic) >> totalPulse = totalPulse + int(pulse) >> file1.close() >> print >> print totalSystolic, totalDiastolic, totalPulse >> >> # sys.exit() >> >> pr.write(totalSystolic) >> # pr.write(totalDiastolic) >> # pr.write(totalPulse) >> >> ========================== >> >> I know that totalSystolic is 1018, totalDiastolic is 469 and >> totalPulse is 465. >> >> I can not figure out why pr.write won't print out 1018 on paper. >> >> Using Python 2.7 on Ubuntu 12.04.5 and using Geany to process the strip. >> >> Thanks for your suggestion. >> >> Ken > > > I'm guessing that you've defined pr.write() to take a string > object but have fed it an integer- hence type error: try > pr.write(str(totalSystolic)) > instead of just pr.write(totalSystolic) > > By the way, those are incredibly high numbers! What units are you using? Thank you, I will try pr.write(str(totalSystolic)). As for the high numbers, they are a total of 8 readings, therefore, Systolic: 1018/8 = 127.25 Diastolic: 469/8 = 58.625 Pulse: 465/8 = 58.125 Again, thanks. Ken From beachkidken at gmail.com Sun Aug 10 17:11:05 2014 From: beachkidken at gmail.com (Ken G.) Date: Sun, 10 Aug 2014 11:11:05 -0400 Subject: [Tutor] Error in printing out totalSystolic on paper (1018) [SOLVED] Message-ID: <53E78B89.2030306@gmail.com> Thanks you to the list for helping me solve my problem. I never had problem using and printing on paper "pr.write" in my coding until this latest one popped up. Yeah, this old dog is still learning new tricks here. LOL. Again, thanks. Ken -------------- next part -------------- An HTML attachment was scrubbed... URL: From bill5work at outlook.com Sun Aug 10 13:30:43 2014 From: bill5work at outlook.com (Bill) Date: Sun, 10 Aug 2014 12:30:43 +0100 Subject: [Tutor] Using Python and Regex Message-ID: Hi, I'm relatively new to Python and I'm trying to write a script to iterate through a series of text files in folder searching for some specific text and write it to a CSV. I plan to use Regex to match the text and I have already identified the Regex to do this. I've also got as far as creating a CSV using python but, being new to this, I'm looking for some pointers on how to traverse through the folder and open each file in turn to check the content for matches using Regex. Any advice would be gratefully received. Regards Bill From r.kentish at btinternet.com Sun Aug 10 14:30:01 2014 From: r.kentish at btinternet.com (RICHARD KENTISH) Date: Sun, 10 Aug 2014 13:30:01 +0100 Subject: [Tutor] Error message In-Reply-To: <20140810113055.GD4525@ando> References: <1407663172.35331.YahooMailNeo@web186002.mail.ir2.yahoo.com> <20140810113055.GD4525@ando> Message-ID: <1407673801.10072.YahooMailNeo@web186004.mail.ir2.yahoo.com> Thanks for your response. I have tried your suggestion and get the same error. ?Here's the text from terminal. Richards-MacBook-Pro:Python resources richardkentish$ pwd /Users/richardkentish/desktop/Python resources Richards-MacBook-Pro:Python resources richardkentish$ python blankgame.py Traceback (most recent call last): ? File "blankgame.py", line 1, in ? ? import pygame, sys ? File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", line 95, in ? ? from pygame.base import * ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so, 2): no suitable image found.? Did find: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so: no matching architecture in universal wrapper Richards-MacBook-Pro:Python resources richardkentish$? I installed the python files from the python site, latest version for mac. Best wishes, Richard ________________________________ From: Steven D'Aprano To: tutor at python.org Sent: Sunday, 10 August 2014, 12:30 Subject: Re: [Tutor] Error message On Sun, Aug 10, 2014 at 10:32:52AM +0100, RICHARD KENTISH wrote: > Hi! > > Ive installed Python 2.7.8 and pygame 1.9.1 onto a macbook pro 10.9.4 Mavericks. > > The code is taken direct from the 'making games' book. Here it is pasted from idle: Whenever you have a mysterious error in Python that doesn't appear to be an error on your part -- and I admit that as a beginner, it's hard to tell which errors are yours and which aren't -- it's always worth trying again running Python directly. IDEs like IDLE sometimes do funny things to the environment in order to provide an Integrated Development Environment, and occasionally they can interfere with the clean running of Python code. So, just to be sure, I suggest you try running your code again outside of IDLE: * Save your code to a file (which I see you've already done). * Open up a terminal so you have a command line. * Change into the directory where your file is saved. Type this command: ? cd "/Users/richardkentish/Desktop/Python resources" ? then press ENTER. * Run the file directly using Python by typing this command: ? python blankgame.py ? then press ENTER. If the error goes away, and you either get no error at all, or a different error, then it may be a problem with IDLE. Copy and paste the error here, and we can advise further. Having said all that, looking at the exception you get: > Traceback (most recent call last): > ? File "/Users/richardkentish/Desktop/Python resources/blankgame.py", line 1, in > ? ? import pygame, sys > ? File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", line 95, in > ? ? from pygame.base import * > ImportError: > dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so, > 2): no suitable image found. ?Did find: > /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so: > no matching architecture in universal wrapper it looks to me like perhaps you have a version of Pygame which is not compatible with the Mac. How did you install it? I'm not a Mac expert (it's been about, oh, 17 years since I've used a Mac) but somebody else may be able to advise. -- Steven _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From r.kentish at btinternet.com Sun Aug 10 17:42:50 2014 From: r.kentish at btinternet.com (RICHARD KENTISH) Date: Sun, 10 Aug 2014 16:42:50 +0100 Subject: [Tutor] Error message In-Reply-To: <1407663172.35331.YahooMailNeo@web186002.mail.ir2.yahoo.com> References: <1407663172.35331.YahooMailNeo@web186002.mail.ir2.yahoo.com> Message-ID: <1407685370.29493.YahooMailNeo@web186005.mail.ir2.yahoo.com> Hi All, I have found a work around - not entirely sure what I did but followed this website?http://www.reddit.com/r/pygame/comments/21tp7n/how_to_install_pygame_on_osx_mavericks/ Still can't run through idle but dragging the saved .py file to the python launcher works! Thanks for your help. Best wishes, Richard ________________________________ From: RICHARD KENTISH To: "tutor at python.org" Sent: Sunday, 10 August 2014, 10:32 Subject: [Tutor] Error message Hi! Ive installed Python 2.7.8 and pygame 1.9.1 onto a macbook pro 10.9.4 Mavericks. The code is taken direct from the 'making games' book. Here it is pasted from idle: import pygame, sys from pygame.locals import * pygame.init() displaysurf = pygame.dispaly.set_mode((400, 300)) pygame.display.set_caption('Hello World!') while True: # main game loop ? ? for event in pygame.event.get(): ? ? ? ? if event.type == quit: ? ? ? ? ? ? pygame.quit() ? ? ? ? ? ? sys.exit() ? ? pygame.display.update() Here is the error I am getting. Python 2.7.8 (v2.7.8:ee879c0ffa11, Jun 29 2014, 21:07:35)? [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================ >>>? Traceback (most recent call last): ? File "/Users/richardkentish/Desktop/Python resources/blankgame.py", line 1, in ? ? import pygame, sys ? File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", line 95, in ? ? from pygame.base import * ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so, 2): no suitable image found. ?Did find: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so: no matching architecture in universal wrapper Thanks for your help. Best wishes, Richard _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sun Aug 10 17:58:09 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 10 Aug 2014 11:58:09 -0400 Subject: [Tutor] Using Python and Regex In-Reply-To: References: Message-ID: On Sun, Aug 10, 2014 at 7:30 AM, Bill wrote: > > Hi, > > I'm relatively new to Python and I'm trying to write a script to iterate > through a series of text files in folder searching for some specific text > and write it to a CSV. > > I plan to use Regex to match the text and I have already identified the > Regex to do this. I've also got as far as creating a CSV using python but, > being new to this, I'm looking for some pointers on how to traverse through > the folder and open each file in turn to check the content for matches using > Regex. > You need to look at os.walk: https://docs.python.org/2/library/os.html#os.walk > Any advice would be gratefully received. > > Regards > > Bill > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com From akleider at sonic.net Sun Aug 10 18:09:06 2014 From: akleider at sonic.net (Alex Kleider) Date: Sun, 10 Aug 2014 09:09:06 -0700 Subject: [Tutor] Using Python and Regex In-Reply-To: References: Message-ID: <77a5686c398ab58398fb91ba8ec8b612@sonic.net> On 2014-08-10 08:58, Joel Goldstick wrote: > > You need to look at os.walk: > https://docs.python.org/2/library/os.html#os.walk is os.path.walk depricated? https://docs.python.org/2/library/os.path.html From akleider at sonic.net Sun Aug 10 18:05:10 2014 From: akleider at sonic.net (Alex Kleider) Date: Sun, 10 Aug 2014 09:05:10 -0700 Subject: [Tutor] Using Python and Regex In-Reply-To: References: Message-ID: <822ceaaa2b74e511f2103438cb69e800@sonic.net> On 2014-08-10 04:30, Bill wrote: > Hi, > > I'm relatively new to Python and I'm trying to write a script to > iterate through a series of text files in folder searching for some > specific text and write it to a CSV. > > I plan to use Regex to match the text and I have already identified > the Regex to do this. I've also got as far as creating a CSV using > python but, being new to this, I'm looking for some pointers on how to > traverse through the folder and open each file in turn to check the > content for matches using Regex. > > Any advice would be gratefully received. > > Regards > > Bill I suggest you begin with os.path.walk() https://docs.python.org/2/library/os.path.html To traverse files line by line: for f_name in mylistoffiles: try: f = open(f_name, 'r', encoding='utf-8') except IOError as err_report: # you might want to keep track of failures continue for line in f: # apply your regex code and do whatever From bill5work at outlook.com Mon Aug 11 09:56:46 2014 From: bill5work at outlook.com (Bill) Date: Mon, 11 Aug 2014 08:56:46 +0100 Subject: [Tutor] Using Python and Regex In-Reply-To: References: Message-ID: Thanks for yoru reply. This was my first attempt,when running through idleid get the following error:- Traceback (most recent call last): File "C:\Users\Bill\Desktop\TXT_Output\email_extraction_script.py", line 27, in traverse_dirs(working_dir) File "C:\Users\Bill\Desktop\TXT_Output\email_extraction_script.py", line 20, in traverse_dirs if match: UnboundLocalError: local variable 'match' referenced before assignment My code is as follows: import os import datetime import re now = datetime.datetime.now() timestamp = now.strftime('%d-%m-%Y') output_file = open('OUTPUT - ' + timestamp + '.csv', 'w+') def traverse_dirs(wdir): grabline = 0 for f in os.listdir('.'): if os.path.isfile(f) == True: if "Email Exceeded Maximum Size Limit" in f: continue else: content = open(f) lines = content.readlines() for line in lines: match = re.search(r"\b[^\<][A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}[^\>]\b",l ine) if match: print(match.group(0)) otext = match.group(0) + ",\n" output_file.write(otext) if __name__ == "__main__": working_dir = 'C:\\Users\\Jono\\Desktop\\TXT_Output\\' traverse_dirs(working_dir) -----Original Message----- From: Tutor [mailto:tutor-bounces+bill5work=outlook.com at python.org] On Behalf Of Bill Sent: 10 August 2014 12:31 To: tutor at python.org Subject: [Tutor] Using Python and Regex Hi, I'm relatively new to Python and I'm trying to write a script to iterate through a series of text files in folder searching for some specific text and write it to a CSV. I plan to use Regex to match the text and I have already identified the Regex to do this. I've also got as far as creating a CSV using python but, being new to this, I'm looking for some pointers on how to traverse through the folder and open each file in turn to check the content for matches using Regex. Any advice would be gratefully received. Regards Bill _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From ch2009 at arcor.de Mon Aug 11 09:02:43 2014 From: ch2009 at arcor.de (Chris) Date: Mon, 11 Aug 2014 09:02:43 +0200 Subject: [Tutor] Python twitter "errors":[{"message":"Could not authenticate you", "code":32 In-Reply-To: References: <53E458A7.4060909@arcor.de> Message-ID: <53E86A93.30902@arcor.de> On 08/08/2014 09:28 AM, Alan Gauld wrote: > > Example code often uses fictitious security keys. Are you sure these > values are genuine values that work if you use them to access > twitter directly? > Do you mean you used the same keys as in the example? Or have you > tested the keys work via some other method of access? I used my own keys and shortened them for this posting. They were working with an curl example from the twitter's dev homepage. > I can't help there I know nothing about Twitter, far less its API! Now, I've downloaded another twitter-library - and it's working! Nevertheless thank you for your reply. -- Christian From __peter__ at web.de Mon Aug 11 14:03:24 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 11 Aug 2014 14:03:24 +0200 Subject: [Tutor] Using Python and Regex References: Message-ID: Bill wrote: > Thanks for yoru reply. This was my first attempt,when running through > idleid get the following error:- > > > Traceback (most recent call last): > File "C:\Users\Bill\Desktop\TXT_Output\email_extraction_script.py", line > 27, in > traverse_dirs(working_dir) > File "C:\Users\Bill\Desktop\TXT_Output\email_extraction_script.py", line > 20, in traverse_dirs > if match: > UnboundLocalError: local variable 'match' referenced before assignment > > My code is as follows: > for line in lines: > match = > re.search(r"\b[^\<][A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4} [^\>]\b",l > ine) > if match: > print(match.group(0)) > otext = match.group(0) + ",\n" > output_file.write(otext) The indentation of 'if match' is wrong; the way you wrote the line will be executed after the for loop, but you want it inside the loop. You are lucky that the first file you encountered was empty and thus the match variable never set ;) Otherwise the error would have been harder to find. Random remarks: > def traverse_dirs(wdir): > grabline = 0 > for f in os.listdir('.'): The listdir() argument should probably be wdir instead of '.'. > if os.path.isfile(f) == True: The idiomatic way to spell this is if os.path.isfile(f): > content = open(f) > lines = content.readlines() > for line in lines: The readlines() call will put the whole file into a potentially huge list. You don't need to do this for your application. Instead iterate over the file directly: content = open(f) for line in content: That keeps memory consumption low and the data processing can start immediately. PS: The way you wrote it your program will process a single directory. If you want to look into subdirectories you should read up on os.walk() as already suggested. You will end up with something like for path, dirs, files in os.walk(wdir): for name in files: f = os.path.join(path, name) content = open(f) ... From alan.gauld at btinternet.com Mon Aug 11 18:23:06 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Aug 2014 17:23:06 +0100 Subject: [Tutor] Using Python and Regex In-Reply-To: References: Message-ID: On 11/08/14 08:56, Bill wrote: Just a wee point I noticed: > def traverse_dirs(wdir): > grabline = 0 > for f in os.listdir('.'): > if os.path.isfile(f) == True: > if "Email Exceeded Maximum Size Limit" in f: > continue Note that this checks whether the string is in the file *name*. It does not test if the string is in the file content. Is that really what you want? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Mon Aug 11 20:07:27 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 11 Aug 2014 11:07:27 -0700 Subject: [Tutor] Error message In-Reply-To: <1407663172.35331.YahooMailNeo@web186002.mail.ir2.yahoo.com> References: <1407663172.35331.YahooMailNeo@web186002.mail.ir2.yahoo.com> Message-ID: Hi Richard, I would recommend asking the PyGame folks on this one. What you're running into is specific to that external library, and folks who work with PyGame have encountered the problem before: they'll know how to diagnose and correct it. For example: http://stackoverflow.com/questions/7775948/no-matching-architecture-in-universal-wrapper-when-importing-pygame http://stackoverflow.com/questions/8275808/installing-pygame-for-mac-os-x-10-6-8 What appears to be happening is a 32-bit vs 64-bit issue: you may have installed a version of PyGame for one architecture, but should have chosen the other. From campusxuemin at gmail.com Mon Aug 11 23:28:39 2014 From: campusxuemin at gmail.com (=?UTF-8?B?546L5a2m5pWP?=) Date: Mon, 11 Aug 2014 16:28:39 -0500 Subject: [Tutor] IndentationError Message-ID: Dear Python Users, Attachment is python code. The function of this code is that I want to insert lots of fiber into matrix, data is a list storing translate vector. When a fiber is translated to matrix, I used fiber to cut matrix. So the new part will be generated, I delete the previous part and resume fiber. The loop will stop when all fibers are inserted to matrix. I used abaqus 6.11 to run fibermatrix.py, but it has problems. Thank you for your help. Best regards, Amy -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: fibermatrix.py Type: application/octet-stream Size: 22383 bytes Desc: not available URL: From alan.gauld at btinternet.com Tue Aug 12 01:51:36 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 12 Aug 2014 00:51:36 +0100 Subject: [Tutor] IndentationError In-Reply-To: References: Message-ID: On 11/08/14 22:28, ??? wrote: > for i in range(len(data)): > instancename='Part'+str(i)+'-'+str(1) > partname='Part'+str(i+1) > pre_part='Part'+str(i) > mdb.models['Model-1'].rootAssembly.translate(instanceList=('fiber-1', ),vector=(data[i][0], data[i][1], 0.0)) > mdb.models['Model-1'].rootAssembly.InstanceFromBooleanCut(cuttingInstances=(... > mdb.models['Model-1'].rootAssembly.instances['fiber-1'], ), ... > instanceToBeCut=mdb.models['Model-1'].rootAssembly.instances[instancename], ... > name=partname, originalInstances=SUPPRESS) > del mdb.models['Model-1'].parts['pre_part'] > mdb.models['Model-1'].rootAssembly.features['fiber-1'].resume() Like the subject says, you have multiple indentation errors. If you want further help I suggest you tell us what "problems" you get - including full error messages. Also if you can reduce your code to something more readable that will help. Also... from part import * from material import * the import * style of import can lead to problems with name clashes - with the last imported name masking all others. This is doubly true when you have so as many imports as you do, the likelihood of a name being used twice is quite high. Finally, I don't recognise any of the modules you are importing, I assume they are from some specialist library or other. In particular you seem to be referencing something called mdb but that does not appear as a module or variable in your code, so its impossible for us to tell what it is. (Presumably its imported as one of the * names but we have no clue which module it comes from!) You could maybe try asking for help on that library's support forum if the error proves to be library related. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Tue Aug 12 02:34:37 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 12 Aug 2014 01:34:37 +0100 Subject: [Tutor] IndentationError In-Reply-To: References: Message-ID: On 11/08/2014 22:28, ??? wrote: > Dear Python Users, > > Attachment is python code. > > The function of this code is that I want to insert lots of fiber into > matrix, data is a list storing translate vector. When a fiber is > translated to matrix, I used fiber to cut matrix. So the new part will > be generated, I delete the previous part and resume fiber. The loop will > stop when all fibers are inserted to matrix. I used abaqus 6.11 to run > fibermatrix.py, but it has problems. Thank you for your help. > > Best regards, > Amy > I'm awfully sorry but I'm not downloading a 22kb file just to find an IndentationError. Please see this http://sscce.org/ -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From campusxuemin at gmail.com Tue Aug 12 03:15:17 2014 From: campusxuemin at gmail.com (=?UTF-8?B?546L5a2m5pWP?=) Date: Mon, 11 Aug 2014 20:15:17 -0500 Subject: [Tutor] how to fix coordinates a part in assembly Message-ID: Dear python users, Since instance includes lots of parts, I want to fix one of the part's coordinates in local coordinates in assembly. How can I fix it. Thank you in advance. Best regards, Amy -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Aug 12 09:15:48 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 12 Aug 2014 08:15:48 +0100 Subject: [Tutor] how to fix coordinates a part in assembly In-Reply-To: References: Message-ID: On 12/08/14 02:15, ??? wrote: > Dear python users, > > Since instance includes lots of parts, I want to fix one of the part's > coordinates in local coordinates in assembly. How can I fix it. Thank > you in advance. As with your other message you give us no clue what you are doing. What is a part? what is an assembly? What does it mean to "fix coordinates in local coordinates? How do you identify which part you want to fix? This is not part of the standard Python library which is what this mailing list is about. If you want help you will need to give us much more information about what libraries you are using and what you are doing with them. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Tue Aug 12 09:26:09 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 12 Aug 2014 09:26:09 +0200 Subject: [Tutor] IndentationError References: Message-ID: ??? wrote: > Dear Python Users, > > Attachment is python code. > > The function of this code is that I want to insert lots of fiber into > matrix, data is a list storing translate vector. When a fiber is > translated to matrix, I used fiber to cut matrix. So the new part will be > generated, I delete the previous part and resume fiber. The loop will stop > when all fibers are inserted to matrix. I used abaqus 6.11 to run > fibermatrix.py, but it has problems. Thank you for your help. You are mixing tabs and spaces. Configure your editor to display a tab as eight spaces and you will see the problem. If your editer offers an option to translate a hit on the tab key into four spaces I recommend that you toggle that option to avoid the problem in the future. From breamoreboy at yahoo.co.uk Tue Aug 12 09:53:46 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 12 Aug 2014 08:53:46 +0100 Subject: [Tutor] how to fix coordinates a part in assembly In-Reply-To: References: Message-ID: On 12/08/2014 02:15, ??? wrote: > Dear python users, > > Since instance includes lots of parts, I want to fix one of the part's > coordinates in local coordinates in assembly. How can I fix it. Thank > you in advance. > > Best regards, > Amy > Please refer to "The SSCCE - Short, Self Contained, Correct (Compilable), Example" at http://sscce.org/ for instructions on how to put a question together for this list. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From keithadu at live.com Tue Aug 12 22:52:44 2014 From: keithadu at live.com (keith papa) Date: Tue, 12 Aug 2014 16:52:44 -0400 Subject: [Tutor] Exercise to work on Message-ID: Hi, am a newbie to python and I wondering if you guys can give me some exercise to work on. I have learned: print function , if function , strings, variables, and raw_input. The more the better -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Wed Aug 13 02:27:32 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 12 Aug 2014 17:27:32 -0700 Subject: [Tutor] Exercise to work on In-Reply-To: References: Message-ID: On Tue, Aug 12, 2014 at 1:52 PM, keith papa wrote: > Hi, am a newbie to python and I wondering if you guys can give me some > exercise to work on. I have learned: print function , if function , strings, > variables, and raw_input. The more the better Do you find yourself doing certain kinds of computations? A typical first beginner example is to compute a fahrenheit to celsius calculator. Numbers are usually easy to work with, so problems that automate basic computations are prevalent in beginner exercises. I'd recommend trying exercises in a beginner's textbook; those are usually fairly easy to do and useful. For example: http://www.greenteapress.com/thinkpython/html/thinkpython003.html#toc23 --- Besides that, do you have hobbies or interests outside of computer programming? Maybe there's something there that you can approach. When I'm learning a language, I try to do something personal to make it concrete, useful, and fun. For example (though not related to Python programming), when I was learning Golang, I tried: https://plus.google.com/117593568781545916065/posts/CALjoYeKU7r because was in the middle of trying to figure out how marginal taxes work, having read an article and not quite getting it. Writing that program let me learn both something domain-specific as well as get a feel for a different programming language. From greg.markham at gmail.com Wed Aug 13 01:25:10 2014 From: greg.markham at gmail.com (Greg Markham) Date: Tue, 12 Aug 2014 16:25:10 -0700 Subject: [Tutor] Simple guessing game - need help with the math Message-ID: Hello again, I'm working on one of the more advanced (at this stage of my learning process), albeit optional, assignments. The objective is to write a program that tries to guess your number from 1 to 100. After each guess, you tell it if it's (h)igher, (l)ower or (c)orrect, and eventually it'll logically zero in on the correct value. In addition, it should count the number of tries required to come to the correct guess. I've worked through a few hiccups so far, but I've come to a standstill. Here follows my code: import os print ("\nShall we play a game?\n\n") print ("Think of a number, 1 to 100, and I will attempt to guess what it is.\n") input("Press [Enter] when ready.\n") guess = 50 change = 50 answer = "" tries = 1 while answer == "h" or "l" or "c": print ("My guess is: ", guess, "\n") answer = input("Is it (H)igher? (L)ower? Or am I (C)orrect? ") answer = answer.lower() if answer == "h": guess = round(int(guess + (change/2))) change = change/2 tries += 1 elif answer == "l": guess = round(int(guess - (guess/2))) tries += 1 elif answer == "c": print ("/n/nYay! I win. Shall we play again?\n\n") os.system('cls' if os.name == 'nt' else 'clear') else: print ("Invalid response. Please try again.\n") Something about the math in the code here isn't quite right. If you were to enter "h" (for 'higher') each time, it would first guess 50, then 75, then 87, then 93, then 96, and finally would stop progressing at the number 97. I suspect it's a side-effect of the way the round function works, but I don't know how to get around it. Any help would be greatly appreciated. Thanks in advance, Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg.markham at gmail.com Wed Aug 13 01:29:39 2014 From: greg.markham at gmail.com (Greg Markham) Date: Tue, 12 Aug 2014 16:29:39 -0700 Subject: [Tutor] Exercise to work on In-Reply-To: References: Message-ID: Keith, This should get you started... http://learnpythonthehardway.org/book/ http://www.codecademy.com/en/tracks/python http://docs.python-guide.org/en/latest/intro/learning/ Happy coding! --Greg On Tue, Aug 12, 2014 at 1:52 PM, keith papa wrote: > Hi, am a newbie to python and I wondering if you guys can give me some > exercise to work on. I have learned: print function , if function , > strings, variables, and raw_input. The more the better > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joseph.lee22590 at gmail.com Wed Aug 13 00:39:51 2014 From: joseph.lee22590 at gmail.com (Joseph Lee) Date: Tue, 12 Aug 2014 15:39:51 -0700 Subject: [Tutor] Exercise to work on Message-ID: <53ea97d9.c151b60a.1044.052e@mx.google.com> Hi Keith, It depends on what you want to do with Python in the end (by the way, if statement is not a function). Here are some of my suggestions (based on current topics and things to come later): 1. Write a loop which prints even numbers from 1 to 100. 2. Write a program which determines if the entered number is an even or odd number. 3. Given a string, locate the last occurrence of a character. 4. Write a program that says number of characters in a string and whether it starts with a consonant or a vowel. I think that's it for now. Again the rest of the exercises that might show up might depend on your ultimate goal with Python (by the way, which version are you using?). Other topics to learn about would be how to write functions, reading from a file, while and for loops and working with organized data such as lists and dictionaries. Cheers, Joseph ----- Original Message ----- From: keith papa Hi Keith, As a follow-up: I'm sure others might have mentioned this, but I also recommend doing exercises presented in the book or reference you're using to learn Python. Cheers, Joseph ----- Original Message ----- From: keith papa References: Message-ID: My apologies, this reply didn't make its way to the list. > > On Aug 13, 2014 1:25 AM, "diliup gabadamudalige" wrote: > > > > Wouldn't it be easier to work it this way? > > for example: > > number range =100 > > your selection = 82 > > > > round 1 > > computer guesses 50 > > you say higher > > then in round 2 the computer makes a guess only between 51 and 100 > > computer guesses 92 > > you say lower > > round 3 computer guesses between 51 and 91 > > round 4 computer guesses 75 > > you say higher > > now guess is between 76 and 91 > > etc. till the correct answer is reached > > you can use the random and range to select a random number between two numbers > > Interesting. I hadn't thought of that. And, it appears that would circumvent the issue I'm running into with rounding. I will try that approach; thank-you. > > But my curiosity is still begging me for an answer regarding my original approach. Is there a way to manage the functionality of be round function such that it does not strip any data to the right of the decimal point? > > Thanks, > > Greg > > > > > > > > > On Wed, Aug 13, 2014 at 4:55 AM, Greg Markham wrote: > >> > >> Hello again, > >> > >> I'm working on one of the more advanced (at this stage of my learning process), albeit optional, assignments. The objective is to write a program that tries to guess your number from 1 to 100. After each guess, you tell it if it's (h)igher, (l)ower or (c)orrect, and eventually it'll logically zero in on the correct value. In addition, it should count the number of tries required to come to the correct guess. > >> > >> I've worked through a few hiccups so far, but I've come to a standstill. Here follows my code: > >> > >> import os > >> > >> print ("\nShall we play a game?\n\n") > >> print ("Think of a number, 1 to 100, and I will attempt to guess what it is.\n") > >> > >> input("Press [Enter] when ready.\n") > >> > >> guess = 50 > >> change = 50 > >> answer = "" > >> tries = 1 > >> > >> while answer == "h" or "l" or "c": > >> print ("My guess is: ", guess, "\n") > >> answer = input("Is it (H)igher? (L)ower? Or am I (C)orrect? ") > >> answer = answer.lower() > >> if answer == "h": > >> guess = round(int(guess + (change/2))) > >> change = change/2 > >> tries += 1 > >> elif answer == "l": > >> guess = round(int(guess - (guess/2))) > >> tries += 1 > >> elif answer == "c": > >> print ("/n/nYay! I win. Shall we play again?\n\n") > >> os.system('cls' if os.name == 'nt' else 'clear') > >> else: > >> print ("Invalid response. Please try again.\n") > >> > >> > >> Something about the math in the code here isn't quite right. If you were to enter "h" (for 'higher') each time, it would first guess 50, then 75, then 87, then 93, then 96, and finally would stop progressing at the number 97. I suspect it's a side-effect of the way the round function works, but I don't know how to get around it. > >> > >> Any help would be greatly appreciated. > >> > >> Thanks in advance, > >> > >> Greg > >> > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> To unsubscribe or change subscription options: > >> https://mail.python.org/mailman/listinfo/tutor > >> > > > > > > > > -- > > Diliup Gabadamudalige > > > > http://www.diliupg.com > > http://soft.diliupg.com/ > > > > ********************************************************************************************** > > This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. > > ********************************************************************************************** > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Wed Aug 13 21:13:19 2014 From: davea at davea.name (Dave Angel) Date: Wed, 13 Aug 2014 15:13:19 -0400 (EDT) Subject: [Tutor] Simple guessing game - need help with the math References: Message-ID: Greg Markham Wrote in message: Please post as text. Because you used html, I cannot quote your message, or indeed even see it at all while replying. There are other problems frequently triggered by html, but on to my response. You don't specify the python version you're writing for. I have to guess 3.x, since your use of input would have been improper in 2.x. Your immediate problem is indeed caused by truncation. In python version 2.x, dividing an int ny 2 will truncate down. You can fix that by using change = int ((1 + change)/ 2) You also need to repeat that in the appropriate elif clause. You do have other problems, however, Your calculation for the new guess is wrong in the elif clause. See if you can spot the problem. Your while loop termination condition will end the loop if a user types something other than one of the three valid ones. And your logic when the user says 'c' starts the next game without reinitializing guess to 50. Your use of round in the guess= lines is superfluous. But you may need to add 1 here as well. I'd suggest starting change at 100, and cutting it in half before adding or subtracting it from the guess. Incidentally, once your code is fixed, it'll converge much faster than the other random suggestion. Further, the binary search technique is well worth understanding and mastering. If I were coding this, then instead of keeping a 'change' variable, I'd keep an upperlimit and a lowerlimit one. Start them at 0 and 101, and start your loop. Each time through the loop your guess would be halfway between the limits. And each time the user tells you that you were high or low, you'd adjust the upperlimit or lowerlimit respectively. -- DaveA From ctny at ctny.org Thu Aug 14 04:07:58 2014 From: ctny at ctny.org (= Clayton - Tang =) Date: Wed, 13 Aug 2014 22:07:58 -0400 (EDT) Subject: [Tutor] read cell phone's directory? Message-ID: <190799530.4224.1407982078363.open-xchange@oxuslxltgw17.lxa.perfora.net> Hi all, I am on WIndows and have an Android cell phone running Android 4.4.4. When I connect the phone to my PC using a micro-USB cable, the phone appears next to the local hard drive under "This PC" window, then I can browse the phone's directory like a regular disk. My goal is to find all the photos on the phone then do something with the files. So I copied the path from the File Explore navigation bar, which is 'This PC\Nexus 5\Internal storage\DCIM\Camera', but the follow code doesn't work. I get an error "W indowsError: [Error 3] The system cannot find the path specified: 'This PC\\Nexus 5\\Internal storage\\DCIM\\Camera/*.*". Does anyone know who to make it work? import os; ## Example pulls filenames from a dir, prints their relative and absolute paths def printdir(dir): filenames = os.listdir(dir) for filename in filenames: print filename ## foo.txt print os.path.join(dir, filename) ## dir/foo.txt (relative to current dir) print os.path.abspath(os.path.join(dir, filename)) ## /home/nick/dir/foo.txt print if __name__ == '__main__': printdir('This PC\Nexus 5\Internal storage\DCIM\Camera') Clayton -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwpolska at gmail.com Thu Aug 14 10:09:23 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Thu, 14 Aug 2014 10:09:23 +0200 Subject: [Tutor] read cell phone's directory? In-Reply-To: <190799530.4224.1407982078363.open-xchange@oxuslxltgw17.lxa.perfora.net> References: <190799530.4224.1407982078363.open-xchange@oxuslxltgw17.lxa.perfora.net> Message-ID: On Aug 14, 2014 9:30 AM, "= Clayton - Tang =" wrote: > > Hi all, > > I am on WIndows and have an Android cell phone running Android 4.4.4. > > When I connect the phone to my PC using a micro-USB cable, the phone appears next to the local hard drive under "This PC" window, then I can browse the phone's directory like a regular disk. My goal is to find all the photos on the phone then do something with the files. So I copied the path from the File Explore navigation bar, which is 'This PC\Nexus 5\Internal storage\DCIM\Camera', but the follow code doesn't work. > > I get an error "W indowsError: [Error 3] The system cannot find the path specified: 'This PC\\Nexus 5\\Internal storage\\DCIM\\Camera/*.*". Does anyone know who to make it work? This was recently discussed on the main list (python-list aka comp.lang.python). Long story short, modern Android phones are using the MTP protocol and do not behave like usual USB drives. You must use a module that implements MTP if you want to access your phone. > import os; No need for a semicolon here. -- Chris ?Kwpolska? Warrick Sent from my SGS3. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Thu Aug 14 14:19:03 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 14 Aug 2014 05:19:03 -0700 Subject: [Tutor] read cell phone's directory? In-Reply-To: <190799530.4224.1407982078363.open-xchange@oxuslxltgw17.lxa.perfora.net> References: <190799530.4224.1407982078363.open-xchange@oxuslxltgw17.lxa.perfora.net> Message-ID: On Wed, Aug 13, 2014 at 7:07 PM, = Clayton - Tang = wrote: > Hi all, > > I am on WIndows and have an Android cell phone running Android 4.4.4. > > When I connect the phone to my PC using a micro-USB cable, the phone appears > next to the local hard drive under "This PC" window, then I can browse the > phone's directory like a regular disk. My goal is to find all the photos on > the phone then do something with the files. So I copied the path from the > File Explore navigation bar, which is 'This PC\Nexus 5\Internal > storage\DCIM\Camera', but the follow code doesn't work. Hmmm... there are a few things you may need to resolve. 1. Backslashes have a meaning in Python string literals. They mark the beginning of an escape character sequence, to let programmers represent strings that contain characters that are hard to otherwise type. See: http://learnpythonthehardway.org/book/ex10.html 2. "This PC" may be simply a convenient name that Windows 8.1 is using in its user interface. It may be mapped to a different location on your hard drive than a directory called "This PC". Unfortunately, I have no experience with Windows 8.1, so hopefully someone else might be able to investigate. From sunil.techspk at gmail.com Thu Aug 14 15:49:25 2014 From: sunil.techspk at gmail.com (Sunil Tech) Date: Thu, 14 Aug 2014 19:19:25 +0530 Subject: [Tutor] re module Message-ID: Hi, I have string like stmt = '

Patient name: Upadhyay Shyam  
Date of birth:   08/08/1988
Issue(s) to be analyzed:  testttttttttttttttttttt

Nurse Clinical summary:  test1 

Date of injury:   12/14/2013

Diagnoses:   723.4 - 300.02 - 298.3 - 780.50 - 724.4 Brachial neuritis or radiculitis nos - Generalized anxiety disorder - Acute paranoid reaction - Unspecified sleep disturbance - Thoracic or lumbosacral neuritis or radiculitis, unspecified
Requester name:   Demo Spltycdtestt
Phone #:   (213) 480-9000

Medical records reviewed
__ pages of medical and administrative records were reviewed including:


Criteria used in analysis
 

Reviewer comments


Determination
Based on the clinical information submitted for this review and using the evidence-based, peer-reviewed guidelines referenced above, this request is 

Peer Reviewer Name/Credentials  

Solis, Test, PhD
Internal Medicine
 

Attestation


Contact Information
 


Peer to Peer contact attempt 1: 08/13/2014 02:46 PM, Central, Incoming Call, Successful, No Contact Made, Peer Contact Did Not Change Determination' i am trying to find the various font sizes and font face from this string. i tried print re.search(" From kwpolska at gmail.com Thu Aug 14 16:07:14 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Thu, 14 Aug 2014 16:07:14 +0200 Subject: [Tutor] re module In-Reply-To: References: Message-ID: On 14 Aug 2014 15:58 "Sunil Tech" wrote: > > Hi, > > I have string like > stmt = '

Patient name: Upadhyay Shyam  
Date of birth:   08/08/1988
Issue(s) to be analyzed:  testttttttttttttttttttt

Nurse Clinical summary:  test1 

Date of injury:   12/14/2013

Diagnoses:   723.4 - 300.02 - 298.3 - 780.50 - 724.4 Brachial neuritis or radiculitis nos - Generalized anxiety disorder - Acute paranoid reaction - Unspecified sleep disturbance - Thoracic or lumbosacral neuritis or radiculitis, unspecified
Requester name:   Demo Spltycdtestt
Phone #:   (213) 480-9000

Medical records reviewed
__ pages of medical and administrative records were reviewed including:


Criteria used in analysis
 

Reviewer comments


Determination
Based on the clinical information submitted for this review and using the evidence-based, peer-reviewed guidelines referenced above, this request is 

Peer Reviewer Name/Credentials  

Solis, Test, PhD
Internal Medicine
 

Attestation


Contact Information
 


Peer to Peer contact attempt 1: 08/13/2014 02:46 PM, Central, Incoming Call, Successful, No Contact Made, Peer Contact Did Not Change Determination' > > > i am trying to find the various font sizes and font face from this string. > > i tried > > print re.search(" > > Thank you. > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > Don't use regular expressions for HTML. Use lxml instead. Also, why would you need that exact thing? It's useless. Also, this code is very ugly, with too many s and ? worse ? s which should not be used at all. -- Chris ?Kwpolska? Warrick Sent from my SGS3. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dvnsarma at gmail.com Thu Aug 14 17:39:06 2014 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Thu, 14 Aug 2014 21:09:06 +0530 Subject: [Tutor] re module In-Reply-To: References: Message-ID: I tested it on IDLE. It works. regards, Sarma. On Thu, Aug 14, 2014 at 7:37 PM, Chris ?Kwpolska? Warrick < kwpolska at gmail.com> wrote: > > On 14 Aug 2014 15:58 "Sunil Tech" wrote: > > > > Hi, > > > > I have string like > > stmt = '

Patient name: Upadhyay Shyam style="font-family: times new roman,times;">  
Date of > birth:   08/08/1988
Issue(s) to be > analyzed:  testttttttttttttttttttt

style="font-size: 11pt;">Nurse Clinical summary:  test1 style="font-family: times new roman,times;"> 

Date of > injury:   12/14/2013

Diagnoses:   723.4 - 300.02 - 298.3 > - 780.50 - 724.4 Brachial neuritis or radiculitis nos - Generalized > anxiety disorder - Acute paranoid reaction - Unspecified sleep disturbance > - Thoracic or lumbosacral neuritis or radiculitis, unspecified
/>Requester > name:   Demo Spltycdtestt
style="font-family: times new roman,times;">Phone #:   (213) > 480-9000

Medical records reviewed
__ pages of medical and > administrative records were reviewed including:


Criteria > used in analysis
 

Reviewer comments


/>Determination
Based on the clinical information submitted for this > review and using the evidence-based, peer-reviewed guidelines referenced > above, this request is 

Peer Reviewer > Name/Credentials  

Solis, Test, PhD
style="font-family: times new roman,times;">Internal Medicine
/> 

/>Attestation

/>
Contact Information
 


roman,times\' size=\'3\'>Peer to Peer contact attempt 1: 08/13/2014 02:46 > PM, Central, Incoming Call, Successful, No Contact Made, Peer Contact Did > Not Change Determination' > > > > > > i am trying to find the various font sizes and font face from this > string. > > > > i tried > > > > print re.search(" > > > > > Thank you. > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > Don't use regular expressions for HTML. Use lxml instead. > > Also, why would you need that exact thing? It's useless. Also, this code > is very ugly, with too many s and ? worse ? s which should not > be used at all. > > -- > Chris ?Kwpolska? Warrick > Sent from my SGS3. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mccombs at imperium.org Thu Aug 14 17:43:11 2014 From: mccombs at imperium.org (P McCombs) Date: Thu, 14 Aug 2014 08:43:11 -0700 Subject: [Tutor] Exercise to work on In-Reply-To: References: Message-ID: On Aug 12, 2014 3:29 PM, "keith papa" wrote: > > Hi, am a newbie to python and I wondering if you guys can give me some exercise to work on. I have learned: print function , if function , strings, variables, and raw_input. The more the better Checkio.org is a game made of python coding challenges. They start simple, demonstrate functional testing, and provide other users' solutions. http://www.checkio.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From ctny at ctny.org Thu Aug 14 17:48:47 2014 From: ctny at ctny.org (= Clayton - Tang =) Date: Thu, 14 Aug 2014 11:48:47 -0400 (EDT) Subject: [Tutor] read cell phone's directory? In-Reply-To: References: <190799530.4224.1407982078363.open-xchange@oxuslxltgw17.lxa.perfora.net> Message-ID: <1453709295.5853.1408031327073.open-xchange@oxuslxltgw16.lxa.perfora.net> Chris, thanks for the reply. I don't have newsgroup access, can you point me to some place where I can learn more? Do you have sample code I can learn from? Thanks. Clayton > On August 14, 2014 at 4:09 AM Chris ?Kwpolska? Warrick > wrote: > > > On Aug 14, 2014 9:30 AM, "= Clayton - Tang =" > wrote: > > > > Hi all, > > > > I am on WIndows and have an Android cell phone running Android 4.4.4. > > > > When I connect the phone to my PC using a micro-USB cable, the phone > > appears next to the local hard drive under "This PC" window, then I can > > browse the phone's directory like a regular disk. My goal is to find all > > the photos on the phone then do something with the files. So I copied the > > path from the File Explore navigation bar, which is 'This PC\Nexus > > 5\Internal storage\DCIM\Camera', but the follow code doesn't work. > > > > I get an error "W indowsError: [Error 3] The system cannot find the path > > specified: 'This PC\\Nexus 5\\Internal storage\\DCIM\\Camera/*.*". Does > > anyone know who to make it work? > > This was recently discussed on the main list (python-list aka > comp.lang.python). Long story short, modern Android phones are using the MTP > protocol and do not behave like usual USB drives. You must use a module that > implements MTP if you want to access your phone. > > > import os; > > No need for a semicolon here. > > -- > Chris ?Kwpolska? Warrick > Sent from my SGS3. > --- Clayton Tang -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Aug 14 19:33:25 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Aug 2014 18:33:25 +0100 Subject: [Tutor] read cell phone's directory? In-Reply-To: <1453709295.5853.1408031327073.open-xchange@oxuslxltgw16.lxa.perfora.net> References: <190799530.4224.1407982078363.open-xchange@oxuslxltgw17.lxa.perfora.net> <1453709295.5853.1408031327073.open-xchange@oxuslxltgw16.lxa.perfora.net> Message-ID: On 14/08/14 16:48, = Clayton - Tang = wrote: > Chris, thanks for the reply. I don't have newsgroup access, can you > point me to some place where I can learn more? Do you have sample code I > can learn from? Thanks. The main newsgroup is also available as a mailing list and can be read, for example, on the Gmane service at: http://news.gmane.org/gmane.comp.python.general -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From kwpolska at gmail.com Thu Aug 14 19:44:35 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Thu, 14 Aug 2014 19:44:35 +0200 Subject: [Tutor] read cell phone's directory? In-Reply-To: <1453709295.5853.1408031327073.open-xchange@oxuslxltgw16.lxa.perfora.net> References: <190799530.4224.1407982078363.open-xchange@oxuslxltgw17.lxa.perfora.net> <1453709295.5853.1408031327073.open-xchange@oxuslxltgw16.lxa.perfora.net> Message-ID: On 14 August 2014 17:48 "= Clayton - Tang =" wrote: > > Chris, thanks for the reply. I don't have newsgroup access, You don't need it. Use the official mailing list that is mirrored to Usenet. Main page with subscribe link: https://mail.python.org/mailman/listinfo/python-list The thread in question: https://mail.python.org/pipermail/python-list/2014-August/676375.html > can you point me to some place where I can learn more? Do you have sample code I can learn from? Thanks. The thread does not have any ready answer just yet, it's currently busy arguing about the protocol. You can Google the term ?python MTP?, you may find some answers there. -- Chris ?Kwpolska? Warrick Sent from my SGS3. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Thu Aug 14 20:50:26 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 14 Aug 2014 11:50:26 -0700 Subject: [Tutor] re module Message-ID: <1408042226.82256.BPMail_high_noncarrier@web163803.mail.gq1.yahoo.com> ----------------------------- On Thu, Aug 14, 2014 4:07 PM CEST Chris ?Kwpolska? Warrick wrote: >On 14 Aug 2014 15:58 "Sunil Tech" wrote: >> >> Hi, >> >> I have string like >> stmt = '

Patient name:?Upadhyay Shyamstyle="font-family: times new roman,times;">??
Date of >birth:???08/08/1988
Issue(s) to be >analyzed:??testttttttttttttttttttt

style="font-size: 11pt;">Nurse Clinical summary:??test1style="font-family: times new roman,times;">?

Date of >injury:???12/14/2013

Diagnoses:???723.4 - 300.02 - 298.3 >- 780.50 - 724.4?Brachial neuritis or radiculitis nos - Generalized >anxiety disorder - Acute paranoid reaction - Unspecified sleep disturbance >- Thoracic or lumbosacral neuritis or radiculitis, unspecified
/>Requester >name:???Demo Spltycdtestt
style="font-family: times new roman,times;">Phone #:???(213) >480-9000

Medical records reviewed
__ pages of medical and >administrative records were reviewed including:


Criteria >used in analysis
?

Reviewer comments


/>Determination
Based on the clinical information submitted for this >review and using the evidence-based, peer-reviewed guidelines referenced >above, this request is?

Peer Reviewer >Name/Credentials??

Solis, Test,?PhD
style="font-family: times new roman,times;">Internal Medicine
/>?

/>Attestation

/>
Contact Information
?


roman,times\' size=\'3\'>Peer to Peer contact attempt 1: 08/13/2014 02:46 >PM, Central, Incoming Call, Successful, No Contact Made, Peer Contact Did >Not Change Determination' >> >> >> i am trying to find the various font sizes and font face from this string. >> >> i tried >> >> print re.search("> >> >> Thank you. >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> >Don't use regular expressions for HTML. Use lxml instead. > >Also, why would you need that exact thing? It's useless. Also, this code is >very ugly, with too many s and ? worse ? s which should not be >used at all. Why lxml and not bs? I read that bs deals better with malformed html. You said the above html is messy, which is not necessarily the same as malformed, but.. Anyway, this reference also seems to favor lxml: http://stackoverflow.com/questions/4967103/beautifulsoup-and-lxml-html-what-to-prefer From dyoo at hashcollision.org Fri Aug 15 00:02:11 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 14 Aug 2014 15:02:11 -0700 Subject: [Tutor] re module In-Reply-To: References: Message-ID: On Thu, Aug 14, 2014 at 8:39 AM, D.V.N.Sarma ??.??.???.???? wrote: > I tested it on IDLE. It works. Hi Sarma, Following up on this one. I'm pretty sure that: print re.search(" References: Message-ID: Hi Sunil, Don't use regular expressions for this task. Use something that knows about HTML structure. As others have noted, the Beautiful Soup or lxml libraries are probably a much better choice here. There are good reasons to avoid regexp for the task you're trying to do. For example, your regular expression: ">> import re >>> m = re.match("'(.*)'", "'quoted' text, but note how it's greedy!") >>> m.group(1) "quoted' text, but note how it" ###################################################### and note how the match doesn't limited itself to "quoted", but goes as far as it can. This shows at least one of the problems that you're going to run into. Fixing this so it doesn't grab so much is doable, of course. But there are other issues, all of which are little headaches upon headaches. (e.g. Attribute vlaues may be single or double quoted, may use HTML entity references, etc.) So don't try to parse HTML by hand. Let a library do it for you. For example with Beautiful Soup: http://www.crummy.com/software/BeautifulSoup/bs4/doc/ the code should be as straightforward as: ########################### from bs4 import BeautifulSoup soup = BeautifulSoup(stmt) for span in soup.find_all('span'): print span.get('style') ########################### where you deal with the _structure_ of your document, rather than at the low-level individual characters of that document. From nulla.epistola at web.de Fri Aug 15 09:37:14 2014 From: nulla.epistola at web.de (Sibylle Koczian) Date: Fri, 15 Aug 2014 09:37:14 +0200 Subject: [Tutor] Simple guessing game - need help with the math In-Reply-To: References: Message-ID: Am 13.08.2014 01:25, schrieb Greg Markham: > while answer == "h" or "l" or "c": > print ("My guess is: ", guess, "\n") > answer = input("Is it (H)igher? (L)ower? Or am I (C)orrect? ") > answer = answer.lower() > if answer == "h": > guess = round(int(guess + (change/2))) > change = change/2 > tries += 1 > elif answer == "l": > guess = round(int(guess - (guess/2))) > tries += 1 > elif answer == "c": > print ("/n/nYay! I win. Shall we play again?\n\n") > os.system('cls' if os.name == 'nt' else 'clear') > else: > print ("Invalid response. Please try again.\n") > Something else is wrong, besides the math: this is an infinite loop, because (answer == "h" or "l" or "c") always evaluates to True. And with the condition you probably wanted: while answer == "h" or answer == "l" or answer == "c": the loop wouldn't even start because you set answer = "" in the beginning. From derektjenkins at gmail.com Fri Aug 15 18:49:54 2014 From: derektjenkins at gmail.com (Derek Jenkins) Date: Fri, 15 Aug 2014 12:49:54 -0400 Subject: [Tutor] Simple guessing game - need help with the math In-Reply-To: References: Message-ID: I am a newbie (please correct me if I am wrong), but I happen to think that it would be best to suggest that your input be in the same case as that of your variables. In other words, it appears that you are suggesting the user make an input choice of H, L, or C while the program appears to want to handle the variables h, l, or c. Clearly my statements do not directly relate to math, but I do not see how your program would be able to handle the input of H, L, or C. On Fri, Aug 15, 2014 at 12:49 PM, Derek Jenkins wrote: > I am a newbie (please correct me if I am wrong), but I happen to think > that it would be best to suggest that your input be in the same case > as that of your variables. In other words, it appears that you are > suggesting the user make an input choice of H, L, or C while the > program appears to want to handle the variables h, l, or c. > > Clearly my statements do not directly relate to math, but I do not see > how your program would be able to handle the input of H, L, or C. > > On Fri, Aug 15, 2014 at 3:37 AM, Sibylle Koczian wrote: >> Am 13.08.2014 01:25, schrieb Greg Markham: >>> >>> while answer == "h" or "l" or "c": >>> print ("My guess is: ", guess, "\n") >>> answer = input("Is it (H)igher? (L)ower? Or am I (C)orrect? ") >>> answer = answer.lower() >>> if answer == "h": >>> guess = round(int(guess + (change/2))) >>> change = change/2 >>> tries += 1 >>> elif answer == "l": >>> guess = round(int(guess - (guess/2))) >>> tries += 1 >>> elif answer == "c": >>> print ("/n/nYay! I win. Shall we play again?\n\n") >>> os.system('cls' if os.name == 'nt' else 'clear') >>> >>> else: >>> print ("Invalid response. Please try again.\n") >>> >> >> Something else is wrong, besides the math: this is an infinite loop, because >> (answer == "h" or "l" or "c") always evaluates to True. >> >> And with the condition you probably wanted: >> >> while answer == "h" or answer == "l" or answer == "c": >> >> the loop wouldn't even start because you set answer = "" in the beginning. >> >> >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Fri Aug 15 19:12:49 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Aug 2014 18:12:49 +0100 Subject: [Tutor] Simple guessing game - need help with the math In-Reply-To: References: Message-ID: On 15/08/14 17:49, Derek Jenkins wrote: > I am a newbie (please correct me if I am wrong), but I happen to think > that it would be best to suggest that your input be in the same case > as that of your variables. In other words, it appears that you are > suggesting the user make an input choice of H, L, or C while the > program appears to want to handle the variables h, l, or c. >>>> answer = input("Is it (H)igher? (L)ower? Or am I (C)orrect? ") >>>> answer = answer.lower() You missed the lower() call in the line above. So that aspect at least is covered. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From terry.kemmerer at gmail.com Fri Aug 15 19:46:49 2014 From: terry.kemmerer at gmail.com (Terry--gmail) Date: Fri, 15 Aug 2014 11:46:49 -0600 Subject: [Tutor] Building Starships -- object of type 'int' has no len() Message-ID: <53EE4789.1060903@gmail.com> Python 3.3 This has something to do with the nature of FOR statements and IF statements, and I am sure it must be a simple mistake...but I seem to be stumped. I am writing a starship encounter program as my first real python program....where the user gets a random amount of credits to design his own ship and the computer also gets a random number of credits to spend and designs it's own ship, and then they go into combat against each other. This is part of the design phase for the user. The user has picked one category of the catalog, such as: Hulls, Drives, Shields, Weapons, Personnel, etc catalog and catalog2 are lists of lists: [[],[],[]] OK. So, my program has scanned the master catalog for a particular chosen category and has built catalog2 containing all the parts of that one category and their associated differences (rows), and now I want to print it out as a menu for the user to pick what part to add of this particular category to his ship. But first, so that I can pretty print the menu items and their associated capabilities to the screen in nice uniform columns, I need to know the maximum size of what is going to be printed in each column on the screen in advance, so I do the below learning scan through catagory2 and I build the simple list 'lens' to contain the max size of each column. As I run the program, this works perfectly for every NEW category the user picks, and the rows of associated data are printed just like I want.......*UNTIL the user chooses to buy a second part from a category he has already visited*, and at that point things error out. Below is the problem code and the error: lens = [] # pre-format the list called lens for maximum number of columns contained in catalog2 lens = [0] * len(catalog2[0]) # map the largest sizes of each column into list 'lens' col, line_number = 0, 0 for line_number in range(len(catalog2)): for col in range(len(catalog2[line_number])): *if lens[col] < len(catalog2[line_number][col]):* lens[col] = len(catalog2[line_number][col]) Traceback (most recent call last): File "encounter.py", line 379, in myship = designShip(credits, myship) File "encounter.py", line 354, in designShip hull, myship, credits, section = nicePrint(hull, credits, myship, catalog, section) File "encounter.py", line 199, in nicePrint if lens[col] < len(catalog2[line_number][col]): TypeError: *object of type 'int' has no len()* I don't get it. This code does the same job, again and again successfully as I proceed to pick new categories. Why would it care if I want to go over the same ground more than once??? It seems to me that the FOR STATEMENT automatically zeros the counters 'col' and line_number' when it starts counting, but why would it suddenly choke because of going over old territory??? In trying to debug i have checked catalog2 and it's data is present and intact. I added the line 'col, line_number = 0, 0' in the sequence of events although I don't see why it would be needed, and evidently it isn't needed because the problem persists. What's left to check? I really want to buy more guns and bombs and armor! But the program seems to be on the side of gun control!!! :) Thanks for your thoughts and suggestions! -------------- next part -------------- An HTML attachment was scrubbed... URL: From terry.kemmerer at gmail.com Fri Aug 15 21:21:17 2014 From: terry.kemmerer at gmail.com (Terry--gmail) Date: Fri, 15 Aug 2014 13:21:17 -0600 Subject: [Tutor] Building Starships -- object of type 'int' has no len() Message-ID: <53EE5DAD.9020206@gmail.com> Thanks for your response JL. I added the following Exception to the code snippet: for line_number in range(len(catalog2)): for col in range(len(catalog2[line_number])): try: if lens[col] < len(catalog2[line_number][col]): lens[col] = len(catalog2[line_number][col]) except TypeError: print(catalog2) print("col #: ", col) print("line_number", line_number) print("catalog2 col content: ", catalog2[line_number][col]) print("catalog2 col content TYPE: ", type(catalog2[line_number][col])) exit() Below is the exception printout. I ordered the catalog2 printout portion to be more readable: [['Drives', 'Type', 'Price', 'Max Speed', 'Energy Drain', 'Rq-Crew', '', '', ''], ['Drives', 'Solar Sail', 3, 1, 'None', 2, '', '', ''], <<------------------------here's the problem ['Drives', 'Bussard Ramjet', '10', '7', '2', '3', '', '', ''], ['Drives', 'Fusion', '70', '15', '5', '8', '', '', ''], ['Drives', 'Matter-Antimatter', '1500', '145', '15', '13', '', '', ''], ['Drives', 'Warp Drive', '2500', '250', '45', '17', '', '', '']] col #: 2 line_number 1 catalog2 col content: 3 catalog2 col content TYPE: Hmmm. It appears that when I bought a Solar Sail the first time through, my code has altered my master Catalog away from holding strings to holding integers for that particular row-record, which is why when I return to a particular category to make a second purchase, the code errors out when it hits the integers that are suppose to be strings. You know, for some reason, it just never sank into my thick skull that the integer 3 doesn't have a length. I just proved that to myself on the python commandline. It's just that my eyes see the number 3 displayed on the screen and my blond brain automatically counts it as occupying 1 space in the printout and thinks it's length is 1....which is why the texts say to use str() on integers and floats in mixed printouts, I guess. Thanks! I guess the above code is actually fine. Now, I just need to discover how and where I am somehow altering the master catalog where everything is suppose to be contained in strings. The problem with that is, I don't think there is any code to mess with the master catalog. I create catalog2 from scans of catalog each time another category is picked. And I store the chosen parts, after a quantity has been selected, in a list called myship. So, the problem must be where I do the quanity calculation, as that is done in integer form before the new row is added to myship. So, I will start there as I suspect I didn't switch it back to strings when I altered the catalog2 row, just before I appended it to myship. Thanks for putting me back on track! -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Fri Aug 15 21:22:34 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 15 Aug 2014 12:22:34 -0700 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53EE4789.1060903@gmail.com> References: <53EE4789.1060903@gmail.com> Message-ID: On Fri, Aug 15, 2014 at 10:46 AM, Terry--gmail wrote: (By the way - your indentation got flattened - cue the inevitable chorus of "DON'T POST TO THIS LIST IN HTML" - so this is my best-guess reconstruction.) > lens = [] > # pre-format the list called lens for maximum number of columns contained in > catalog2 > lens = [0] * len(catalog2[0]) > # map the largest sizes of each column into list 'lens' > col, line_number = 0, 0 > for line_number in range(len(catalog2)): > for col in range(len(catalog2[line_number])): > if lens[col] < len(catalog2[line_number][col]): > lens[col] = len(catalog2[line_number][col]) There are two separate issues here - the syntactic mistake that's giving you the error, and the non-Pythonic nature of "for col in range()" - let's deal with the first one. catalog2 is a list containing lines; line_number is a list containing integers. catalog2[line_number][col] is an integer; len(int) gives you a TypeError, as you've seen. I don't entirely understand what you're trying to do, so I can't tell you whether you want > if lens[col] < len(catalog2[line_number]): or > if lens[col] < catalog2[line_number][col]: but it's probably one or the other. Now, for the second issue - to take the length of a list and use that as the limit for a one-by-one crawl through the list is not the Python way. Rather than: > for line_number in range(len(catalog2)): use > for line_number, item in enumerate(catalog2): https://docs.python.org/3/tutorial/datastructures.html#looping-techniques From leamhall at gmail.com Fri Aug 15 21:38:47 2014 From: leamhall at gmail.com (leam hall) Date: Fri, 15 Aug 2014 15:38:47 -0400 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: References: <53EE4789.1060903@gmail.com> Message-ID: On a totally side note, I'm watching this because I want to do my own starship stuff. Long time Traveller player. -- Mind on a Mission From davea at davea.name Fri Aug 15 22:05:55 2014 From: davea at davea.name (Dave Angel) Date: Fri, 15 Aug 2014 16:05:55 -0400 (EDT) Subject: [Tutor] Building Starships -- object of type 'int' has no len() References: <53EE5DAD.9020206@gmail.com> Message-ID: Terry--gmail Wrote in message: > > Please don't post here in html mail. Tell your email program to use text. Your program fragment displayed here as a mess, which is one of many problems with html. Please use reply-list (or whatever your email supports, like reply-all and remove the extra recipients) when adding a message to a thread. By starting a new thread, you've robbed us of context. Now to your code, which I can't see because of the html message. Don't use bare except, unless that's throwaway code designed only to uncover the type mismatch. I couldn't see enough of your code to figure where you're messing up a type. But you should probably write a validation function to make sure all the fields are of expected types, and call it before and after the update to narrow down the culprit. -- DaveA From joseph.lee22590 at gmail.com Fri Aug 15 20:05:24 2014 From: joseph.lee22590 at gmail.com (Joseph Lee) Date: Fri, 15 Aug 2014 11:05:24 -0700 Subject: [Tutor] Building Starships -- object of type 'int' has no len() Message-ID: <53ee4c08.8839440a.30b0.688a@mx.google.com> Hi, My thoughts are in the message: ----- Original Message ----- From: Terry--gmail Hi Terry (if that's your name), Start slow - don't think ahead too much. It is a good thing that you know the end product, but sometimes when building a real-life system, you might want to work with one aspect of the program at a time (input, calculations, print, etc.) to make sure it works as advertised before moving onto other things. Also, I put print statements that prints "before and after" picture of a variable to make sure that I and the computer are in agreement as to what is what. Good luck. Cheers, Joseph (UC Riverside) ----- Original Message ----- From: Terry--gmail Greetings Python Community: I am new to Computer Programming with Python,having finished an 8 week Introductory Course. The Instructor used the Textbook:"Python Programming,3rd Edition (for the absolute beginner) by Michael Dawson;Cengage Learning, Course Technology Copyright 2010 ISBN-13: 978-1-4354-5500-9? ISBN-10: 1-4354-5500-2. The course only covered the Chapters 1-6 in the book. I have accomplished some reading of my own,Chapter 7 which I understood; but ran into stiff headwinds when I tried to read Ch.8,"Software Objects:The Critter Caretaker Program". I hope that some of you have the textbook or can look it up online,because I have many questions about the Text's treatment of Software Objects. (I'm scheduled to take a JavaScript class shortly and since that is object-oriented I really need to get this OOP down). Specifically,the Text on pages 222-232 I am finding the whole discussion on "Instantiating an Object","Methods","Constructors","Attributes-on page 226-228,Using Class Attributes and Static Methods(page 228-230;Creating A Class Attribute,Accessing a Class Attribute(Pg. 231);Using and Invoking a Static Method (pages 231-232) is all confusing to me and doesn't "congeal" or "come Together" in one coherent discussion. Forgive me if I seem dense;but this chapter has a lot of heavy reading in it! Please,somebody,explain the magic of Software Objects in Python to me ASAP. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Aug 17 10:55:12 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Aug 2014 09:55:12 +0100 Subject: [Tutor] Alert to all Experienced Python Software Object Oriented Programmers-Novice Needs Help In Understanding Textbook In-Reply-To: <1408244328.49645.YahooMailNeo@web124702.mail.ne1.yahoo.com> References: <1408244328.49645.YahooMailNeo@web124702.mail.ne1.yahoo.com> Message-ID: On 17/08/14 03:58, Stephen Mik wrote: > Introductory Course. The Instructor used the Textbook:"Python > Programming,3rd Edition (for the absolute beginner) by Michael > Dawson;... > ran into stiff headwinds when I tried to read Ch.8,"Software Objects > (I'm scheduled to take a JavaScript class shortly and since that > is object-oriented I really need to get this OOP down). Actually modern best practice in JavaScript does not use OOP so much as Functional Programming. And the OOP parts of JavaScript tend to be very different to the traditional style of OOP used in Python. So I wouldn't worry too much, you will have a new way of working to learn in JavaScript even if you master Python OOP, although at least the basic concepts will be familiar. > discussion on "Instantiating an Object","Methods","Constructors", That's pretty much most of OOP... Have you tried reading another OOP tutorial? Sometimes a different approach can help. You can try my OOP topic in my tutorial(see .sig) > "Attributes-on page 226-228,Using Class > Attributes and Static Methods(page 228-230;Creating A Class > Attribute,Accessing a Class Attribute(Pg. 231);Using and Invoking a > Static Method (pages 231-232) is all confusing to me Forget about this stuff until you have the basics down. class and static methods are quite advanced OOP topics. They won't make much sense until you understand classes, instances and instance methods. > Please,somebody,explain the magic of Software Objects in Python to me > ASAP. Thanks! Try the OOP topic in my tutorial and come back if you are still confused about the basics. The more specific the question the better the answers will be so try to explain what it is you don't understand. Include some code samples that you want to have explained for example. Also tell us which version of Python you use because some of the syntax for OOP changed significantly between Python v2 and Python v3. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From chigga101 at gmail.com Sun Aug 17 14:14:15 2014 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 17 Aug 2014 13:14:15 +0100 Subject: [Tutor] python ssl error Message-ID: Hi this might not be the correct place to ask this. I am using the google api and as soon as I use the build function: service = build('books', 'v1', developerKey=api_key) I get an SSL error. I'm not sure what build() does but it triggers an SSL error. Here's the error message: ssl.SSLError: [Errno 185090050] _ssl.c:357: error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib I googled this error but I don't understand the solution. It seems specific to httplib2: https://github.com/kennethreitz/requests/issues/557 Here is the full trace back. Any ideas? http://bpaste.net/show/isukkSeo08a0rx23ziBD/ From alan.gauld at btinternet.com Sun Aug 17 17:42:40 2014 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 17 Aug 2014 16:42:40 +0100 Subject: [Tutor] Alert to all Experienced Python Software Object Oriented Programmers-Novice Needs Help In Understanding Textbook In-Reply-To: References: <1408244328.49645.YahooMailNeo@web124702.mail.ne1.yahoo.com> Message-ID: <1408290160.92034.YahooMailNeo@web186005.mail.ir2.yahoo.com> Forwarding to the list, please use ReplyAll to?include the list. ? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos >________________________________ > From: diliup gabadamudalige >To: Alan Gauld >Sent: Sunday, 17 August 2014, 13:06 >Subject: Re: [Tutor] Alert to all Experienced Python Software Object Oriented Programmers-Novice Needs Help In Understanding Textbook > > > >below is a good article. > > > >http://www.voidspace.org.uk/python/articles/OOP.shtml > > > >below is another good one. > > >http://www.jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/?utm_source=Python+Weekly+Newsletter&utm_campaign=5a7c0c161f-Python_Weekly_Issue_145_June_26_2014&utm_medium=email&utm_term=0_9e26887fc5-5a7c0c161f-307214369 > > > > >On Sun, Aug 17, 2014 at 2:25 PM, Alan Gauld wrote: > >On 17/08/14 03:58, Stephen Mik wrote: >> >> >>Introductory Course. The Instructor used the Textbook:"Python >>>Programming,3rd Edition (for the absolute beginner) by Michael >>> Dawson;... >>> >>>ran into stiff headwinds when I tried to read Ch.8,"Software Objects >>> >> >>(I'm scheduled to take a JavaScript class shortly and since that >>> > is object-oriented I really need to get this OOP down). >> >> Actually modern best practice in JavaScript does not use OOP so much as Functional Programming. And the OOP parts of JavaScript tend to be very different to the traditional style of OOP used in Python. So I wouldn't worry too much, you will have a new way of working to learn in JavaScript even if you master Python OOP, although at least the basic concepts will be familiar. >> >> >> >>discussion on "Instantiating an Object","Methods","Constructors", >>> >> That's pretty much most of OOP... >>Have you tried reading another OOP tutorial? Sometimes a different approach can help. You can try my OOP topic in my tutorial(see .sig) >> >> >> >>"Attributes-on page 226-228,Using Class >>>Attributes and Static Methods(page 228-230;Creating A Class >>>Attribute,Accessing a Class Attribute(Pg. 231);Using and Invoking a >>>Static Method (pages 231-232) is all confusing to me >>> >> Forget about this stuff until you have the basics down. class and static methods are quite advanced OOP topics. They won't make much sense until you understand classes, instances and instance methods. >> >> >> >>Please,somebody,explain the magic of Software Objects in Python to me >>>ASAP. Thanks! >>> >> Try the OOP topic in my tutorial and come back if you are still confused about the basics. The more specific the question the better the answers will be so try to explain what it is you don't >>understand. Include some code samples that you want to have >>explained for example. >> >>Also tell us which version of Python you use because some of >>the syntax for OOP changed significantly between Python v2 >>and Python v3. >> >>-- >>Alan G >>Author of the Learn to Program web site >>http://www.alan-g.me.uk/ >>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 >> > > > >-- > >Diliup Gabadamudalige > >http://www.diliupg.com >http://soft.diliupg.com/ > >********************************************************************************************** >This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. >********************************************************************************************** > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From abidsaied at gmail.com Sun Aug 17 16:50:15 2014 From: abidsaied at gmail.com (abid saied) Date: Sun, 17 Aug 2014 15:50:15 +0100 Subject: [Tutor] Python = {0}.format Message-ID: <833D703F-19B2-48CB-9D1B-4CDABF45D154@gmail.com> Hi, I?m in the process of teaching myself python. Can someone have a look at the text in red and explain please. # String exercise 2 print("Quote Formatter") print("This program displays a given quote in different formats") print() # Why is this needed? quote = input("Please enter a quote to format: ") print(quote) print(quote.upper()) print(quote.lower()) print(quote.capitalize()) print(quote.title()) replaceWord = input("Which word in the quote would you like to replace: ") replaceWith = input("Please enter the word to replace with: ") print("The original quote is: {0}".format(quote)) print("The new quote is:{0}".format(quote.replace(replaceWord,replaceWith))) # Not sure what the {0}.format is doing Thanks. Abid -------------- next part -------------- An HTML attachment was scrubbed... URL: From sajjadul.islam.bd at gmail.com Sun Aug 17 15:11:14 2014 From: sajjadul.islam.bd at gmail.com (Sajjadul Islam) Date: Sun, 17 Aug 2014 19:11:14 +0600 Subject: [Tutor] print string Message-ID: Hello forum, I have started working with python 2.7.6 and i am trying to print the following string value: print("Same", "message", "as before") and i am supposed to get Same message as before. But i am getting the following : ("Same", "message", "as before") Any hint whats wrong? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Mon Aug 18 00:26:06 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 17 Aug 2014 15:26:06 -0700 Subject: [Tutor] python ssl error In-Reply-To: References: Message-ID: On Sun, Aug 17, 2014 at 5:14 AM, Matthew Ngaha wrote: > Hi this might not be the correct place to ask this. I am using the > google api and as soon as I use the build function: > > service = build('books', 'v1', developerKey=api_key) > > I get an SSL error. I'm not sure what build() does but it triggers an > SSL error. Here's the error message: > > ssl.SSLError: [Errno 185090050] _ssl.c:357: error:0B084002:x509 > certificate routines:X509_load_cert_crl_file:system lib Hi Matthew, Yeah, this is not quite Python-Tutor material. Check with the httplib2 folks: I think this in is their domain. Anyway, thanks for the detailed error message. It gives me something to search. I'll see if there's something reasonable here... ... ok, found something. According to: http://stackoverflow.com/questions/15696526/ssl-throwing-error-185090050-while-authentication-via-oauth the httplib2 library is having trouble accessing the certificate file. This appears a bug involved with the pip installer and root permissions: https://code.google.com/p/httplib2/issues/detail?id=292 In your case, since your httplib2 is installed in: /usr/lib/python2.7/site-packages/httplib2-0.9-py2.7.egg/httplib2/ I would recommend checking whether the 'cacerts.txt' file in that subdirectory is user-readable or not. Make sure it's readable. If it isn't, chmod it and try again: that will probably fix it. If you do a few more searches, you might run into two dubious recommendations: 1. Run as root. 2. Disable ssl certficiate validation. Both of these recommendations look potentially dangerous to me. Don't do either of these unless you really know what you're doing. At the very least, you might try #1 just to see if you see the same error message: if you do not see that error message when running as the superuser, then that almost certainly means that the cause is permission access to the cacerts.txt file. The fix, then, should be: correct the permission of that file. Try not to run programs as superuser if you can help it. From alan.gauld at btinternet.com Mon Aug 18 00:30:27 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Aug 2014 23:30:27 +0100 Subject: [Tutor] print string In-Reply-To: References: Message-ID: On 17/08/14 14:11, Sajjadul Islam wrote: > Hello forum, > > I have started working with python 2.7.6 and i am trying to print the > following string value: > > print("Same", "message", "as before") Looks like you are using a Python v3 tutorial on Python 2.7. The syntax of printing changed a lot in Python 3. The good news is that you can fake it in Python 2.7 by adding the line: from __future__ import print_function at the start of your session/program. Then you get Python3 style printing in 2.7. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From ben+python at benfinney.id.au Mon Aug 18 00:32:57 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 18 Aug 2014 08:32:57 +1000 Subject: [Tutor] Python = {0}.format References: <833D703F-19B2-48CB-9D1B-4CDABF45D154@gmail.com> Message-ID: <85vbpq4uhy.fsf@benfinney.id.au> abid saied writes: > I?m in the process of teaching myself python. Congratulations, and welcome. > Can someone have a look at the text in red and explain please. Text comes through as text. Don't rely on fonts, colours, or other non-text markup to survive. If you want to draw attention to some part of code, it is much better to reduce the example so it is minimal enough to show only what is relevant, while still exhibiting the behaviour you want to discuss. > print("The original quote is: {0}".format(quote)) > print("The new quote is:{0}".format(quote.replace(replaceWord,replaceWith))) > # Not sure what the {0}.format is doing Every value in Python is an object, with methods according to its type. A text string has many methods . The ?format? method of the ?str? type is used to generate formatted output from a template string. See and . -- \ ?I have yet to see any problem, however complicated, which, | `\ when you looked at it in the right way, did not become still | _o__) more complicated.? ?Paul Anderson | Ben Finney From ben+python at benfinney.id.au Mon Aug 18 00:34:35 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 18 Aug 2014 08:34:35 +1000 Subject: [Tutor] print string References: Message-ID: <85r40e4uf8.fsf@benfinney.id.au> Sajjadul Islam writes: > I have started working with python 2.7.6 In addition to the other responses: You should use Python 3 if at all possible. It is in active development and much more suitable for learning today. -- \ ?Ignorance more frequently begets confidence than does | `\ knowledge.? ?Charles Darwin, _The Descent of Man_, 1871 | _o__) | Ben Finney From alan.gauld at btinternet.com Mon Aug 18 00:41:43 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Aug 2014 23:41:43 +0100 Subject: [Tutor] Python = {0}.format In-Reply-To: <833D703F-19B2-48CB-9D1B-4CDABF45D154@gmail.com> References: <833D703F-19B2-48CB-9D1B-4CDABF45D154@gmail.com> Message-ID: On 17/08/14 15:50, abid saied wrote: > Hi, > > I?m in the process of teaching myself python. Can someone have a look at > the text in red and explain please. > print("This program displays a given quote in different formats") > print() # Why is this needed? Its not it only adds a bnlank line. You could achieve the same result by adding a \n character at the end of the last line. > quote = input("Please enter a quote to format: ") > print(quote) > replaceWord = input("Which word in the quote would you like to replace: ") > replaceWith = input("Please enter the word to replace with: ") > print("The original quote is: {0}".format(quote)) > # Not sure what the {0}.format is doing String formatting inserts data values into a string. Notice that the .format() occurs after the striong, not after the {} marker. The {} marks the place where the data will be inserted. The 0 indicates that its the zero'th (or first) item in the list that should be inserted. The list of data items is the list of parameters to format(). Here is an example: print ("{0} x {1} = {2}".format(3,4,12) And another showing the value of the indexing: s = "{0} can be written as {0} or {1}".format('four',4) print(s) You can have various other codes inside the {} to control spacing and justification or padding etc. Here is the official documentation page on the subject: https://docs.python.org/3/library/string.html#string-formatting HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Mon Aug 18 00:46:38 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 17 Aug 2014 15:46:38 -0700 Subject: [Tutor] Python = {0}.format In-Reply-To: <833D703F-19B2-48CB-9D1B-4CDABF45D154@gmail.com> References: <833D703F-19B2-48CB-9D1B-4CDABF45D154@gmail.com> Message-ID: > print("The original quote is: {0}".format(quote)) > print("The new quote is:{0}".format(quote.replace(replaceWord,replaceWith))) Hi Abid, You should be able to change this to the equivalent code: print("The original quote is: " + quote) print("The new quote is:" + quote.replace(replaceWord,replaceWith)) which does not use string formatting, but just plain string concatenation. I believe it should have the same meaning, since we know the things we're concatenating are strings. Python includes a mini "templating language" for having a strings with fill-me-ins, and letting you fill in the fill-me-ins later. In such a small example as the one above, I'd argue that templates are overkill. You'll note that the non-templated version is even shorter than the original code that uses templates. String templating makes a lot more sense outside of a toy context, when the output isn't a one-liner. If you have access to a good public library, find the classic book Jon Bentley's "Programming Pearls" and read Chapter 3 on Data Structures Programs: it discusses a rationale for "Form Letter Programming". From terry.kemmerer at gmail.com Mon Aug 18 01:48:57 2014 From: terry.kemmerer at gmail.com (Terry--gmail) Date: Sun, 17 Aug 2014 17:48:57 -0600 Subject: [Tutor] Building Starships -- object of type 'int' has no len() Message-ID: <53F13F69.2000406@gmail.com> WOW! There is a lot of help on this mailing list! I want to thank everyone for their valuable input! Thanks! (I am working my way through the replies.) Sorry about the HTML. I think I have it turned off now in Thunderbirdy for this address. If so, then what follows should not be flat. If it is flat, please tell me. The problem portion of the program now works, as I have corrected where my strings were getting converted to integers. However, if it is OK. I'd like to discuss and ask a few questions on a few things that have been brought up. Mark: You commented on the non-Pythonic nature of my program. HA HA HA! I don't doubt it! I am coming from a BASIC background based on line numbers and GOTO and GOSUB statements, and when I read this book on Python I am sure I understood it in terms of that old BASIC. Hence, my nested FOR statements have been laid out in layers as I did it in this Python program because that is how I envisioned those statements through BASIC eyes. BUT, they might also have looked something like: 30 FORX=1TOZ:FORC=1TOE::NEXTE:NEXTZ The fact is, I am VERY interested in acquiring that 'Pythonic' view you mention and I have encountered that term bandied about on the Internet, but have come away confused as to exactly what Pythonic Thinking really is! The writers seem to take it for granted I know. I don't. After all, the way I laid the code out in my program is actually functional. So, I am really curious about the benefit of a Pythonic Way, and what it looks and reads like... Is their a Pythonic Table anywhere on the Internet, where various possible coding methods in Python are contrasted to the real Pythonic Way? -So I can examine and study the contrasted structure to understand what the Pythonic Structure is accomplishing? (Maybe I am asking the wrong question here.) I must confess that I had, when first writing the code to discover the maximum size of each column for later print to screen, searched the Internet for a python statement or an import of some kind that I could simply hand my block of data to, and have it come back with the maximum sizes of the columns. (Yes. I'm an optimist! :) ). But, I did find the below piece of code which sounded like it was doing what I wanted, so I tested it and then integrated into my program: lens = [max(map(len, col)) for col in zip(*catalog2)] It worked great! So I kept it (as a thing of utter beauty) as I was awed by it. -until I started getting that syntactic error pointing to that line. The problem is, I didn't understand the commands within the above statement (max, map, zip, and the * usage) and how they were interactively accomplishing things (the statement was utterly over my head at this juncture), and when it came to debugging, after a few embedded print statements failed to tip me off to the problem and the bug persisted, I kept suspecting the statement......so I decided to replace the above code with something that was very familiar and understandable to me (albeit, not a thing of pythonic beauty): lens = [0] * len(catalog2[0]) for line_number in range(len(catalog2)): for col in range(len(catalog2[line_number])): if lens[col] < len(catalog2[line_number][col]): lens[col] = len(catalog2[line_number][col]) -And was surprised to discover the same bug persisted! The situation buffaloed me into thinking there was something about the language I was not comprehending in this section, when the actual problem, as we discovered, was elsewhere.....some of the string data had been converted to integers, and thus expecting a string instead of an integer, I got the Type Error. But I am now very curious to see how this same coding would be accomplished in a Pythonic Way, so, letting the statement you gave me redefine the entire flow of thought in that area of code-- catalog2 = [ ["Drives", "Type", "Price", "Max Speed", "Energy Drain", "Rq-Crew", "", "", ""], ["Drives", "Solar Sail", "3", "1", "None", "2", "", "", ""], ["Drives", "Bussard Ramjet", "10", "7", "2", "3", "", "", ""], ["Drives", "Fusion", "70", "15", "5", "8", "", "", ""], ["Drives", "Matter-Antimatter", "1500", "145", "15", "13", "", "", ""], ["Drives", "Warp Drive", "2500", "250", "45", "17", "", "", ""], ] We want to find the maximum size for each column-- lens = [0] * len(catalog2[0]) for line_number, row in enumerate(catalog2): for col, item in enumerate(row): if lens[col] < len(item): lens[col] = len(item) print(lens) [6, 17, 5, 9, 12, 7, 0, 0, 0] <<-----that is the correct answer. Did I do this correctly? Or, was there a way to compact it more? What have we gained? We have grabbed the entire row of data, and then looped through it without setting indexes when referring to the parts of each line...thus less clutter. Did we do this because there is less overhead generated as we sweep through the data? It is the same number of lines, BUT there is less typing in most of the lines. Do we anticipate an execution speed increase doing it this way also? Or have we altered the way we think to fit a Pythonic Way of structuring that will help us with other portions of the language??? (Does the pattern of it become more easily readable at a glance after we have gotten used to it?) Thanks! --Terry -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Mon Aug 18 02:17:35 2014 From: chigga101 at gmail.com (Matthew Ngaha) Date: Mon, 18 Aug 2014 01:17:35 +0100 Subject: [Tutor] python ssl error In-Reply-To: References: Message-ID: On Sun, Aug 17, 2014 at 11:26 PM, Danny Yoo wrote: > I would recommend checking whether the 'cacerts.txt' file in that > subdirectory is user-readable or not. Make sure it's readable. If it > isn't, chmod it and try again: that will probably fix it. > Thanks ever so much for your efforts! I'm glad to say your suggestion above fixed the problem. From alan.gauld at btinternet.com Mon Aug 18 02:41:54 2014 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 18 Aug 2014 01:41:54 +0100 Subject: [Tutor] Alert to all Experienced Python Software Object Oriented Programmers-Novice Needs Help In Understanding Textbook In-Reply-To: <1408318132.82552.YahooMailNeo@web124705.mail.ne1.yahoo.com> References: <1408244328.49645.YahooMailNeo@web124702.mail.ne1.yahoo.com> <1408318132.82552.YahooMailNeo@web124705.mail.ne1.yahoo.com> Message-ID: <1408322514.12551.YahooMailNeo@web186001.mail.ir2.yahoo.com> Forwarding to list, Use ReplyAll to respond to the list. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos > requirement to see hard copy of your material,which my printer seems to balk at Try the PDF version ofthe ?v2 tutor - I haven't got around to converting the v3 one yet!... Or you can open the link from the table of contents in a new tab and it should? print ok from there. > work with the Google Chrome browser because of its' Development Tools.? I completely understand that, I'd hate to develop Javascript in anything other? than Chrome nowadays. Its simply the best toolset for that job IMHO. Very similar to using the Python interactive prompt and IDLE debugger. > Alas,I tried to Download Chrome from a suggested Google site,but it would? > not be "docked".? Not sure why, it works for me on a Macbook Air. > At the Community College we used Python version 3.4.0 which I guess is up to date.? Yes indeed, the latest and greatest. Alan G From alan.gauld at btinternet.com Mon Aug 18 03:08:48 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 18 Aug 2014 02:08:48 +0100 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F13F69.2000406@gmail.com> References: <53F13F69.2000406@gmail.com> Message-ID: On 18/08/14 00:48, Terry--gmail wrote: > Sorry about the HTML. I think I have it turned off now in Thunderbirdy > for this address. If so, then what follows should not be flat. If it is > flat, please tell me. Still flat for me... Sorry. > The fact is, I am VERY interested in acquiring that 'Pythonic' view you > mention and I have encountered that term bandied about on the Internet, > but have come away confused as to exactly what Pythonic Thinking really > is! The writers seem to take it for granted I know. I don't. It just means using the "normal" Python idioms - and they are learned by reading other Python code. Gradually it permeats your brain and seems second nature. There are a few guidelines published but mostly its just local style. > But I am now very curious to see how this same coding would be > accomplished in a Pythonic Way, so, letting the statement you gave me > redefine the entire flow of thought in that area of code-- > > catalog2 = [ > ["Drives", "Type", "Price", "Max Speed", "Energy Drain", "Rq-Crew", "", > "", ""], > ["Drives", "Solar Sail", "3", "1", "None", "2", "", "", ""], > ["Drives", "Bussard Ramjet", "10", "7", "2", "3", "", "", ""], > ["Drives", "Fusion", "70", "15", "5", "8", "", "", ""], > ["Drives", "Matter-Antimatter", "1500", "145", "15", "13", "", "", ""], > ["Drives", "Warp Drive", "2500", "250", "45", "17", "", "", ""], > ] > > > We want to find the maximum size for each column-- > > lens = [0] * len(catalog2[0]) > > for line_number, row in enumerate(catalog2): > for col, item in enumerate(row): > if lens[col] < len(item): > lens[col] = len(item) You don't need the enumerate() for the first loop since you aren't using the index. for row in catalog2[1:]: # miss the header row for col,item in enumerate(row): if lens[col] < len(item): lens[col] = len(item) Another way to do it would be to store a list of lengths for each field then get the max of each list, like this: lens = [] * len(catalog2[0]) for row in catalog2[1:]: # miss the first row for col,item in row: lens[col].append(len(item)) lens = [max(col) for col in lens] I suspect the first one is quicker but without timing them I'm not sure. I'm also not sure which I'd consider most Pythonic... > Do we anticipate an execution speed increase doing it this way also? Sometimes, but its also usually more reliable - less chance of dropping off the end of a row or missing one out. > Or have we altered the way we think to fit a Pythonic Way of structuring > that will help us with other portions of the language??? yes a bit of that. More thinking about the intent - to process all items - than about the how of the implementation - counting indexes up to the length. > pattern of it become more easily readable at a glance after we have > gotten used to it?) That too, and also for other Python programmers. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From marc.tompkins at gmail.com Mon Aug 18 03:37:56 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 17 Aug 2014 18:37:56 -0700 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F13F69.2000406@gmail.com> References: <53F13F69.2000406@gmail.com> Message-ID: On Sun, Aug 17, 2014 at 4:48 PM, Terry--gmail wrote: > WOW! There is a lot of help on this mailing list! I want to thank everyone > for their valuable input! Thanks! (I am working my way through the > replies.) > > Sorry about the HTML. I think I have it turned off now in Thunderbirdy for > this address. If so, then what follows should not be flat. If it is flat, > please tell me. It's not only flat, but appears in a confusing array of sizes and styles - VERY SHOUTY bold 18-point for most of the text; 12.8 regular for code; 15.8 regular for the text that appears after the code. Hard to read the prose, never mind that it wiped out the indentation of your code. > > Mark: > > You commented on the non-Pythonic nature of my program. HA HA HA! I don't > doubt it! What I was getting at is a sort of feeling. Taking the length of a list, then using that length as the end value for range(), then counting up to the end of that range to step through the list... does it not feel like you've got unnecessarily far from the subject at hand? The Pythonic way would be to step through the list itself - or, if you must have a numeric index, to get it from enumerate()ing the list. As for a general theory of Pythonicity... it's a bit like all of those Zen koans where a novice monk asks the master "Does (x) have Buddha-nature?" (Not _quite_ as impossible to grasp as that, though!) From terry.kemmerer at gmail.com Mon Aug 18 06:40:29 2014 From: terry.kemmerer at gmail.com (Terry--gmail) Date: Sun, 17 Aug 2014 22:40:29 -0600 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: References: <53F13F69.2000406@gmail.com> Message-ID: <53F183BD.7070305@gmail.com> I found another place in Thunderbirdy to set 'plain text'. This is a test. Does the below code look correct now? --And did I reply correctly this time? (Reply-All and keep only tutor at python.org address...) for line_number, row in enumerate(catalog2): for col, item in enumerate(row): if lens[col] < len(item): lens[col] = len(item) From marc.tompkins at gmail.com Mon Aug 18 06:49:46 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 17 Aug 2014 21:49:46 -0700 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F183BD.7070305@gmail.com> References: <53F13F69.2000406@gmail.com> <53F183BD.7070305@gmail.com> Message-ID: On Sun, Aug 17, 2014 at 9:40 PM, Terry--gmail wrote: > I found another place in Thunderbirdy to set 'plain text'. > > This is a test. > > Does the below code look correct now? > > --And did I reply correctly this time? (Reply-All and keep only > tutor at python.org address...) > > > for line_number, row in enumerate(catalog2): > > for col, item in enumerate(row): > > if lens[col] < len(item): > > lens[col] = len(item) 1) It's plain text - no more funky font changes. 2) Addressing is good. 3) Indentation is still flat. Ah well. As Meat Loaf sang, two out of three ain't bad... From marc.tompkins at gmail.com Mon Aug 18 06:53:53 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 17 Aug 2014 21:53:53 -0700 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: References: <53F13F69.2000406@gmail.com> <53F183BD.7070305@gmail.com> Message-ID: On Sun, Aug 17, 2014 at 9:49 PM, Marc Tompkins wrote: > On Sun, Aug 17, 2014 at 9:40 PM, Terry--gmail wrote: >> I found another place in Thunderbirdy to set 'plain text'. >> >> This is a test. >> >> Does the below code look correct now? >> >> --And did I reply correctly this time? (Reply-All and keep only >> tutor at python.org address...) >> >> >> for line_number, row in enumerate(catalog2): >> >> for col, item in enumerate(row): >> >> if lens[col] < len(item): >> >> lens[col] = len(item) > > 1) It's plain text - no more funky font changes. > 2) Addressing is good. > 3) Indentation is still flat. It just occurred to me: how are you indenting? If you're using tabs, that would explain the problem (TBird might be helpfully converting tabs to newlines); in any case, the usual Python convention is to use four spaces for indentation (it's pretty easy to set your text editor to convert tabs to spaces on-the-fly, too.) If you're already using spaces, please disregard. From cs at zip.com.au Mon Aug 18 07:13:07 2014 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 18 Aug 2014 15:13:07 +1000 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F183BD.7070305@gmail.com> References: <53F183BD.7070305@gmail.com> Message-ID: <20140818051307.GA74796@cskk.homeip.net> On 17Aug2014 22:40, Terry--gmail wrote: >I found another place in Thunderbirdy to set 'plain text'. >This is a test. You message is plain text now. Thank you! >Does the below code look correct now? > >--And did I reply correctly this time? (Reply-All and keep only >tutor at python.org address...) Basicly, yes! This is sometimes a matter for debate. In personal email I always reply-all (I never use the reply-only-to-author button), and then (rarely) prune the To/CC list of unwanted recipients. On a mailing list it is always good to reply to the list unless you're departing wildly off topic. On some mailing lists it may be acceptable to CC the author (and possibly other individuals as they accrue in the to/cc lines). Many people would rather you replied only to the list (reply-all and prune, as you have done); that is always safe. Some people prefer or accept replies that go to the list and also to others; by naming them individually it can make the message more visible in their mailer, depending on their personal arrangements. For me, for example, a message which CCs me specificly gets filed to the "python" folder and also my main inbox, so I will notice it more immediately. As personal etiquette, these days I: reply-all, then remove everything except the list address unless there are already extra people in the To/CC. Some mail programs have a "list-reply" function; I don't think Thunderbird is one of them. >for line_number, row in enumerate(catalog2): > >for col, item in enumerate(row): > >if lens[col] < len(item): > >lens[col] = len(item) The above code has no indentation. Was it indented when you wrote it? Cheers, Cameron Simpson Having been erased, The document you're seeking Must now be retyped. - Haiku Error Messages http://www.salonmagazine.com/21st/chal/1998/02/10chal2.html From terry.kemmerer at gmail.com Mon Aug 18 07:51:57 2014 From: terry.kemmerer at gmail.com (Terry--gmail) Date: Sun, 17 Aug 2014 23:51:57 -0600 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: References: <53F13F69.2000406@gmail.com> <53F183BD.7070305@gmail.com> Message-ID: <53F1947D.2000602@gmail.com> I'm copy and pasting from Ninja-IDE, which I thought was created specifically to do python programming...so I never checked to see if it needs to have the tab set to enter 4 spaces, as it appeared visually to be doing that. But, I don't remember whether I used their tab or manually typed 4 spaces. SO, I have typed the lines below in manually: for line_number, row in enumerate(catalog2): for col, item in enumerate(row): if lens[col] < len(item): lens[col] = len(item) How's that? --Terry From kwpolska at gmail.com Mon Aug 18 08:31:49 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Mon, 18 Aug 2014 08:31:49 +0200 Subject: [Tutor] Alert to all Experienced Python Software Object Oriented Programmers-Novice Needs Help In Understanding Textbook In-Reply-To: <1408322514.12551.YahooMailNeo@web186001.mail.ir2.yahoo.com> References: <1408244328.49645.YahooMailNeo@web124702.mail.ne1.yahoo.com> <1408318132.82552.YahooMailNeo@web124705.mail.ne1.yahoo.com> <1408322514.12551.YahooMailNeo@web186001.mail.ir2.yahoo.com> Message-ID: On 18 August 2014 02:45 "ALAN GAULD" wrote: > > At the Community College we used Python version 3.4.0 which I guess is up to date. > > Yes indeed, the latest and greatest. The ?latest and greatest? is actually 3.4.1. -- Chris ?Kwpolska? Warrick Sent from my SGS3. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Aug 18 09:36:37 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 18 Aug 2014 00:36:37 -0700 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F1947D.2000602@gmail.com> References: <53F13F69.2000406@gmail.com> <53F183BD.7070305@gmail.com> <53F1947D.2000602@gmail.com> Message-ID: On Sun, Aug 17, 2014 at 10:51 PM, Terry--gmail wrote: > I'm copy and pasting from Ninja-IDE, which I thought was created > specifically to do python programming... Specifically for programming, yes, and Python is among the supported languages - but according to their web page, they support many languages (and in many other languages, whitespace is either not meaningful, or else you might actually want the Tab key to produce a tab character.) Anyway, I'm only guessing that the reason your indentation was disappearing was a tab/space issue; I don't actually know. > > for line_number, row in enumerate(catalog2): > for col, item in enumerate(row): > if lens[col] < len(item): > lens[col] = len(item) > > How's that? Perfect. From cs at zip.com.au Mon Aug 18 09:13:41 2014 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 18 Aug 2014 17:13:41 +1000 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F1947D.2000602@gmail.com> References: <53F1947D.2000602@gmail.com> Message-ID: <20140818071341.GA91999@cskk.homeip.net> On 17Aug2014 23:51, Terry--gmail wrote: >I'm copy and pasting from Ninja-IDE, which I thought was created >specifically to do python programming...so I never checked to see if >it needs to have the tab set to enter 4 spaces, as it appeared >visually to be doing that. But, I don't remember whether I used their >tab or manually typed 4 spaces. SO, I have typed the lines below in >manually: > >for line_number, row in enumerate(catalog2): > for col, item in enumerate(row): > if lens[col] < len(item): > lens[col] = len(item) > >How's that? All good except for the last line, which would normally be indented further than the "if". Cheers, Cameron Simpson This information is absolutely reliable; I read it on Usenet somewhere. - scott at festival.ed.ac.uk (Scott Larnach) From marc.tompkins at gmail.com Mon Aug 18 10:00:25 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 18 Aug 2014 01:00:25 -0700 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <20140818071341.GA91999@cskk.homeip.net> References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> Message-ID: On Mon, Aug 18, 2014 at 12:13 AM, Cameron Simpson wrote: > On 17Aug2014 23:51, Terry--gmail wrote: >> >> I'm copy and pasting from Ninja-IDE, which I thought was created >> specifically to do python programming...so I never checked to see if it >> needs to have the tab set to enter 4 spaces, as it appeared visually to be >> doing that. But, I don't remember whether I used their tab or manually >> typed 4 spaces. SO, I have typed the lines below in manually: >> >> for line_number, row in enumerate(catalog2): >> for col, item in enumerate(row): >> if lens[col] < len(item): >> lens[col] = len(item) >> >> How's that? > > > All good except for the last line, which would normally be indented further > than the "if". Poop. I missed that. Also, looking at the Ninja-IDE website more closely I see that, although they do mention compatibility with multiple languages, they were designed by and for Python programmers - which makes the tab/space issue less likely. I dunno. From cb2659 at att.com Mon Aug 18 17:23:42 2014 From: cb2659 at att.com (BALDWIN, CATHY L (Legal)) Date: Mon, 18 Aug 2014 15:23:42 +0000 Subject: [Tutor] Tutor Message-ID: <335ED5E12327274A86F051169E00ECC0019F43F8@MOKSCY3MSGUSRHD.ITServices.sbc.com> "I'm in Grand Prairie, TX and need a tutor. Someone I can meet with who can explain it to me like I'm 4 years old. Anybody out there up for the challenge. I will gladly pay you for your help. email me at home dacatm at aol.com" Cathy L. Baldwin Legal Assistant to: Ken Gitter, Mert Simons 208 S. Akard Floor 31 Dallas, TX 75202 214 757-3499 -------------- next part -------------- An HTML attachment was scrubbed... URL: From ch.de2.2309 at gmail.com Mon Aug 18 17:44:02 2014 From: ch.de2.2309 at gmail.com (Whees Northbee) Date: Mon, 18 Aug 2014 22:44:02 +0700 Subject: [Tutor] Error in get pixel value in coordinate (x, y) using getPixel(x, y) In-Reply-To: References: Message-ID: I'm so sorry for late reply, my laptop broken, the code actually I already put in thread before so I'll copy to here.. I don't know how to get pixel, I just searched and many link using 'getPixel' to get value of pixel.. I know color frame using 3 channel B G R to get pixel, but I just want to get pixel value in 1 channel, they said I need to use video in gray scale, and I already convert my video to gray scale Here's the code: cap =cv2.VideoCapture("c:\Users\Shiloh\Videos\AVI\MOV_5675.avi") width =cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH) height =cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT) NUM_SAMPLES =20 RADIUS =20 MIN_MATCHES =2 SUBSAMPLE_FACTOR =16 c_xoff= [-1, 0, 1, -1, 1, -1, 0, 1, 0] c_yoff= [-1, 0, 1, -1, 1, -1, 0, 1, 0] while(1): #Assign space and init m_samples=[] #height, width, depth=cap.shape c_black=np.zeros( (height,width), dtype=np.uint8) for i in range(0,NUM_SAMPLES,1): m_samples.append(c_black) m_mask=np.zeros( (width,height), dtype=np.uint8) m_foregroundMathCount=np.zeros( (width,height), dtype=np.uint8) # Capture frame-by-frame ret, frame = cap.read() #Init model from first frame for i in range(0,width,1): for j in range(0,height,1): for k in range(0,NUM_SAMPLES,1): random=np.random.randint(0,9) row=i+c_yoff[random] if(row<0): row=0 if(row>=width): row=width-1 col=j+c_xoff[random] if(col<0): col=0 if(col>=height): col=height-1 m_samples[k][i][j]=getPixel(frame,row,col) -------------- next part -------------- An HTML attachment was scrubbed... URL: From keithadu at live.com Mon Aug 18 21:18:07 2014 From: keithadu at live.com (keith papa) Date: Mon, 18 Aug 2014 15:18:07 -0400 Subject: [Tutor] how do I make my code better? Message-ID: Am a newbie and I decided to code a program that you input a round number and spit out the list of names or other information? how do I make this better? how do I make the code repeat itself, so I can keep asking the program to print out list of names for a variable? here my code: print 'Hello TheNetWork A' round1 = "First Round players: [Jamaal Charles RB KC], [LeSean McCoy RB PHI], [Calvin Johnson WR DET]" round2 = "Second round player: [Matt Forte RB CHI], [Eddie Lacy RB GB]," round3 = "Third Round players: [Peyton Manning QB DEN], [Jimmy Graham TE NO], [Demaryius Thomas WR DEN]" round4 = '[Dez Bryant WR DAL], [A.J. Green WR CIN],[ Brandon Marshall WR CHI], [Julio Jones WR ATL]' answer =raw_input('Enter round number here: \n')if answer == 'round1': print round1if answer == 'round2': print round2if answer == 'round3': print round3if answer == 'round4': print round4 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Aug 19 01:19:41 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Aug 2014 00:19:41 +0100 Subject: [Tutor] Tutor In-Reply-To: <335ED5E12327274A86F051169E00ECC0019F43F8@MOKSCY3MSGUSRHD.ITServices.sbc.com> References: <335ED5E12327274A86F051169E00ECC0019F43F8@MOKSCY3MSGUSRHD.ITServices.sbc.com> Message-ID: On 18/08/14 16:23, BALDWIN, CATHY L (Legal) wrote: > "I'm in Grand Prairie, TX and need > a tutor. Someone I can meet with who can explain it to me like I'm 4 > years old. Anybody out there up for the challenge. That's not really how the tutor list works. Instead, you try to learn the language (either by using a course, book, video or online tutorial) and when you get stuck or want feedback you send a mail here and whoever is available and interested will post a reply. Usually you will get several replies (and occasionally none). However somebody may be willing to meet you for 1-1 tutoring but its not the preferred way on this list. Not least because only you benefit whereas by doing it as described above everyone gets the chance to learn. There is a list of tutorials for absolute beginners here: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers Or you can try my tutorial, see below -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From ben+python at benfinney.id.au Tue Aug 19 01:27:55 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 19 Aug 2014 09:27:55 +1000 Subject: [Tutor] Tutor References: <335ED5E12327274A86F051169E00ECC0019F43F8@MOKSCY3MSGUSRHD.ITServices.sbc.com> Message-ID: <851tsd4bus.fsf@benfinney.id.au> "BALDWIN, CATHY L (Legal)" writes: > "I'm in Grand Prairie, TX and need a tutor. This forum is dedicated to tutoring people *here*, in the forum, in public. This is a great benefit because all participants (including you) can observe the discussions and learn from them. > Anybody out there up for the challenge. If you're up for the challenge: * Set up your mail client to post plain text messages only, so your code examples survive. * Ask a question, preferably showing some (very short and simple) code which you would like to understand better. * Participate in the ensuing discussion. * Ask more questions in new threads, and repeat :-) Welcome, and here's to learning a great language! -- \ ?Not to be absolutely certain is, I think, one of the essential | `\ things in rationality.? ?Bertrand Russell | _o__) | Ben Finney From dyoo at hashcollision.org Tue Aug 19 01:41:48 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 18 Aug 2014 16:41:48 -0700 Subject: [Tutor] how do I make my code better? In-Reply-To: References: Message-ID: Hello, Often, when you're writing code that looks roughly like: ####################### a_1 = ... a_2 = ... ... a_n = ... if ... a_1: ... if ... a_2: ... ... if ... a_n: ... ####################### then your program is crying out to use a table. The idea is to use a list to structure the pieces into a single, tabular thing, so that you can just point to an entry in the table to do something. >From a brief glance, as a first pass, your code can be transformed to: ########################################################## rounds = ["First Round players: [Jamaal Charles RB KC], [LeSean McCoy RB PHI], [Calvin Johnson WR DET]", "Second round player: [Matt Forte RB CHI], [Eddie Lacy RB GB]," "Third Round players: [Peyton Manning QB DEN], [Jimmy Graham TE NO], [Demaryius Thomas WR DEN]", "[Dez Bryant WR DAL], [A.J. Green WR CIN],[ Brandon Marshall WR CHI], [Julio Jones WR ATL]", ] answer = raw_input('Enter round number here: \n') print rounds[int(answer)-1] ########################################################## where the user now just enters a number, and that number is used to lookup in the "rounds". We use a list here to represent the table. There may be other ways to improve this. The entries in this table are strings: maybe it makes sense for them to have some more structure. Depends on if you have more plans to expand the program further. From alan.gauld at btinternet.com Tue Aug 19 02:55:35 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Aug 2014 01:55:35 +0100 Subject: [Tutor] how do I make my code better? In-Reply-To: References: Message-ID: On 18/08/14 20:18, keith papa wrote: > Am a newbie and I decided to code a program that you input a round > number and spit out the list of names or other information? how do I > make this better? how do I make the code repeat itself, so I can keep > asking the program to print out list of names for a variable? Have you come across the while loop? It looks like this: while : do stuff here So for your program it should look something like: while True: # loop forever answer = raw_input(.... if answer = 'quit': break # exits the loop elif answer = .... as before If while loops are new to you then you will find more info in the Loops topic of my tutorial (see .sig). HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From sunil.techspk at gmail.com Tue Aug 19 12:31:57 2014 From: sunil.techspk at gmail.com (Sunil Tech) Date: Tue, 19 Aug 2014 16:01:57 +0530 Subject: [Tutor] re module In-Reply-To: References: Message-ID: Hey thanks Danny Yoo, Chris ?Kwpolska? Warrick, D.V.N Sarma ?. I will take all your inputs. Thanks a lot.? On Fri, Aug 15, 2014 at 3:32 AM, Danny Yoo wrote: > On Thu, Aug 14, 2014 at 8:39 AM, D.V.N.Sarma ??.??.???.???? > wrote: > > I tested it on IDLE. It works. > > > Hi Sarma, > > > Following up on this one. I'm pretty sure that: > > print re.search(" > is going to print something, but it almost certainly will not do what > Sunil wants. See: > > https://docs.python.org/2/howto/regex.html#greedy-versus-non-greedy > > for why. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Tom_Roche at pobox.com Tue Aug 19 15:03:01 2014 From: Tom_Roche at pobox.com (Tom Roche) Date: Tue, 19 Aug 2014 09:03:01 -0400 Subject: [Tutor] howto create virtual environment for Enthought Training on Debian? Message-ID: <87a970zl6i.fsf@pobox.com> I'm running a 64-bit flavor of Debian (LMDE) with GNOME, which includes a system python and various python-using applets and applications. I have a long-standing interest in scientific software, but only recently acquired some spare time and an Enthought Training license. So I'd like to get setup to work the Enthought Training exercises, which apparently means installing Canopy (formerly EPD), possibly et al. However, the last time I tried to do something similar (2 years ago? installing EPD), using the provided installer, it whacked some system-python-dependent appss. I therefore want to install Canopy (and whatever else I need to do the Enthought Training that is not independently available via debian packages) into a virtual environment (so as not to cause problems with dependencies of my system python). How to do this? conda? venv? virtualenv? Unfortunately I'm not seeing any howto's on Enthought's site[1]. Please reply to me as well as the list: I'm on the digest, which gets huge. Alternatively, add your answer to this StackOverflow[2] (which I setup at Enthought's apparent recommendation[1]). TIA, Tom Roche [1]: https://support.enthought.com/home [2]: http://stackoverflow.com/questions/25375171/create-virtual-environment-for-enthought-training-on-debian From marc.tompkins at gmail.com Tue Aug 19 20:14:33 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 19 Aug 2014 11:14:33 -0700 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> Message-ID: On Mon, Aug 18, 2014 at 1:00 AM, Marc Tompkins wrote: > Also, looking at the Ninja-IDE website more closely I see that, > although they do mention compatibility with multiple languages, they > were designed by and for Python programmers - which makes the > tab/space issue less likely. I dunno. Update: I tried out NinjaIDE myself, and confirmed that copying four-space indented code from Ninja, then pasting it into a plain-text compose box in GMail results in flat code/extra newlines; I can only presume that it's much the same with TBird. The problem is definitely not (as I had thought) a space/tab problem; it has something to do with how Ninja (and GMail, and TBird) deals with the clipboard. I can copy from Ninja and paste into Notepad++; the indentation is preserved. If I then re-copy the same text from Notepad++ and paste it into the compose box, the indentation is preserved. But if I go straight from Ninja to compose - flat! From breamoreboy at yahoo.co.uk Tue Aug 19 22:04:05 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 19 Aug 2014 21:04:05 +0100 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> Message-ID: On 19/08/2014 19:14, Marc Tompkins wrote: > On Mon, Aug 18, 2014 at 1:00 AM, Marc Tompkins wrote: > >> Also, looking at the Ninja-IDE website more closely I see that, >> although they do mention compatibility with multiple languages, they >> were designed by and for Python programmers - which makes the >> tab/space issue less likely. I dunno. > > Update: I tried out NinjaIDE myself, and confirmed that copying > four-space indented code from Ninja, then pasting it into a plain-text > compose box in GMail results in flat code/extra newlines; I can only > presume that it's much the same with TBird. The problem is definitely > not (as I had thought) a space/tab problem; it has something to do > with how Ninja (and GMail, and TBird) deals with the clipboard. > I'm not aware of any problem with Thunderbird or any (semi-)decent mail client. Having said that I can't really comment on gmail but I do know that google groups screws up anything and everything that goes near it. That's why https://wiki.python.org/moin/GoogleGroupsPython exists. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From marc.tompkins at gmail.com Tue Aug 19 22:29:15 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 19 Aug 2014 13:29:15 -0700 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> Message-ID: On Tue, Aug 19, 2014 at 1:04 PM, Mark Lawrence wrote: > I'm not aware of any problem with Thunderbird or any (semi-)decent mail > client. The original poster uses NinjaIDE and Thunderbird, and his code was being persistently flattened when he copied/pasted. I believe I've just tracked it down to an incompatibility between the two (which also happens to extend to Ninja/Gmail.) I'm not sure how Google Groups enters into it. From cs at zip.com.au Wed Aug 20 00:34:43 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 20 Aug 2014 08:34:43 +1000 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: References: Message-ID: <20140819223443.GA11903@cskk.homeip.net> On 19Aug2014 13:29, Marc Tompkins wrote: >On Tue, Aug 19, 2014 at 1:04 PM, Mark Lawrence wrote: >> I'm not aware of any problem with Thunderbird or any (semi-)decent mail >> client. It may depend a great deal on the source program. >The original poster uses NinjaIDE and Thunderbird, and his code was >being persistently flattened when he copied/pasted. I believe I've >just tracked it down to an incompatibility between the two (which also >happens to extend to Ninja/Gmail.) I'm not sure how Google Groups >enters into it. Your experiment with Notepad suggests that it is pasting "rich" text that may be the issue. If you paste from the IDE into Notepad it works and then the text from Notepad pastes ok into the others. I am imagining that Notepad is plain fixed width text? Or just a better-handled formatting when handed to TBird or Gmail/GGroups? Debugging is not helped by the fact that for some things the GMail/GGroups HTML looks ok but the associated plain text version that they generate and send is usually awful. Cheers, Cameron Simpson A ridiculous place! Leaping from one bump to another, 187 corners or whatever it was! The number of times I've thanked God when I finished a lap there! It gave you amazing satisfaction, no doubt about it, but anyone who says he loved it is either a liar or wasn't going fast enough! - Jackie Stewart From terry.kemmerer at gmail.com Wed Aug 20 00:41:37 2014 From: terry.kemmerer at gmail.com (Terry--gmail) Date: Tue, 19 Aug 2014 16:41:37 -0600 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> Message-ID: <53F3D2A1.2040402@gmail.com> The down side of setting the python.org domain to be mailed to as plain text, appears to be that Thunderbirdy has changed all my email to plain text, instead of just the email going to this domain....which is weird. Leam Hall: I have just one additional function to create in the User Design section where the the user designs his own starship, to complete, before I move on to the Alien Design section where the computer semi-intelligently and randomly designs the unknown Alien ship we are going to meet out in interstellar space. That will be in 1 dimensional space to start with. You can either try to run away, charge right in and try to match relative direction and speed, or sweep in and fly right past the enemy blasting away at it. As the program gets worked out, I will alter for more dimensions....eventually, as I learn graphics. Right now, it is about the combat against an unknown enemy of unknown strength and capabilities. I figure it's a fun way to acquire pythonic skills and manage to remember all the commands possible. It's what I did when I first learned BASIC. So...it's going to be traditional with me... If you want, and if it doesn't violate any rules for this mailing list, I could post the User Design section for you to look over to see what my basic concepts are, just after I add and test this last section. Ultimately, I want this design section to be really easy to add additional capabilities to later and it is sort of written for the most part that way right now....although necessity also requires some custom filtering for different catagories of parts - like, you can only purchase one Hull for your ship! ( :) I probably wouldn't try to learn my techniques though....my python skills and vocabulary are a real work in progress and I read so much that I am forgetting what I have read. And I have no doubt I have probably broken pythonic rules and slaughtered proper methodology to high heaven in the layout and implementation. Ha Ha Ha) But this section does work....at least until I discover a bug in some untested possible combination of choices. The way I broke it was by adding additional functions. Just let me know if you want me to post it for you to look over. DaveA: The bare 'except' was a throw away. By bare 'except' I am assuming you mean without defining the type of error 'except' is to act upon? try: something except ValueError: do something -Or does bare 'except' mean something else? Alan Guald: I have been trying out the different ways you suggested for doing this, and have ran into a problem on making the very last one work. I stuck a print statement in it to help, but I am not sure what the error statement is telling me: for row in catalog2: print(row) for col, item in row: lens[col].append(len(item)) lens = [max(col) for col in lens] and I get the following error in 'for col, item in row:' 'ValueError: too many values to unpack (expected 2)': I don't see why it would possibly say there are too many values to unpack or why it would expect only 2! Also, the list comprehension you have used on the final line reminds me that I would really like to understand comprehensions better. Is there some info on the Internet that starts very basic concerning comprehensions and explains step by step in complexity how they are structured and what the computer is doing? Just looking at the code setting there inside the list brackets and know what the output is going to be, reminds me of a programmed cell of a spreadsheet....kind of. Mark Tompkins: "Does (x) have Buddha-nature?" In college, in a Psychology of Communications class, I spent a lot of time studying, writing about, and contemplating "The Is-ness of IS!" Does that count? I hand typed all of the above code in, except the error portion. This is pasted from Ninja-IDE and it comes out in smaller letters and is impossible to make larger... for row in catalog2: for col, item in row: lens[col].append(len(item)) lens = [max(col) for col in lens] Mark Lawrence gave me the idea to copy from Ninja-IDE to gedit and then copied it from gedit here: (actually I saved it in gedit and then re-grabbed it with gedit ) for row in catalog2: print(row) for col, item in row: lens[col].append(len(item)) lens = [max(col) for col in lens] Boy! It looks far better on my page than the straight Ninja-ide paste above! And it is now manipulatable, I can enlarge and shrink it...whereas, the Ninja paste resists things like trying to delete the extra lines of white space below it and I have even saw it collapse to flat right before my eyes! So, I guess the best route is to paste from Ninja to gedit and then to my email....assuming this is good on your end. On 08/19/2014 02:29 PM, Marc Tompkins wrote: > On Tue, Aug 19, 2014 at 1:04 PM, Mark Lawrence wrote: >> I'm not aware of any problem with Thunderbird or any (semi-)decent mail >> client. > The original poster uses NinjaIDE and Thunderbird, and his code was > being persistently flattened when he copied/pasted. I believe I've > just tracked it down to an incompatibility between the two (which also > happens to extend to Ninja/Gmail.) I'm not sure how Google Groups > enters into it. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From cs at zip.com.au Wed Aug 20 01:26:36 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 20 Aug 2014 09:26:36 +1000 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F3D2A1.2040402@gmail.com> References: <53F3D2A1.2040402@gmail.com> Message-ID: <20140819232636.GA90095@cskk.homeip.net> On 19Aug2014 16:41, Terry--gmail wrote: >The bare 'except' was a throw away. By bare 'except' I am assuming you mean without defining the type of error 'except' is to act upon? > >try: > something >except ValueError: > do something > >-Or does bare 'except' mean something else? You're right, it means "except" with no exception type. The trouble with bare excepts is that they catch every exception, not just the one you expected to get. For example, this code: x = 1 y = 2 z = xx + y would raise a NameError because "xx" is unknown. To my mind and yours it is just a typo, but in a dynamic language like Python this is only detected at runtime. If that code were inside a bare try/except then you might spent a very long time figuring out what was wrong because you're expecting one kind of failure be getting another. As general practice, the rule of thumb is that you should make "except"s as precise as possible and only handle errors you explicitly expect and know what to do with. An example from some of my code: try: arfp = open(arpath) except OSError as e: if e.errno == errno.ENOENT: arfp = None else: raise Here I'm catching the expected possibility that the file I'm opening does not exist and setting arfp to None. Any other type of problem (permission denied, etc) continues on to raise an exception. While this makes you code fragile in one sense, it prevents it _silently_ misinterpreting one thing as another, and that is usually best. Cheers, Cameron Simpson The aim of AI is to make computers act like the ones in the movies. - Graham Mann From cs at zip.com.au Wed Aug 20 01:29:28 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 20 Aug 2014 09:29:28 +1000 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F3D2A1.2040402@gmail.com> References: <53F3D2A1.2040402@gmail.com> Message-ID: <20140819232928.GA3112@cskk.homeip.net> On 19Aug2014 16:41, Terry--gmail wrote: >Alan Guald: > >I have been trying out the different ways you suggested for doing >this, and have ran into a problem on making the very last one work. I >stuck a print statement in it to help, but I am not sure what the >error statement is telling me: > >for row in catalog2: > print(row) > for col, item in row: > lens[col].append(len(item)) >lens = [max(col) for col in lens] > >and I get the following error in 'for col, item in row:' > > 'ValueError: too many values to unpack (expected 2)': > >I don't see why it would possibly say there are too many values to >unpack or why it would expect only 2! Your for-loop says: for col, item in row: That iterates over each element in "row" and attempts to unpack it into the two variables "col" and "item". Presumably the row element has more than two items in it. We'd need to see to say. Try this: for element in row: print(element) col, item = element lens[col].append(len(item)) and see what you get. Cheers, Cameron Simpson Archiving the net is like washing toilet paper! - Leader Kibo From cs at zip.com.au Wed Aug 20 01:33:42 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 20 Aug 2014 09:33:42 +1000 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F3D2A1.2040402@gmail.com> References: <53F3D2A1.2040402@gmail.com> Message-ID: <20140819233342.GA8044@cskk.homeip.net> On 19Aug2014 16:41, Terry--gmail wrote: >Alan Guald: [...] >lens = [max(col) for col in lens] [...] >Also, the list comprehension you have used on the final line reminds >me that I would really like to understand comprehensions better. Is >there some info on the Internet that starts very basic concerning >comprehensions and explains step by step in complexity how they are >structured and what the computer is doing? The line above is essentially equivalent to this: lens_orig = lens lens = [] for col in lens_orig: lens.append(max(col)) It just assembles a list of values, each being max(col), for each element in lens. The mucking with "lens" and "lens_orig" above is only because you're replacing "lens" with the new list. >Just looking at the code setting there inside the list brackets and >know what the output is going to be, reminds me of a programmed cell >of a spreadsheet....kind of. It is very like that, if you consider two spreadsheet columns, the first with the original values in "lens" and the second having "max(col)" for each. Cheers, Cameron Simpson ERROR 155 - You can't do that. - Data General S200 Fortran error code list From alan.gauld at btinternet.com Wed Aug 20 02:09:23 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 20 Aug 2014 01:09:23 +0100 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F3D2A1.2040402@gmail.com> References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> <53F3D2A1.2040402@gmail.com> Message-ID: On 19/08/14 23:41, Terry--gmail wrote: > Alan Guald: > > > for row in catalog2: > print(row) > for col, item in row: > lens[col].append(len(item)) My bad, it should have been for col, item in enumerate(row): Sorry, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Aug 20 02:13:46 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 20 Aug 2014 01:13:46 +0100 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F3D2A1.2040402@gmail.com> References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> <53F3D2A1.2040402@gmail.com> Message-ID: On 19/08/14 23:41, Terry--gmail wrote: > Also, the list comprehension you have used on the final line reminds me > that I would really like to understand comprehensions better. Is there > some info on the Internet that starts very basic concerning > comprehensions and explains step by step in complexity how they are > structured and what the computer is doing? You can try the Functional Programming topic in my tutorial. Comprehensions start roughly half way down. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From diliupg at gmail.com Wed Aug 20 08:23:28 2014 From: diliupg at gmail.com (diliup gabadamudalige) Date: Wed, 20 Aug 2014 11:53:28 +0530 Subject: [Tutor] (no subject) Message-ID: Hi all! Is there any way I can bundle all my graphics only using Python and Pygame so that the user may not be able to read them out of the program? Let us assume that the user does NOT know Python and will not go looking for people who knows Python to crack the files. In other words an average user. 1. I have tried the Zip file method by making a Zip file with Win Rar or Winzip and password lock the file. But the unpacking is WAY TOO SLOW! with ZipFile('stuff.zip') as zf: zf.extract("image.jpg", pwd="123456") 2. I have used the repr command and written the code to a py file but again the unpacking is WAY TOO SLOW. with open(name4pypath,"wb") as outfile: outfile.write(name4pyfile + "=" + repr(str1)) 3. The best out of the lot has been the one using base64 str1 = base64.b64encode(from_disk.read()) with open(code_to_dir, "ab+") as to_disk: to_disk.write(str1) Can anyone show me a better way? Thanks in advance -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ********************************************************************************************** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ********************************************************************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Wed Aug 20 09:32:29 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 20 Aug 2014 00:32:29 -0700 Subject: [Tutor] Embedding resources Message-ID: On Aug 19, 2014 11:53 PM, "diliup gabadamudalige" wrote: > > Hi all! > > Is there any way I can bundle all my graphics only using Python and Pygame so that the user may not be able to read them out of the program? (Changing subject line to more descriptive title) Would something like http://www.pygame.org/pcr/image2py/index.php apply to your problem? -------------- next part -------------- An HTML attachment was scrubbed... URL: From abidsaied at gmail.com Wed Aug 20 13:00:25 2014 From: abidsaied at gmail.com (abid saied) Date: Wed, 20 Aug 2014 12:00:25 +0100 Subject: [Tutor] How to end this program Message-ID: <34C27E96-F0A4-4956-8CC4-F79B6C1E7671@gmail.com> # OK, I'm stuck on setting up an instruction that ends the program once you # say either 'yes' or 'no'. And if you don't say 'yes' or 'no', and you reach # the end, the program comes to an end. Please remember I'm a newbie and would # appreciate any advise in plain simple English, like I was 5 years old! import time def main(): print() print("YES/NO Game ") time.sleep(2) print() print() print("In this game, I will ask you a series of questions, if you answer YES or NO, you loose!") print() print("Remember to answer in Capitals!") print() time.sleep(2) print("Starting the game ...") print() time.sleep(2) name = input("What is your name? ") print() time.sleep(2) print("ok " + (name) + (", time for the questions...")) print() time.sleep(2) answer = input("How old are you? ") if answer == "YES": print("...You said yes, you loose!") elif answer == "NO": print ("...You said NO, you loose!") answer = input("Do you like apples? ") if answer == "YES": print("...You said yes, you loose!") elif answer == "NO": print ("...You said NO, you loose!") answer = input("Do you enjoy music? ") if answer == "YES": print("...You said yes, you loose!") elif answer == "NO": print ("...You said NO, you loose!") answer = input("Have you ever been on a train? ") if answer == "YES": print("...You said yes, you loose!") elif answer == "NO": print ("...You said NO, you loose!") answer = input("Do you watch 'Home and Away'? ") if answer == "YES": print("...You said yes, you loose!") elif answer == "NO": print ("...You said NO, you loose!") answer = input("What is 50/5? ") if answer == "YES": print("...You said yes, you loose!") elif answer == "NO": print ("...You said NO, you loose!") answer = input("Can a duck fly? ") if answer == "YES": print("...You said yes, you loose!") elif answer == "NO": print ("...You said NO, you loose!") answer = input("Can you drive a car? ") if answer == "YES": print("...You said yes, you loose!") elif answer == "NO": print ("...You said NO, you loose!") answer = input("Do you still watch cartoons? ") if answer == "YES": print("...You said yes, you loose!") elif answer == "NO": print ("...You said NO, you loose!") answer = input("Can a duck fly? ") if answer == "YES": print("...You said yes, you loose!") elif answer == "NO": print ("...You said NO, you loose!") print("OK, you win!You didn't say 'YES' or 'NO', well done!") time.sleep(2) Abid Saied abidsaied at gmail.com From dexternet89 at mail.ru Wed Aug 20 14:35:03 2014 From: dexternet89 at mail.ru (=?UTF-8?B?RGltYSBLdWxpaw==?=) Date: Wed, 20 Aug 2014 16:35:03 +0400 Subject: [Tutor] =?utf-8?q?Parsing_txt_file?= Message-ID: <1408538103.932889670@f414.i.mail.ru> Hi to all. I have a problem with parsing file. I have txt file exported from AD and it has such structure: DistinguishedName : CN=*** ,OU=*** ,OU=*** ,DC=*** ,DC=***,DC=*** GroupCategory???? : Distribution GroupScope??????? : Universal Name????????????? : **** ObjectClass?????? : group ObjectGUID??????? : 0b74b4e2-aad1-4342-a8f4-2fa7763e1d49 SamAccountName??? : **** SID?????????????? : S-1-5-21-1801674531-492894223-839522115-16421 i need to export to file all stings which start from "Name" I've tried to make little parser: keywords = ['Name', 'Name:'] input_file=open("Mail_Groups.txt","r").readlines() output_file=open("Out.txt","w") for line in input_file: ??? for word in line.split(): ??????? if word in keywords: ??????????? output_file.write(line) but the output is clear. What the problem is? Can some one help me? -- Dima Kulik -------------- next part -------------- An HTML attachment was scrubbed... URL: From diliupg at gmail.com Wed Aug 20 15:45:41 2014 From: diliupg at gmail.com (diliup gabadamudalige) Date: Wed, 20 Aug 2014 19:15:41 +0530 Subject: [Tutor] Fwd: Embedding resources In-Reply-To: References: Message-ID: Hi Danny! The routine works fine and so does this one. http://www.pygame.org/pcr/zipshow/index.php The only problem with all these are that that the time taken to read these files and to either make a list or send to screen is WAY TOO LONG. The only one that works without much delay is in the file I have attached. It is a bit of code that I wrote with verbose print statements to follow the program in action while testing. As this uses base64 only there is no secure encryption. Please have a look at it and try to improve it. Am I doing this correctly? Are these messages getting to the community? On Wed, Aug 20, 2014 at 1:18 PM, diliup gabadamudalige wrote: > Hi Danny! > > You are always there to lend a helping hand I've noticed! Thanks for the > quick response! Let me try the code and get back to you. > > > > On Wed, Aug 20, 2014 at 1:02 PM, Danny Yoo wrote: > >> >> On Aug 19, 2014 11:53 PM, "diliup gabadamudalige" >> wrote: >> > >> > Hi all! >> > >> > Is there any way I can bundle all my graphics only using Python and >> Pygame so that the user may not be able to read them out of the program? >> >> (Changing subject line to more descriptive title) >> >> Would something like http://www.pygame.org/pcr/image2py/index.php apply >> to your problem? >> > > > > -- > Diliup Gabadamudalige > > http://www.diliupg.com > http://soft.diliupg.com/ > > > ********************************************************************************************** > This e-mail is confidential. It may also be legally privileged. If you are > not the intended recipient or have received it in error, please delete it > and all copies from your system and notify the sender immediately by return > e-mail. Any unauthorized reading, reproducing, printing or further > dissemination of this e-mail or its contents is strictly prohibited and may > be unlawful. Internet communications cannot be guaranteed to be timely, > secure, error or virus-free. The sender does not accept liability for any > errors or omissions. > > ********************************************************************************************** > > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ********************************************************************************************** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ********************************************************************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- """ Author: Diliup Gabadamudalige. diliupg at gmail.com> Copyright: If you wish to use this code please keep this multiline comment, along with function source. Thank you. read the files in the current directory and get all files except ones in the exempt list or directories.. Get the file extension. and convert them by using maketrans without file extensions. When converting from original files with file extensions, remove the file extension(with the .), reverse it and add it to the begining of the filename. encode the file. add new file ext "@lm". eg: file name -> picture.tiff -> ffit.picture ->AFKDiO$1#&mL at lm. encoded files added to a directory "coded" which is created if not exist. decoded files added to a directory "decoded" which is created if not exist. path = your path where the files are run = True -> encode run = False -> decode """ import os import string import base64 from master_vars import alpha, coder def main(path, code = None, ex = [".wpr", ".wpu", ".py", ".pyc", ". at lm"]): getfiles = [] path = path code = code # exclude = ex items = os.listdir(path) if code: # if code = True then encode mode = "encode" if not os.path.exists("coded"): os.makedirs("coded") else: # else decode mode = "decode" ## if decode mode and coded folder does not exist exit program if not os.path.exists("coded"): print "nothing to decode." elif not os.path.exists("decoded") and os.path.exists("coded"): os.makedirs("decoded") elif os.path.exists("decoded"): items = os.listdir(path + "\\" + "coded") ## get the names of the files in the path which are not in the exclude list ## encode or decode either way this works correct for n in items: if code: fpath = path + "\\" + n if os.path.isfile(fpath): # check if file is not a directory if n[n.index("."):] not in exclude: getfiles.append(n) else: fpath = path + "\\coded\\" + n if n.endswith(". at lm"): # get only the converted files getfiles.append(n) print "file names to process:", getfiles print for f in getfiles: if code: ## decode and reverse file name namea = f.translate(string.maketrans(alpha,coder)) nameb = namea[::-1] + ". at lm" code_to_dir = path + "\\coded\\" + nameb read_file = path + "\\" + f else: ## drop the file ext. decode and reverse namea = f[:-4].translate(string.maketrans(coder, alpha)) ## file name + reversed nameb = namea [::-1] decode_to_dir = path + "\\decoded\\" + nameb read_file = path + "\\coded\\" + f print "new file name not invert no ext:", namea print "new file name:", nameb print "old file name:", f print with open(read_file , "rb") as from_disk: if code: str1 = base64.b64encode(from_disk.read()) with open(code_to_dir, "wb") as to_disk: to_disk.write(str1) else: str1 = base64.b64decode(from_disk.read()) with open(decode_to_dir, "wb") as to_disk: to_disk.write(str1) print mode + "ed ", len(getfiles), " files." if __name__=='__main__': path = "d:\PYTHON\diliupg\SoftwareDG\Educational\Learn_music\encode_decode" # if path not supplied use the current working directory if not path: path = os.getcwd() code = True main(path, code) From joel.goldstick at gmail.com Wed Aug 20 20:34:53 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 20 Aug 2014 14:34:53 -0400 Subject: [Tutor] How to end this program In-Reply-To: <34C27E96-F0A4-4956-8CC4-F79B6C1E7671@gmail.com> References: <34C27E96-F0A4-4956-8CC4-F79B6C1E7671@gmail.com> Message-ID: On Wed, Aug 20, 2014 at 7:00 AM, abid saied wrote: > > # OK, I'm stuck on setting up an instruction that ends the program once you > # say either 'yes' or 'no'. And if you don't say 'yes' or 'no', and you reach > # the end, the program comes to an end. Please remember I'm a newbie and would > # appreciate any advise in plain simple English, like I was 5 years old! > > > > import time > > def main(): > print() > print("YES/NO Game ") > time.sleep(2) > print() > print() > > print("In this game, I will ask you a series of questions, if you answer YES or NO, you loose!") > print() > print("Remember to answer in Capitals!") > print() > time.sleep(2) > print("Starting the game ...") > print() > time.sleep(2) > name = input("What is your name? ") > print() > time.sleep(2) > print("ok " + (name) + (", time for the questions...")) > print() > time.sleep(2) > > > answer = input("How old are you? ") > if answer == "YES": > print("...You said yes, you loose!") > elif answer == "NO": > print ("...You said NO, you loose!") > > > answer = input("Do you like apples? ") > if answer == "YES": > print("...You said yes, you loose!") > elif answer == "NO": > print ("...You said NO, you loose!") > You repeat this pattern throughout your program, so it should be made a function like this: def ask_question(question): answer = input(question) answer = answer.upper() if answer == "YES" or answer == "NO": print "...You said %s, you loose!", answer exit(0) # this will end the program return # this will get you out of your function To ask all of your questions, create a list of questions like this: list_of_questions = ["first question", "second question", etc ... ] Now do this: for question in list_of_questions: ask_question then finish with what you have below. > > print("OK, you win!You didn't say 'YES' or 'NO', well done!") > time.sleep(2) > > > > > Abid Saied > abidsaied at gmail.com > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com From joel.goldstick at gmail.com Wed Aug 20 20:40:31 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 20 Aug 2014 14:40:31 -0400 Subject: [Tutor] How to end this program In-Reply-To: References: <34C27E96-F0A4-4956-8CC4-F79B6C1E7671@gmail.com> Message-ID: On Wed, Aug 20, 2014 at 2:34 PM, Joel Goldstick wrote: > On Wed, Aug 20, 2014 at 7:00 AM, abid saied wrote: >> >> # OK, I'm stuck on setting up an instruction that ends the program once you >> # say either 'yes' or 'no'. And if you don't say 'yes' or 'no', and you reach >> # the end, the program comes to an end. Please remember I'm a newbie and would >> # appreciate any advise in plain simple English, like I was 5 years old! >> >> >> >> import time >> >> def main(): >> print() >> print("YES/NO Game ") >> time.sleep(2) >> print() >> print() >> >> print("In this game, I will ask you a series of questions, if you answer YES or NO, you loose!") >> print() >> print("Remember to answer in Capitals!") >> print() >> time.sleep(2) >> print("Starting the game ...") >> print() >> time.sleep(2) >> name = input("What is your name? ") >> print() >> time.sleep(2) >> print("ok " + (name) + (", time for the questions...")) >> print() >> time.sleep(2) >> >> >> answer = input("How old are you? ") >> if answer == "YES": >> print("...You said yes, you loose!") >> elif answer == "NO": >> print ("...You said NO, you loose!") >> >> >> answer = input("Do you like apples? ") >> if answer == "YES": >> print("...You said yes, you loose!") >> elif answer == "NO": >> print ("...You said NO, you loose!") >> > You repeat this pattern throughout your program, so it should be made > a function like this: > > def ask_question(question): > answer = input(question) > answer = answer.upper() > if answer == "YES" or answer == "NO": > print "...You said %s, you loose!", answer > exit(0) # this will end the program > return # this will get you out of your function > > > To ask all of your questions, create a list of questions like this: > > list_of_questions = ["first question", "second question", etc ... ] > > Now do this: > for question in list_of_questions: > ask_question() > > > then finish with what you have below. > > >> >> print("OK, you win!You didn't say 'YES' or 'NO', well done!") >> time.sleep(2) >> >> >> >> >> Abid Saied >> abidsaied at gmail.com >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor > > > > -- > Joel Goldstick > http://joelgoldstick.com -- Joel Goldstick http://joelgoldstick.com From joel.goldstick at gmail.com Wed Aug 20 20:41:23 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 20 Aug 2014 14:41:23 -0400 Subject: [Tutor] How to end this program In-Reply-To: References: <34C27E96-F0A4-4956-8CC4-F79B6C1E7671@gmail.com> Message-ID: On Wed, Aug 20, 2014 at 2:40 PM, Joel Goldstick wrote: > On Wed, Aug 20, 2014 at 2:34 PM, Joel Goldstick > wrote: >> On Wed, Aug 20, 2014 at 7:00 AM, abid saied wrote: >>> >>> # OK, I'm stuck on setting up an instruction that ends the program once you >>> # say either 'yes' or 'no'. And if you don't say 'yes' or 'no', and you reach >>> # the end, the program comes to an end. Please remember I'm a newbie and would >>> # appreciate any advise in plain simple English, like I was 5 years old! >>> >>> >>> >>> import time >>> >>> def main(): >>> print() >>> print("YES/NO Game ") >>> time.sleep(2) >>> print() >>> print() >>> >>> print("In this game, I will ask you a series of questions, if you answer YES or NO, you loose!") >>> print() >>> print("Remember to answer in Capitals!") >>> print() >>> time.sleep(2) >>> print("Starting the game ...") >>> print() >>> time.sleep(2) >>> name = input("What is your name? ") >>> print() >>> time.sleep(2) >>> print("ok " + (name) + (", time for the questions...")) >>> print() >>> time.sleep(2) >>> >>> >>> answer = input("How old are you? ") >>> if answer == "YES": >>> print("...You said yes, you loose!") >>> elif answer == "NO": >>> print ("...You said NO, you loose!") >>> >>> >>> answer = input("Do you like apples? ") >>> if answer == "YES": >>> print("...You said yes, you loose!") >>> elif answer == "NO": >>> print ("...You said NO, you loose!") >>> >> You repeat this pattern throughout your program, so it should be made >> a function like this: >> >> def ask_question(question): >> answer = input(question) >> answer = answer.upper() >> if answer == "YES" or answer == "NO": >> print "...You said %s, you loose!", answer >> exit(0) # this will end the program >> return # this will get you out of your function >> >> >> To ask all of your questions, create a list of questions like this: >> >> list_of_questions = ["first question", "second question", etc ... ] >> >> Now do this: >> for question in list_of_questions: >> ask_question(question) sorry I messed up the last line a couple of times >> >> >> then finish with what you have below. >> >> >>> >>> print("OK, you win!You didn't say 'YES' or 'NO', well done!") >>> time.sleep(2) >>> >>> >>> >>> >>> Abid Saied >>> abidsaied at gmail.com >>> >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> https://mail.python.org/mailman/listinfo/tutor >> >> >> >> -- >> Joel Goldstick >> http://joelgoldstick.com > > > > -- > Joel Goldstick > http://joelgoldstick.com -- Joel Goldstick http://joelgoldstick.com From terry.kemmerer at gmail.com Wed Aug 20 21:06:14 2014 From: terry.kemmerer at gmail.com (Terry--gmail) Date: Wed, 20 Aug 2014 13:06:14 -0600 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> <53F3D2A1.2040402@gmail.com> Message-ID: <53F4F1A6.5090905@gmail.com> Alan Gauld Hi! We are not quite out of the woods on this last example you gave me. It now seems to be complaining that it doesn't want to append an integer to the list or that this isn't the place to use '.append' -- I am probably interpreting it's complaint wrong: Python 3.3 If I run this last piece of code that we just added 'enumerate(row)' to: lens = [0] * len(catalog2[0]) for row in catalog2: for col, item in enumerate(row): print(col, item, len(item)) lens[col].append(len(item)) lens = [max(col) for col in lens] My result is: 0 Drives 6 <<---- my print statement result Traceback (most recent call last): File "/home/justme/1a_Computer_Related/Python/scripts/scratch.py", line 43, in lens[col].append(len(item)) AttributeError: 'int' object has no attribute 'append' While messing with the above problem, I found myself thinking (almost always a mistake on my part) that the '.append' extension doesn't need the list pre-formatted any more than a simple lens= [], since .append has the ability to expand the list anyway, which would let the number of columns be more easily expanded later in life by the programmer simply adding a column of data to the table, so I tried- lens = [] for row in catalog2: for col, item in enumerate(row): print(col, item, len(item)) lens[col].append(len(item)) lens = [max(col) for col in lens] But my result says otherwise: 0 Drives 6 Traceback (most recent call last): File "/home/justme/1a_Computer_Related/Python/scripts/scratch.py", line 45, in lens[col].append(len(item)) IndexError: list index out of range From dyoo at hashcollision.org Wed Aug 20 21:14:49 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 20 Aug 2014 12:14:49 -0700 Subject: [Tutor] Fwd: Embedding resources In-Reply-To: References: Message-ID: On Wed, Aug 20, 2014 at 6:45 AM, diliup gabadamudalige wrote: > Hi Danny! > > The routine works fine and so does this one. > > http://www.pygame.org/pcr/zipshow/index.php > > The only problem with all these are that that the time taken to read these > files and to either make a list or send to screen is WAY TOO LONG. > The only one that works without much delay is in the file I have attached. Hi Dilliup, You'll probably want to contact the PyGame community to get more specialized help on this one then. I suspect that this is a common problem that the PyGame folks there have encountered (and hopefully solved!). The problem of including resources in packaged programs, in a way that's resistant to outside peeking, is specialized enough that Tutor is probably not the most effective place to ask. You can talk to them from the links here: http://pygame.org/wiki/info Good luck! From marc.tompkins at gmail.com Wed Aug 20 22:26:07 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 20 Aug 2014 13:26:07 -0700 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F4F1A6.5090905@gmail.com> References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> <53F3D2A1.2040402@gmail.com> <53F4F1A6.5090905@gmail.com> Message-ID: On Aug 20, 2014 12:07 PM, "Terry--gmail" wrote: > > Alan Gauld > > Hi! > We are not quite out of the woods on this last example you gave me. It now seems to be complaining > that it doesn't want to append an integer to the list or that this isn't the place to use '.append' -- I am probably interpreting it's complaint wrong: > > Python 3.3 > > If I run this last piece of code that we just added 'enumerate(row)' to: > > lens = [0] * len(catalog2[0]) > for row in catalog2: > > for col, item in enumerate(row): > print(col, item, len(item)) > > lens[col].append(len(item)) > lens = [max(col) for col in lens] > > My result is: > > 0 Drives 6 <<---- my print statement result > > Traceback (most recent call last): > File "/home/justme/1a_Computer_Related/Python/scripts/scratch.py", line 43, in > lens[col].append(len(item)) > AttributeError: 'int' object has no attribute 'append' > Once again you're confusing the list with its contents. lens is a list; lens[col] is an integer. lens.append(whatever) should do the trick. -------------- next part -------------- An HTML attachment was scrubbed... URL: From terry.kemmerer at gmail.com Wed Aug 20 22:38:29 2014 From: terry.kemmerer at gmail.com (Terry--gmail) Date: Wed, 20 Aug 2014 14:38:29 -0600 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> <53F3D2A1.2040402@gmail.com> <53F4F1A6.5090905@gmail.com> Message-ID: <53F50745.9030203@gmail.com> Marc, my understanding is, is that: lens[col].append(len(item)) -should be building a mirror image of my list of lists called catalog2, which currently has 9 columns by x number of rows, and that we are plugging into these positions, the sizes of all the elements in that block of data. If that is true, then lens[col] is creating lists which contain the sizes of the elements in that particular column. So, I completely don't understand why we would eliminate the positioning of which list we are referencing in lens by saying: lens.append(len(item)) It seems to me that, that statement would put the entire block of element sizes into one list, and the next MAX statement would then yield only a single number, which would be the largest size element it encounted in the whole of catalog2! Or am I really missing the boat here? :) Thanks for your thoughts! --Terry On 08/20/2014 02:26 PM, Marc Tompkins wrote: > > On Aug 20, 2014 12:07 PM, "Terry--gmail" > wrote: > > > > Alan Gauld > > > > Hi! > > We are not quite out of the woods on this last example you gave me. > It now seems to be complaining > > that it doesn't want to append an integer to the list or that this > isn't the place to use '.append' -- I am probably interpreting it's > complaint wrong: > > > > Python 3.3 > > > > If I run this last piece of code that we just added 'enumerate(row)' to: > > > > lens = [0] * len(catalog2[0]) > > for row in catalog2: > > > > for col, item in enumerate(row): > > print(col, item, len(item)) > > > > lens[col].append(len(item)) > > lens = [max(col) for col in lens] > > > > My result is: > > > > 0 Drives 6 <<---- my print statement result > > > > Traceback (most recent call last): > > File "/home/justme/1a_Computer_Related/Python/scripts/scratch.py", > line 43, in > > lens[col].append(len(item)) > > AttributeError: 'int' object has no attribute 'append' > > > Once again you're confusing the list with its contents. lens is a > list; lens[col] is an integer. lens.append(whatever) should do the trick. > From marc.tompkins at gmail.com Wed Aug 20 22:56:04 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 20 Aug 2014 13:56:04 -0700 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F50745.9030203@gmail.com> References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> <53F3D2A1.2040402@gmail.com> <53F4F1A6.5090905@gmail.com> <53F50745.9030203@gmail.com> Message-ID: On Wed, Aug 20, 2014 at 1:38 PM, Terry--gmail wrote: > Marc, my understanding is, is that: > > lens[col].append(len(item)) > > -should be building a mirror image of my list of lists called catalog2, > which currently has 9 columns by x number of rows, and that we are plugging > into these positions, the sizes of all the elements in that block of data. What's important is how you defined lens: > lens = [0] * len(catalog2[0]) That's a list of integers, as far as I can tell without running it (I'm away from an interpreter at the moment.) So no, you cannot do lens[col].append(whatever), because - as the error message said - 'int' object has no attribute 'append'. There might be some misunderstanding about what list.append(whatever) does - it adds "whatever" to the end of list. It does NOT assign values to elements that already exist; to do that, you need to do assignment by index. So maybe this is what you're looking for?: > lens[col] = len(item) > So, I completely don't understand why we would eliminate the positioning of > which list we are referencing in lens by saying: > > lens.append(len(item)) > > It seems to me that, that statement would put the entire block of element > sizes into one list, and the next MAX statement would then yield only a > single number, which would be the largest size element it encounted in the > whole of catalog2! > > Or am I really missing the boat here? :) > lens.append(len(item)) will append a single integer to lens. I'm afraid I don't quite follow the bit about "the next MAX statement", as I've lost the thread of what your larger project is trying to accomplish... In any case, max() _should_ only return a single number, no? From __peter__ at web.de Wed Aug 20 23:18:31 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 20 Aug 2014 23:18:31 +0200 Subject: [Tutor] Building Starships -- object of type 'int' has no len() References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> <53F3D2A1.2040402@gmail.com> <53F4F1A6.5090905@gmail.com> <53F50745.9030203@gmail.com> Message-ID: Terry--gmail wrote: > Marc, my understanding is, is that: > > lens[col].append(len(item)) > > -should be building a mirror image of my list of lists called catalog2, > which currently has 9 columns by x number of rows, and that we are > plugging into these positions, the sizes of all the elements in that > block of data. > > If that is true, then lens[col] is creating lists which contain the > sizes of the elements in that particular column. > > So, I completely don't understand why we would eliminate the positioning > of which list we are referencing in lens by saying: > > lens.append(len(item)) > > It seems to me that, that statement would put the entire block of > element sizes into one list, and the next MAX statement would then yield > only a single number, which would be the largest size element it > encounted in the whole of catalog2! > > Or am I really missing the boat here? :) [Alan Gauld] > lens = [] * len(catalog2[0]) > for row in catalog2[1:]: # miss the first row > for col,item in row: > lens[col].append(len(item)) > > lens = [max(col) for col in lens] In the above snipped Alan introduced introduced another bug that wasn't fixed in any of the posts I saw: lens should be a list of lists. With "lens" referring to [[], [], [], ...] lens[n] refers to the n-th list and thus lens[col].append(len(item)) appends the items's length to the respective column/list. The complete fixed code is then: # make a list with one empty list per column lens = [] for item in catalog2[0]: lens.append([]) for row in catalog2: for col, item in enumerate(row): lens[col].append(len(item)) lens = [max(col) for col in lens] The first for-loop can also be written as a list comprehension: lens = [[] for item in catalog2[0]] You might be tempted to simplify further # WRONG: lens = [[]] * len(catalog2[0]) but that repeats the same inner list len(catalog2[0]) times where you actually need len(catalog2[0]) distinct lists. From davea at davea.name Thu Aug 21 00:09:16 2014 From: davea at davea.name (Dave Angel) Date: Wed, 20 Aug 2014 18:09:16 -0400 (EDT) Subject: [Tutor] Parsing txt file References: <1408538103.932889670@f414.i.mail.ru> Message-ID: Dima Kulik Wrote in message: Please post in text mode. The html mode you used can cause multiple problems. Please specify your Python version and os version in any new thread.It sometimes makes a big difference in the solution. Your primary problem is that you don't close the files. But you should start by writing a specification. I'm not sure what you mean by all stings. I'd assume you mean all lines. But that's not what the code does. The code is looking at every word of every line. Perhaps you mean the first word of the input file. You say the output is clear, by which I'm guessing you mean the output file is empty. Since there could be many causes for that, I'd suggest adding appropriate print statements to see what happened. I'd also suggest removing the call to readlines. It doesn't change the result, and causes several problems. One is that input _ file is not a File, but a list. It becomes impossible to close it, and if the file is large it wastes memory. -- DaveA From terry.kemmerer at gmail.com Thu Aug 21 00:34:27 2014 From: terry.kemmerer at gmail.com (Terry--gmail) Date: Wed, 20 Aug 2014 16:34:27 -0600 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> <53F3D2A1.2040402@gmail.com> <53F4F1A6.5090905@gmail.com> <53F50745.9030203@gmail.com> Message-ID: <53F52273.8070806@gmail.com> Hi Marc Tompkins! You are absolutely right that lens = [0] * len(catalog2[0]) Just creates a list of integers! Here is what happened, my original method of finding the maximum element sizes in the 9 x ? block of data held in catalog2, only needed a final list of integers to contain it. However, as everyone helped me make my routine more pythonic, things evolved, but we always used the same beginning formatting statement until Alan Gauld gave me, as a last example, a different way to do the same thing, but he left out, I think, a matching formatting statement, and I ASSUMED WE WERE STILL USING THE OLD ONE. You drew my eyes to it. So, I replaced the above statement with this line: lens = [[], [], [], [], [], [], [],[], []] So, trying that: lens = [[], [], [], [], [], [], [],[], []] for row in catalog2: for col, item in enumerate(row): lens[col].append(len(item)) lens = [max(col) for col in lens] print(lens) My result is: [6, 17, 5, 9, 12, 7, 0, 0, 0] <<--------THAT IS CORRECT! IT WORKS!!! But, when I try to automate the formatting of lens so that my data block can easily be changed in the originating table: lens = [[]] * len(catalog2[0]) for row in catalog2: for col, item in enumerate(row): lens[col].append(len(item)) lens = [max(col) for col in lens] print(lens) My result is: [17, 17, 17, 17, 17, 17, 17, 17, 17] <<--------THAT IS NOT CORRECT! I haven't figured out what the difference is between the two formatting statements....but it appears to be profound! Ha! And the MAX statement that I was referring to that you couldn't see was the last line where the column lists were used to find the maximum size of each column of sizes and change lens to a single list of integers: lens = [max(col) for col in lens] --Terry IT WORKS! I just don't know how to automatically format lens with enough [] like I was able to tell On 08/20/2014 02:56 PM, Marc Tompkins wrote: > On Wed, Aug 20, 2014 at 1:38 PM, Terry--gmail wrote: >> Marc, my understanding is, is that: >> >> lens[col].append(len(item)) >> >> -should be building a mirror image of my list of lists called catalog2, >> which currently has 9 columns by x number of rows, and that we are plugging >> into these positions, the sizes of all the elements in that block of data. > What's important is how you defined lens: >> lens = [0] * len(catalog2[0]) > That's a list of integers, as far as I can tell without running it > (I'm away from an interpreter at the moment.) So no, you cannot do > lens[col].append(whatever), because - as the error message said - > 'int' object has no attribute 'append'. > > There might be some misunderstanding about what list.append(whatever) > does - it adds "whatever" to the end of list. It does NOT assign > values to elements that already exist; to do that, you need to do > assignment by index. So maybe this is what you're looking for?: >> lens[col] = len(item) > > >> So, I completely don't understand why we would eliminate the positioning of >> which list we are referencing in lens by saying: >> >> lens.append(len(item)) >> >> It seems to me that, that statement would put the entire block of element >> sizes into one list, and the next MAX statement would then yield only a >> single number, which would be the largest size element it encounted in the >> whole of catalog2! >> >> Or am I really missing the boat here? :) >> lens.append(len(item)) > will append a single integer to lens. I'm afraid I don't quite follow > the bit about "the next MAX statement", as I've lost the thread of > what your larger project is trying to accomplish... In any case, > max() _should_ only return a single number, no? > From dyoo at hashcollision.org Thu Aug 21 00:48:35 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 20 Aug 2014 15:48:35 -0700 Subject: [Tutor] Parsing txt file In-Reply-To: <1408538103.932889670@f414.i.mail.ru> References: <1408538103.932889670@f414.i.mail.ru> Message-ID: > i need to export to file all stings which start from "Name" > > I've tried to make little parser: > > keywords = ['Name', 'Name:'] > input_file=open("Mail_Groups.txt","r").readlines() > output_file=open("Out.txt","w") > for line in input_file: > for word in line.split(): > if word in keywords: > output_file.write(line) > > but the output is clear. Questions: 1. How are you determining that the output is clear? I don't know what you mean by "output is clear". 2. Does your program close() the file that it is writing to? See: https://docs.python.org/2/library/stdtypes.html#file.write https://docs.python.org/2/library/stdtypes.html#file.close as to why this may be important. 3. Your problem description says: i need to export to file all stings which start from "Name" but the code here: for word in line.split(): if word in keywords: ... is doing much more than what is required. It is checking whether "Name" shows up anywhere on the line, not just as part of the name of the left-hand-side key. Is that ok? From dyoo at hashcollision.org Thu Aug 21 00:51:26 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 20 Aug 2014 15:51:26 -0700 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F52273.8070806@gmail.com> References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> <53F3D2A1.2040402@gmail.com> <53F4F1A6.5090905@gmail.com> <53F50745.9030203@gmail.com> <53F52273.8070806@gmail.com> Message-ID: > > lens = [0] * len(catalog2[0]) Ah. Read the following closely: https://docs.python.org/2/faq/programming.html#how-do-i-create-a-multidimensional-list If you have any questions, please feel free to ask further. See if that clears up the mistake that's in your code. From alan.gauld at btinternet.com Thu Aug 21 00:56:48 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 20 Aug 2014 23:56:48 +0100 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: <53F4F1A6.5090905@gmail.com> References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> <53F3D2A1.2040402@gmail.com> <53F4F1A6.5090905@gmail.com> Message-ID: On 20/08/14 20:06, Terry--gmail wrote: > We are not quite out of the woods on this last example > lens = [0] * len(catalog2[0]) This is what happens when you don't test code. My apologies, the initialisation is all wrong. Try this instead: lens = [ [] for n in catalog2[0] ] That adds an empty list for each element in catalog2's header. > for row in catalog2: > for col, item in enumerate(row): > print(col, item, len(item)) > lens[col].append(len(item)) > lens = [max(col) for col in lens] This should now work... although I still haven't tested it! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From japhy at pearachute.com Wed Aug 20 23:03:31 2014 From: japhy at pearachute.com (Japhy Bartlett) Date: Wed, 20 Aug 2014 16:03:31 -0500 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> <53F3D2A1.2040402@gmail.com> <53F4F1A6.5090905@gmail.com> <53F50745.9030203@gmail.com> Message-ID: this forms a list of integers >>> [0]*5 [0, 0, 0, 0, 0] what I think you want is something like: >>> [[0] for i in range(5)] [[0], [0], [0], [0], [0]] (a list of lists) >>> foo = [[0] for i in range(5)] >>> foo[3].append('bar') >>> foo [[0], [0], [0], [0, 'bar'], [0]] On Wed, Aug 20, 2014 at 3:56 PM, Marc Tompkins wrote: > On Wed, Aug 20, 2014 at 1:38 PM, Terry--gmail > wrote: > > Marc, my understanding is, is that: > > > > lens[col].append(len(item)) > > > > -should be building a mirror image of my list of lists called catalog2, > > which currently has 9 columns by x number of rows, and that we are > plugging > > into these positions, the sizes of all the elements in that block of > data. > > What's important is how you defined lens: > > lens = [0] * len(catalog2[0]) > > That's a list of integers, as far as I can tell without running it > (I'm away from an interpreter at the moment.) So no, you cannot do > lens[col].append(whatever), because - as the error message said - > 'int' object has no attribute 'append'. > > There might be some misunderstanding about what list.append(whatever) > does - it adds "whatever" to the end of list. It does NOT assign > values to elements that already exist; to do that, you need to do > assignment by index. So maybe this is what you're looking for?: > > lens[col] = len(item) > > > > > So, I completely don't understand why we would eliminate the positioning > of > > which list we are referencing in lens by saying: > > > > lens.append(len(item)) > > > > It seems to me that, that statement would put the entire block of element > > sizes into one list, and the next MAX statement would then yield only a > > single number, which would be the largest size element it encounted in > the > > whole of catalog2! > > > > Or am I really missing the boat here? :) > > > lens.append(len(item)) > will append a single integer to lens. I'm afraid I don't quite follow > the bit about "the next MAX statement", as I've lost the thread of > what your larger project is trying to accomplish... In any case, > max() _should_ only return a single number, no? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Thu Aug 21 01:31:53 2014 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 21 Aug 2014 09:31:53 +1000 Subject: [Tutor] Parsing txt file In-Reply-To: <1408538103.932889670@f414.i.mail.ru> References: <1408538103.932889670@f414.i.mail.ru> Message-ID: <20140820233153.GA99960@cskk.homeip.net> On 20Aug2014 16:35, Dima Kulik wrote: > Hi to all. I have a problem with parsing file. >I have txt file exported from AD and it has such structure: > >DistinguishedName : CN=*** ,OU=*** ,OU=*** ,DC=*** ,DC=***,DC=*** >GroupCategory???? : Distribution >GroupScope??????? : Universal >Name????????????? : **** >ObjectClass?????? : group >ObjectGUID??????? : 0b74b4e2-aad1-4342-a8f4-2fa7763e1d49 >SamAccountName??? : **** >SID?????????????? : S-1-5-21-1801674531-492894223-839522115-16421 [...] >I've tried to make little parser: > >keywords = ['Name', 'Name:'] >input_file=open("Mail_Groups.txt","r").readlines() >output_file=open("Out.txt","w") >for line in input_file: >??? for word in line.split(): Aside from the remarks from others, I would change the way you're parsing each line. Based entirely on what you show above, I'd make the main out loops look like this: for line in input_file: left, right = line.split(':', 1) label = left.strip() value = right.strip() and then made decisions using "label" and "value". Your approach breaks the line into "words" on whitespace, which has several difficulties, including that the example input data look like a report. Often things with trailing colons will abut the colon if the label is long, eg: HereIsALongNameLabel: info... Your split() will be presuming the colon is spaced out. Just splitting once on the first colon and the trimming the whitespace from the two piece is simpler and gets you a more reliable parse. Cheers, Cameron Simpson Trust the computer industry to shorten Year 2000 to Y2K. It was this thinking that caused the problem in the first place. - Mark Ovens From terry.kemmerer at gmail.com Thu Aug 21 08:25:58 2014 From: terry.kemmerer at gmail.com (Terry--gmail) Date: Thu, 21 Aug 2014 00:25:58 -0600 Subject: [Tutor] Building Starships -- object of type 'int' has no len() In-Reply-To: References: <53F1947D.2000602@gmail.com> <20140818071341.GA91999@cskk.homeip.net> <53F3D2A1.2040402@gmail.com> <53F4F1A6.5090905@gmail.com> <53F50745.9030203@gmail.com> Message-ID: <53F590F6.3050904@gmail.com> Thanks Japhy Bartlett! [[0] for i in range(5)] Works! I converted to fit into my routine as: lens = [[] for i in range(len(catalog2[0]))] <<---- the new statement for row in catalog2: for col, item in enumerate(row): lens[col].append(len(item)) lens = [max(col) for col in lens] print(lens) My result is: [6, 17, 5, 9, 12, 7, 0, 0, 0] <<--------THAT IS THE CORRECT ANSWER! Perfect! Peter Otten Thanks! Those work also! Danny Yoo Thanks for the Documentation on creating multidimensioned lists! Interesting read! And now I know why my first attempts to get multi-dimensions from an equation failed. Alan Gauld YUP! lens = [ [] for n in catalog2[0] ] Works! --And greatly simplifies how I first constructed this! Thanks! Thanks Everyone! This gets me going again.... From lnartist at yahoo.com Thu Aug 21 04:12:10 2014 From: lnartist at yahoo.com (LN A-go-go) Date: Wed, 20 Aug 2014 19:12:10 -0700 Subject: [Tutor] import values, calculate distance Message-ID: <1408587130.81435.YahooMailNeo@web161304.mail.bf1.yahoo.com> Python Mentors, I can't get this code to run and at times, I can't even save it.? It is sections of code used from previous exercises, put it together?and it just isn't right.? Thank-you, LN The method is as follows: 1. Run the distance calculations for pt1 to all other points, and print or save the results. 2. Set a holding variable for pt1 values, then switch the values from pt1 to pt2 (so pt2 is now in the first position of your coordinate list). 3. Calculate the new distances for pt2 to all other points, and print or save the results. 4. Switch pt2 and pt1 so that they are back in their original positions. 5. Re-set the holding variable for pt1 values, then switch the values from pt1 to pt3 (so pt3 is now in the first position of your coordinate list).?Calculate the new distances for pt3 to all other points, and print or save the results. ? continue with this method until all points are done. Here is the text file of points: ID?X?Y PT1?2.6?8.7 PT2?5.6?10.3 PT3?8.9?45.7 PT4?10.4?6.2 PT5?2.1?21.4 PT6?8.7?78.2 PT7?44.5?15.2 PT8?23.6?45.8 PT9?43.1?2.3 PT10?1.1?62.5 ? # Description: read in all of the given data file and then calculate # the distance between each of the data points and then write or print out the results # to a new text file. # Open path to file, readlines and create variables, run a 'while' loop, split the line (initialize with import string) into the three variable lists infile = open("z:/filepath/coordinate.txt","r") line = infile.readline() import math import string IDCODE = [] XCOORDINATE = [] YCOORDINATE = [] n = 0 while True: ?line = infile.readline() ?if not line: break ?ID,X,Y = string.split(line) ?XNUM = float(X) ?YNUM = float(Y) ?n = n + 1 ?XCOORDINATE.append(XNUM) ?YCOORDINATE.append(YNUM) ?IDCODE.append(ID)? ? print (XCOORDINATE, YCOORDINATE), IDCODE # # activate the math modular function (use import math function) in order to use the #square root function dist = {} def distance(n,p,s, XCOORDINATE, YCOORDINATE, IDCODE): ?import math ?p = 1 ?s = 0 ?DP = [] ?while p < n: ?? DT= math.sqrt((XCOORDINATE[p]-XCOORDINATE[0])**2 + (YCOORDINATE[p]-YCOORDINATE[0])**2) ??DP.append(DT) ??p = p + 1 ?while s < n-1: ??dist[DP[s]] = IDCOORDINATE[s+1] ??s = s + 1 ?? ??for key in sorted(dist): ???print dist[key],[key] ?return dist def switch(n,XCOORDINATE, YCOORDINATE, IDCODE): ?import math, string ?idcodezero = IDCODE[0] ?xcodezero = XCOORDINATE[0] ?ycodezero = YCOORDINATE[0] ?z = 1 ?while z <=n - 1: ??IDCODE[0] = IDCODE[z] ??XCOORDINATE[0] = XCOORDINATE[z] ??YCOORDINATE[0] = YCOORDINATE[z] ??IDCODE[z] = IDCODEzero ??XCOORDINATE[z] = XCOORDINATEzero ??YCOORDINATE[z] = YCOORDINATEzero ??DR = distance(n,XCOORDINATE, YCOORDINATE, IDCODE) ??IDCODE[z] = IDCODE[0] ??XCOORDINATE[z] = XCOORDINATE[0] ??YCOORDINATE[z] = YCOORDINATE[0] ??IDCODE[0] = IDCODEzero ??XCOORDINATE[0] = XCOORDINATEzero ??YCOORDINATE[0] = YCOORDINATEzero ??DP = [] ??z = z + 1 ?? # -------------- next part -------------- An HTML attachment was scrubbed... URL: From Lucia.Stockdale at mggs.vic.edu.au Thu Aug 21 05:03:03 2014 From: Lucia.Stockdale at mggs.vic.edu.au (Lucia Stockdale) Date: Thu, 21 Aug 2014 13:03:03 +1000 Subject: [Tutor] Question Message-ID: <9AAE9AAD971D6F47A5FE32CC54DA4236023C2CE14BAB@MGGS-EXDS02.mggs.vic.edu.au> Hi everyone, I have been writing a program to print words backwards until an an empty line of input is entered, but after I put in the input it comes up with TypeError. This is my goal: Line: hello world olleh dlrow Line: extra artxe Line: i love python i evol nohtyp Line: This is my current code: line = input('Line: ') while line != '': line = line[len(line):0:-1] line = line.split() line = line.reverse() line = (' '.join(line)) print(line) Thanks Lucia This email is intended for the use of the named individual or entity and may contain confidential and privileged information. Any dissemination, distribution or copying by anyone other than the intended recipient of this email is strictly prohibited. Confidentiality and legal privilege are not waived or lost as a result of mistaken delivery. Attachments are opened and transmitted at the user's own risk. Any representations or opinions expressed are those of the individual sender, and not necessarily those of Melbourne Girls Grammar. From __peter__ at web.de Thu Aug 21 10:04:27 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 21 Aug 2014 10:04:27 +0200 Subject: [Tutor] Question References: <9AAE9AAD971D6F47A5FE32CC54DA4236023C2CE14BAB@MGGS-EXDS02.mggs.vic.edu.au> Message-ID: Lucia Stockdale wrote: > Hi everyone, > > I have been writing a program to print words backwards until an an empty > line of input is entered, but after I put in the input it comes up with > TypeError. In the future please include the traceback (cut and paste, don't rephrase). > This is my goal: > > Line: hello world > olleh dlrow > Line: extra > artxe > Line: i love python > i evol nohtyp > Line: > > This is my current code: > > line = input('Line: ') > while line != '': > line = line[len(line):0:-1] Python uses half-open intervals; thus line[0] is not included in the result. Use line = line[::-1] to reverse the string. > line = line.split() > line = line.reverse() The reverse() method modifies the line in place, and by convention such methods return None in Python. Change the above line to line.reverse() > line = (' '.join(line)) > print(line) I see another problem, the while loop will run at most once, but you should be able to fix that yourself. From felix.dietrich at sperrhaken.name Thu Aug 21 10:08:16 2014 From: felix.dietrich at sperrhaken.name (Felix Dietrich) Date: Thu, 21 Aug 2014 10:08:16 +0200 Subject: [Tutor] Question In-Reply-To: <9AAE9AAD971D6F47A5FE32CC54DA4236023C2CE14BAB@MGGS-EXDS02.mggs.vic.edu.au> (Lucia Stockdale's message of "Thu, 21 Aug 2014 13:03:03 +1000") References: <9AAE9AAD971D6F47A5FE32CC54DA4236023C2CE14BAB@MGGS-EXDS02.mggs.vic.edu.au> Message-ID: <87egwajmdr.fsf@turm.home> Lucia Stockdale writes: > I have been writing a program to print words backwards until an an > empty line of input is entered, but after I put in the input it comes > up with TypeError. For completeness give us the whole Traceback, it makes pin-pointing the error easier. Also, tell us which Version of /python/ you are using. I assume you are using python3, because you did not get a SyntaxError in /input/ (in python2 /input/ evaluates the string as python-code). > This is my current code: > > line = input('Line: ') > while line != '': > line = line[len(line):0:-1] > line = line.split() > line = line.reverse() Reverse mutates the list /line/ and returns None, which you then assign to /line/. Returning None is a common pattern for python methods mutating the objects value and not creating a copy. > line = (' '.join(line)) Your calling of ' '.join(None) results in a TypeError here. str.join takes an iterable. > print(line) After the call to /print/ you probably want to duplicate the line line = input('Line: ') or you will end up in an infinite loop, since your program does not read another line of input and therefore the value of /line/ never changes and gets no chance to become the empty string. -- Felix Dietrich From cs at zip.com.au Thu Aug 21 09:55:17 2014 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 21 Aug 2014 17:55:17 +1000 Subject: [Tutor] Question In-Reply-To: <9AAE9AAD971D6F47A5FE32CC54DA4236023C2CE14BAB@MGGS-EXDS02.mggs.vic.edu.au> References: <9AAE9AAD971D6F47A5FE32CC54DA4236023C2CE14BAB@MGGS-EXDS02.mggs.vic.edu.au> Message-ID: <20140821075517.GA90745@cskk.homeip.net> On 21Aug2014 13:03, Lucia Stockdale wrote: >I have been writing a program to print words backwards until an an empty line of input is entered, >but after I put in the input it comes up with TypeError. Hi Lucia, It would be helpful to include the whole traceback that Python shows you. Can you reply including this information please? At the least it should tell you the precise line on which the error occurs. Then you can insert a print() call before that particular line to show the values or types involved. [...snip...] >Line: i love python >i evol nohtyp [...] Thanks for providing a nice clear description of the desired output. >This is my current code: >line = input('Line: ') >while line != '': > line = line[len(line):0:-1] You might find: line = line.strip() simpler. > line = line.split() "line" used to be a string. Now it is an array of strings. I tend to write this as: words = line.split() and work with the name "words" from there on. It keeps it clearer in the mind the different types of values in play. Anyway, come back wish a traceback and the results of any other experiments you make with your program and we'll see where we are. Cheers, Cameron Simpson ... and that was only one of many occasions on which I met my death, an experience which I don't hesitate to recommend strongly. - Baron von Munchausen From __peter__ at web.de Thu Aug 21 10:27:06 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 21 Aug 2014 10:27:06 +0200 Subject: [Tutor] Question References: <9AAE9AAD971D6F47A5FE32CC54DA4236023C2CE14BAB@MGGS-EXDS02.mggs.vic.edu.au> Message-ID: Peter Otten wrote: > I see another problem, the while loop will run at most once, but you > should be able to fix that yourself. Sorry, it will run forever reversing and unreversing the same string... From davea at davea.name Thu Aug 21 10:32:31 2014 From: davea at davea.name (Dave Angel) Date: Thu, 21 Aug 2014 04:32:31 -0400 (EDT) Subject: [Tutor] Question References: <9AAE9AAD971D6F47A5FE32CC54DA4236023C2CE14BAB@MGGS-EXDS02.mggs.vic.edu.au> Message-ID: Lucia Stockdale Wrote in message: > Hi everyone, Welcome to the list. And thanks for using text mode. What's the Python version and os version. I expect this is crucial. > > I have been writing a program to print words backwards until an an empty line of input is entered, > but after I put in the input it comes up with TypeError. What else did it say? You're paraphrasing a traceback into one word. Just copy/paste the whole thing, starting with the word Traceback, and ending with the error line, apparently starting with the word TypeError: For that matter, you should include the output starting with the prompt 'Line: ' > > This is my goal: > > Line: hello world > olleh dlrow > Line: extra > artxe > Line: i love python > i evol nohtyp > Line: > > This is my current code: > > line = input('Line: ') > while line != '': > line = line[len(line):0:-1] > line = line.split() > line = line.reverse() > line = (' '.join(line)) > print(line) > > Most likely your problem is that you're using Python 2.x, and therefore should be using raw_input instead of input. Of course the full traceback could point somewhere else, since it shows the line in error. After you fix the error that python shows you you'll still have at least two more. You'll need another raw_input at the end of the loop. And the call to reverse will reorder the words in the line, not the letters in each word. You need a loop or equivalent. In fact I'd recommend assigning the results ofbthe split to a different name, since it's no longer a line, but a list of words. Something like words = line.split () At that point it should be clearer that you have to loop over the words. I'll point out that the outer parentheses on the join line are redundant but harmless. The do nothing for the compiler and just confuse a human reader. > > This email is intended for the use of the named individual or entity and may contain confidential and privileged information. ....... Don't post confidential information on a public mailing list. And don't expect such a disclaimer to do anything but waste megabytes of space on computers around the world. > > -- DaveA From breamoreboy at yahoo.co.uk Thu Aug 21 10:32:10 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 21 Aug 2014 09:32:10 +0100 Subject: [Tutor] Top posting Message-ID: Please note everybody that I'm giving up trying to help out here as I can't cope with the stream of top posted replies. They make long threads such as the recent "Re: Building Starships -- object of type 'int' has no len()" unreadable to me. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From davea at davea.name Thu Aug 21 11:19:13 2014 From: davea at davea.name (Dave Angel) Date: Thu, 21 Aug 2014 05:19:13 -0400 (EDT) Subject: [Tutor] import values, calculate distance References: <1408587130.81435.YahooMailNeo@web161304.mail.bf1.yahoo.com> Message-ID: LN A-go-go Wrote in message: > Thanks for a better subject line, and for starting a new thread when you have a substantially new question. . Please use text mail instead of html. The html you're using can cause several different problems. And please do interleaved quoting, not top-posting. (I can't do likewise, since your html doesn?t quote at all with my mail reader) Also specify in the first message of any thread what python version and os version you're using. You say 'at times, I can't even save it' Sounds like you need to learn your text editor better. Or switch to a better one if it's just flaky. You say 'it just isn't right' That's not much of an error message. You need to make it easier for us to help you. Did you get a traceback? Quote the whole thing. Did you get the wrong results? Tell us what you expected and show us what you got instead. So, without some specific questions, I'll comment on the code. Some of these changes may help you narrow down the problem. You only seem to be indenting 2 spaces, but that may be an html artifact, see above. Many htn ml to text converters throw out half the spaces. You have way too much code at top level, rather than functions. In distance (), the line starting DP.append does not line up with the preceding line. All the lines of a given block must line up exactly. I suppose you may be mixing spaces and tabs, which is very dangerous. Tell your editor to convert any existing tabs to spaces, then tell it to expand all future use of the tab key to 4 spaces. You define dist as a global and have an argument for it in function distance. I suspect it should simply be a local in distance () I don't spot any calls to distance or switch. I'm sure there are other things, but without running it, this is enough for now. -- DaveA From Steve.Flynn at capita.co.uk Thu Aug 21 11:03:59 2014 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Thu, 21 Aug 2014 10:03:59 +0100 Subject: [Tutor] sys module - what does "It is always available" mean in the docs? Message-ID: The documentation (https://docs.python.org/3/library/sys.html) for Python 3.4.1 says that "This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available." I interpreted that last sentence as "It's built in", so I made the assumption I didn't need to import it in order to use it. This is not the case - it still needs to be imported before I can use anything defined within it. Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> print(sys.maxsize) Traceback (most recent call last): File "", line 1, in print(sys.maxsize) NameError: name 'sys' is not defined >>> import sys >>> print(sys.maxsize) 9223372036854775807 >>> So, what does the documentation mean by explicitly pointing out that sys is always available? To me, it's misleading but I'm obviously missing a subtlety. I've asked this question on /learnpython on reddit recently and the best explanation is that it's built by the interpreter at runtime, so it can't fail to import due to a broken installation. Any other offers? As an addendum, I fired up my local docs via "Module Docs" and "This is always available" *isn't* in the docs page for sys. I'd assumed they were built from the same sources but apparently not. -- Steve Flynn This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. From davea at davea.name Thu Aug 21 12:32:19 2014 From: davea at davea.name (Dave Angel) Date: Thu, 21 Aug 2014 06:32:19 -0400 (EDT) Subject: [Tutor] sys module - what does "It is always available" mean in the docs? References: Message-ID: "Flynn, Stephen (L & P - IT)" Wrote in message: > The documentation (https://docs.python.org/3/library/sys.html) for > Python 3.4.1 says that "This module provides access to some variables > used or maintained by the interpreter and to functions that interact > strongly with the interpreter. It is always available." > > I interpreted that last sentence as "It's built in", so I made the > assumption I didn't need to import it in order to use it. > The module is available, so the import statement cannot fail. In fact it's already imported and in the cache. Last time I looked, there were 42 modules in the cache by the time your code gets control (see sys.modules). They're not all promised, but sys and time are. If sys is broken, the interpreter won't go. -- DaveA From joel.goldstick at gmail.com Thu Aug 21 15:13:09 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 21 Aug 2014 09:13:09 -0400 Subject: [Tutor] import values, calculate distance In-Reply-To: <1408587130.81435.YahooMailNeo@web161304.mail.bf1.yahoo.com> References: <1408587130.81435.YahooMailNeo@web161304.mail.bf1.yahoo.com> Message-ID: On Wed, Aug 20, 2014 at 10:12 PM, LN A-go-go wrote: > Python Mentors, > > I can't get this code to run and at times, I can't even save it. It is > sections of code used from previous exercises, put it together and it just > isn't right. > > Thank-you, > LN > > > The method is as follows: > > Run the distance calculations for pt1 to all other points, and print or save > the results. > Set a holding variable for pt1 values, then switch the values from pt1 to > pt2 (so pt2 is now in the first position of your coordinate list). > Calculate the new distances for pt2 to all other points, and print or save > the results. > Switch pt2 and pt1 so that they are back in their original positions. > Re-set the holding variable for pt1 values, then switch the values from pt1 > to pt3 (so pt3 is now in the first position of your coordinate list). > Calculate the new distances for pt3 to all other points, and print or save > the results. > ? continue with this method until all points are done. > > > Here is the text file of points: > > ID X Y > PT1 2.6 8.7 > PT2 5.6 10.3 > PT3 8.9 45.7 > PT4 10.4 6.2 > PT5 2.1 21.4 > PT6 8.7 78.2 > PT7 44.5 15.2 > PT8 23.6 45.8 > PT9 43.1 2.3 > PT10 1.1 62.5 > > > > > > > # Description: read in all of the given data file and then calculate > # the distance between each of the data points and then write or print out > the results > # to a new text file. > > # Open path to file, readlines and create variables, run a 'while' loop, > split the line (initialize with import string) into the three variable lists > infile = open("z:/filepath/coordinate.txt","r") > line = infile.readline() > import math > import string For ease of reading, put your imports at the top of your file the code below should probably be put in a function. Its purpose is to read your data and populate your lists. >From here ---------------------------------------------------------------------------------------------------------- > IDCODE = [] > XCOORDINATE = [] > YCOORDINATE = [] while you can name things like this, good python style (look up 'pep8') says this would be better id_code, x_coordinate, y_coordinate But better yet, I think would be to call these things: id, x, y > n = 0 > while True: > line = infile.readline() > if not line: break > ID,X,Y = string.split(line) The only use of X, and Y are to use as placeholder so that you can convert to float ID serves no purpose since you copy it to IDCODE below temp = string.split(line) x = float(temp[1]) y = float(temp[2]) id_code.append[temp[3]) > XNUM = float(X) > YNUM = float(Y) > n = n + 1 > XCOORDINATE.append(XNUM) > YCOORDINATE.append(YNUM) > IDCODE.append(ID) > > print (XCOORDINATE, YCOORDINATE), IDCODE to here ---------------------------------------------------------------------------------------------------------------- This looks like a new function below > # > # activate the math modular function (use import math function) in order to > use the > #square root function > dist = {} > def distance(n,p,s, XCOORDINATE, YCOORDINATE, IDCODE): > import math > p = 1 > s = 0 > DP = [] > while p < n: > DT= math.sqrt((XCOORDINATE[p]-XCOORDINATE[0])**2 + > (YCOORDINATE[p]-YCOORDINATE[0])**2) > DP.append(DT) > p = p + 1 > while s < n-1: > dist[DP[s]] = IDCOORDINATE[s+1] > s = s + 1 > > for key in sorted(dist): > print dist[key],[key] > return dist > def switch(n,XCOORDINATE, YCOORDINATE, IDCODE): > import math, string > idcodezero = IDCODE[0] > xcodezero = XCOORDINATE[0] > ycodezero = YCOORDINATE[0] > z = 1 > while z <=n - 1: > IDCODE[0] = IDCODE[z] > XCOORDINATE[0] = XCOORDINATE[z] > YCOORDINATE[0] = YCOORDINATE[z] > IDCODE[z] = IDCODEzero > XCOORDINATE[z] = XCOORDINATEzero > YCOORDINATE[z] = YCOORDINATEzero > DR = distance(n,XCOORDINATE, YCOORDINATE, IDCODE) > IDCODE[z] = IDCODE[0] > XCOORDINATE[z] = XCOORDINATE[0] > YCOORDINATE[z] = YCOORDINATE[0] > IDCODE[0] = IDCODEzero > XCOORDINATE[0] = XCOORDINATEzero > YCOORDINATE[0] = YCOORDINATEzero > DP = [] > z = z + 1 > > # > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From __peter__ at web.de Thu Aug 21 15:14:52 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 21 Aug 2014 15:14:52 +0200 Subject: [Tutor] sys module - what does "It is always available" mean in the docs? References: Message-ID: Flynn, Stephen (L & P - IT) wrote: > The documentation (https://docs.python.org/3/library/sys.html) for > Python 3.4.1 says that "This module provides access to some variables > used or maintained by the interpreter and to functions that interact > strongly with the interpreter. It is always available." > > I interpreted that last sentence as "It's built in", so I made the > assumption I didn't need to import it in order to use it. "built-in" means that it is part of the interpreter executable. You still have to import it, but for built-in (and already loaded) modules that is only a cache lookup. That cache (called sys.modules) is part of the sys module, so if the sys module were not available even import would fail... You can find out about other built-in modules with >>> import sys >>> sys.builtin_module_names ('_ast', '_bisect', '_codecs', '_collections', '_datetime', '_elementtree', [...] >>> len(_) 54 > This is not the case - it still needs to be imported before I can use > anything defined within it. > > Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 > bit (AMD64)] on win32 > Type "copyright", "credits" or "license()" for more information. >>>> print(sys.maxsize) > Traceback (most recent call last): > File "", line 1, in > print(sys.maxsize) > NameError: name 'sys' is not defined >>>> import sys >>>> print(sys.maxsize) > 9223372036854775807 >>>> > > So, what does the documentation mean by explicitly pointing out that sys > is always available? To me, it's misleading but I'm obviously missing a > subtlety. > > I've asked this question on /learnpython on reddit recently and the best > explanation is that it's built by the interpreter at runtime, so it > can't fail to import due to a broken installation. Any other offers? > > > As an addendum, I fired up my local docs via "Module Docs" and "This is > always available" *isn't* in the docs page for sys. I'd assumed they > were built from the same sources but apparently not. From alessandro.dibella at gmail.com Thu Aug 21 13:01:14 2014 From: alessandro.dibella at gmail.com (Alessandro Di Bella) Date: Thu, 21 Aug 2014 12:01:14 +0100 Subject: [Tutor] Development of administration utility Message-ID: <53F5D17A.1070305@gmail.com> Hi, We are currently investigating different languages and technologies to develop an command line administration utility. Python is one of the options we are looking at for the job but currently we have no relevant skill set so I thought I'd post some question to get an idea if using python is something worth pursuing or not. The utility should have the following characteristics: 1. support for sub commands and parameters (e.g. svn or git) 2. integration with bash_completion 3. Modular. The idea would be that by installing different packages (or RPMs), new sub-commands and parameters will be made available to the utility. E.g., 1. "Base" package is installed: subcommand available is "view-config " 2. "Base" and "database" package are installed, subcommands available are "view-config" and "backup-db" 4. Support for executing remote commands via ssh I have no doubt that with enough effort, a Python application could be developed to implement the above. However, I'm not too sure if Python is the right tools for the job particularly about point 3: 1. Is there a built-in discovery mechanism like Java SPI (http://docs.oracle.com/javase/tutorial/sound/SPI-intro.html)? 2. Are there any libraries/framework we could build upon or would we need to start from scratch? 3. Should we consider 2.x or 3.x in order to ensure cross system compatibility (linux, windows)? Any feedback on any of the points above would be greatly appreciated. Regards, Alessandro -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at linux-ip.net Thu Aug 21 18:42:33 2014 From: martin at linux-ip.net (Martin A. Brown) Date: Thu, 21 Aug 2014 12:42:33 -0400 Subject: [Tutor] Development of administration utility In-Reply-To: <53F5D17A.1070305@gmail.com> References: <53F5D17A.1070305@gmail.com> Message-ID: Greetings Alessandro, : We are currently investigating different languages and technologies to : develop an command line administration utility. : Python is one of the options we are looking at for the job but currently we : have no relevant skill set so I thought I'd post some question to get an idea : if using python is something worth pursuing or not. : : The utility should have the following characteristics: : : 1. support for sub commands and parameters (e.g. svn or git) : 2. integration with bash_completion : 3. Modular. The idea would be that by installing different packages : (or RPMs), new sub-commands and parameters will be made available to : the utility. E.g., : 1. "Base" package is installed: subcommand available is "view-config " : 2. "Base" and "database" package are installed, subcommands : available are "view-config" and "backup-db" : 4. Support for executing remote commands via ssh : I have no doubt that with enough effort, a Python application could be : developed to implement the above. : However, I'm not too sure if Python is the right tools for the job : particularly about point 3: : : 1. Is there a built-in discovery mechanism like Java SPI : (http://docs.oracle.com/javase/tutorial/sound/SPI-intro.html)? I don't know SPI, and this link didn't help me understand quite what you meant by discovery. Flexible discovery is very difficult. : 2. Are there any libraries/framework we could build upon or would we need : to start from scratch? Yes. In elements 1. and 3. above, it sounds almost like you are describing the features of argparse (available for Python 2.x and 3.x). See documentation here: https://docs.python.org/2/library/argparse.html https://docs.python.org/3/library/argparse.html I think item 2. about bash_completion bit is outside the scope of Python, specifically, though, and more of an operating environment thing. : 3. Should we consider 2.x or 3.x in order to ensure cross system : compatibility (linux, windows)? Others may chime in on this. I, personally, will choose what my platform chooses (still Python-2.x), so I'm a "behind the adoption curve" kind of guy. You also mentioned, in item 4. above about ssh. It's hard to have completion oriented tools and (reliable) remote execution support without a uniformly administered set of systems. Of course, you can call ssh from Python, but in this case, it seems like you'd have a simpler system by leaving the ssh out of the mix. If you want to use ssh from Python, there's paramiko. https://pypi.python.org/pypi/paramiko/ : Any feedback on any of the points above would be greatly appreciated. I don't know if this is the sort of feedback that you were looking for, so I'll just stop there. Good luck, -Martin From __peter__ at web.de Thu Aug 21 19:12:37 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 21 Aug 2014 19:12:37 +0200 Subject: [Tutor] Development of administration utility References: <53F5D17A.1070305@gmail.com> Message-ID: Martin A. Brown wrote: > I think item 2. about bash_completion bit is outside the scope of > Python, specifically, though, and more of an operating environment > thing. I have recently (re)discovered that there is an easy way to get bash completion: https://pypi.python.org/pypi/argcomplete I'm in the process of adding try: import argcomplete except ImportError: pass else: argcomplete.autocomplete(parser) to every script I touch. So far it works great. From japhy at pearachute.com Thu Aug 21 17:43:20 2014 From: japhy at pearachute.com (Japhy Bartlett) Date: Thu, 21 Aug 2014 10:43:20 -0500 Subject: [Tutor] Development of administration utility In-Reply-To: <53F5D17A.1070305@gmail.com> References: <53F5D17A.1070305@gmail.com> Message-ID: You could definitely achieve that modularity, if the parent package knows (by convention) where to look for sub-modules. I'm not sure there's a built-in mechanism, unless you want to use 'import' in a clever way. It feels like that's more of a RPM/.deb challenge than a Python challenge. There are command line parsing libraries built-in to the language: https://docs.python.org/2/library/optparse.html 2x / 3x is a bit of a religious war at the moment.. Probably either one is fine, but 2x is installed by default on more systems. - Japhy On Thu, Aug 21, 2014 at 6:01 AM, Alessandro Di Bella < alessandro.dibella at gmail.com> wrote: > Hi, > > We are currently investigating different languages and technologies to > develop an command line administration utility. > Python is one of the options we are looking at for the job but currently > we have no relevant skill set so I thought I'd post some question to get an > idea if using python is something worth pursuing or not. > > The utility should have the following characteristics: > > 1. support for sub commands and parameters (e.g. svn or git) > 2. integration with bash_completion > 3. Modular. The idea would be that by installing different packages > (or RPMs), new sub-commands and parameters will be made available to the > utility. E.g., > 1. "Base" package is installed: subcommand available is "view-config " > 2. "Base" and "database" package are installed, subcommands > available are "view-config" and "backup-db" > 4. Support for executing remote commands via ssh > > I have no doubt that with enough effort, a Python application could be > developed to implement the above. > However, I'm not too sure if Python is the right tools for the job > particularly about point 3: > > 1. Is there a built-in discovery mechanism like Java SPI ( > http://docs.oracle.com/javase/tutorial/sound/SPI-intro.html)? > 2. Are there any libraries/framework we could build upon or would we > need to start from scratch? > 3. Should we consider 2.x or 3.x in order to ensure cross system > compatibility (linux, windows)? > > Any feedback on any of the points above would be greatly appreciated. > > Regards, > > Alessandro > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Thu Aug 21 19:23:13 2014 From: emile at fenx.com (Emile van Sebille) Date: Thu, 21 Aug 2014 10:23:13 -0700 Subject: [Tutor] import values, calculate distance In-Reply-To: References: <1408587130.81435.YahooMailNeo@web161304.mail.bf1.yahoo.com> Message-ID: On 8/21/2014 6:13 AM, Joel Goldstick wrote:> On Wed, Aug 20, 2014 at 10:12 PM, LN A-go-go > wrote: > while you can name things like this, good python style (look up > 'pep8') says this would be better > id_code, x_coordinate, y_coordinate > > But better yet, I think would be to call these things: > id, x, y > Minor nit: better still would be: code, x, y so as not to shadow the builtin id Emile From emile at fenx.com Thu Aug 21 19:30:06 2014 From: emile at fenx.com (Emile van Sebille) Date: Thu, 21 Aug 2014 10:30:06 -0700 Subject: [Tutor] import values, calculate distance In-Reply-To: References: <1408587130.81435.YahooMailNeo@web161304.mail.bf1.yahoo.com> Message-ID: On 8/21/2014 6:13 AM, Joel Goldstick wrote:> On Wed, Aug 20, 2014 at 10:12 PM, LN A-go-go > wrote: > while you can name things like this, good python style (look up > 'pep8') says this would be better > id_code, x_coordinate, y_coordinate > > But better yet, I think would be to call these things: > id, x, y > Minor nit: better still would be: code, x, y so as not to shadow the builtin id Emile From alan.gauld at btinternet.com Thu Aug 21 19:35:07 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Aug 2014 18:35:07 +0100 Subject: [Tutor] Development of administration utility In-Reply-To: <53F5D17A.1070305@gmail.com> References: <53F5D17A.1070305@gmail.com> Message-ID: On 21/08/14 12:01, Alessandro Di Bella wrote: > We are currently investigating different languages and technologies to > develop an command line administration utility. For what? Operating under which environments? > The utility should have the following characteristics: > > 1. support for sub commands and parameters (e.g. svn or git) Can you elaborate? Do you mean subcommands modelled after how git/svn work or do you mean sub commands of git/svn? In other words are you trying to control external commands from your application or simply work in the same/similar ways? Take a look at the cmd module and see if it meets your needs.... > 2. integration with bash_completion I'm not clear what you expect here. What if your user does not use bash? What should the app do then? Is this a *nix only app or does it have to work on Windows with the cmd shell too? > 3. Modular. The idea would be that by installing different packages (or > RPMs), new sub-commands and parameters will be made available to the > utility. E.g., Are you planning on using the application to install the packages or are you expecting the app to read the installed package data from the package manager? What happens if multiple package managers are used? What about things installed from source? > 1. "Base" package is installed: subcommand available is "view-config " > 2. "Base" and "database" package are installed, subcommands > available are "view-config" and "backup-db" > 4. Support for executing remote commands via ssh This bit should be straightforward. > I have no doubt that with enough effort, a Python application could be > developed to implement the above. > However, I'm not too sure if Python is the right tools for the job > particularly about point 3: That depends on what you intend point 3 to mean. See the comments above. > 1. Is there a built-in discovery mechanism like Java SPI > (http://docs.oracle.com/javase/tutorial/sound/SPI-intro.html)? > 2. Are there any libraries/framework we could build upon or would we > need to start from scratch? There are hundreds of libraries and dozens of frameworks from networking through GUIs and domain specific tools. Whether any of them come close to what you want is not yet clear. > 3. Should we consider 2.x or 3.x in order to ensure cross system > compatibility (linux, windows)? The Python version doesn't make much difference for cross platform issues, at least for the standard library. For maximium third party support you should go with Python 2.x, especially as its often installed by default on the OS already. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Thu Aug 21 20:45:24 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 21 Aug 2014 11:45:24 -0700 Subject: [Tutor] Development of administration utility In-Reply-To: <53F5D17A.1070305@gmail.com> References: <53F5D17A.1070305@gmail.com> Message-ID: On Aug 21, 2014 7:39 AM, "Alessandro Di Bella" wrote: > > Hi, > > We are currently investigating different languages and technologies to develop an command line administration utility. Hi Alessandro, This is out of scope for Python Tutor. This is not to say that the question is not interesting, but it is not a beginner question. I think you can get better advice if you try asking on a system administration forum. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mimiouyang at hotmail.com Fri Aug 22 04:43:20 2014 From: mimiouyang at hotmail.com (Mimi Ou Yang) Date: Fri, 22 Aug 2014 02:43:20 +0000 Subject: [Tutor] =?utf-8?q?Question_about_if_functions?= Message-ID: name = input("Enter your name: ) age = input("Enter your age: ) age = int(age) if (name and age == jimmy and 35): print ("BLABLABLABLABLABLAB") how can I make a code that has the same effect has the code that I wrote even though it isn?t a real working code. I hope you understand this code. Basically, it asks you your name and age. And then, if (the name input and the age input) == (jimmy and 35): it prints blablablablablabl -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Aug 22 07:47:22 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 22 Aug 2014 06:47:22 +0100 Subject: [Tutor] Question about if functions In-Reply-To: References: Message-ID: On 22/08/14 03:43, Mimi Ou Yang wrote: > name = input("Enter your name: ) > age = input("Enter your age: ) > age = int(age) > > if (name and age == jimmy and 35): > print ("BLABLABLABLABLABLAB") > There are two problems here. First You need to put quote signs around 'jimmy' since its a literal string, not a variable. Second, and more fundamental, Python sees your if test like this: if (name and age) == ('jimmy' and 35) Which Python always sees as True == True which is always True. You need to rewrite it like: if (name == 'jimmy') and (age == 35): The parentheses are not strictly needed, I've just used them to show how #Python reads it, In this specific case you can shorten it slightly to: if (name,age) == ('jimmy',35): but most programmers prefer the first style since its more flexible and maintainable (the tuple style only works for and tests) hth, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Fri Aug 22 17:25:38 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Aug 2014 01:25:38 +1000 Subject: [Tutor] Question about if functions In-Reply-To: References: Message-ID: <20140822152538.GT25957@ando> On Fri, Aug 22, 2014 at 02:43:20AM +0000, Mimi Ou Yang wrote: > if (name and age == jimmy and 35): > print ("BLABLABLABLABLABLAB") if name == 'jimmy' and age == 35: print("BLAB") or if you prefer: if (name, age) == ("jimmy", 35): print("BLAB") Take careful note that strings like "jimmy" have to be quoted, otherwise Python will look for a variable jimmy. -- Steven From atp2gr at yahoo.co.uk Fri Aug 22 15:48:50 2014 From: atp2gr at yahoo.co.uk (atp2gr at yahoo.co.uk) Date: Fri, 22 Aug 2014 13:48:50 +0000 Subject: [Tutor] =?utf-8?q?Please_get_me_started_in_django?= Message-ID: <375d9d83e0154a89b97a8da778add02f@yahoo.co.uk> Hi I have developed a python maths game in 2.7 and want to try and run it from the web. PLEASE can you guide me in getting started. Im not very familiar with command line operations. I have installed python 3.4 does that help. If this is not the best place to get help with django can you recommend an interactive site. Thanks Peter Sent from Windows Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Aug 22 20:51:38 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 22 Aug 2014 14:51:38 -0400 Subject: [Tutor] Please get me started in django In-Reply-To: <375d9d83e0154a89b97a8da778add02f@yahoo.co.uk> References: <375d9d83e0154a89b97a8da778add02f@yahoo.co.uk> Message-ID: On Fri, Aug 22, 2014 at 9:48 AM, wrote: > Hi > > I have developed a python maths game in 2.7 and want to try and run it from > the web. PLEASE can you guide me in getting started. Im not very familiar > with command line operations. > > I have installed python 3.4 does that help. > > If this is not the best place to get help with django can you recommend an > interactive site. > Start here: https://www.djangoproject.com/ The site has installation instructions, tutorial, detailed documentation and lists of other resources There is also a django-users mailing list. Sorry I don't know the url offhand > Thanks > > Peter > > Sent from Windows Mail > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From fomcl at yahoo.com Fri Aug 22 23:10:21 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 22 Aug 2014 14:10:21 -0700 Subject: [Tutor] simple unicode question Message-ID: <1408741821.17328.YahooMailNeo@web163801.mail.gq1.yahoo.com> Hi, I have data that is either floats or byte strings in utf-8. I need to cast both to unicode strings. I am probably missing something simple, but.. in the code below, under "float", why does [B] throw an error but [A] does not? # Python 2.7.3 (default, Feb 27 2014, 19:39:10) [GCC 4.7.2] on linux2 >>> help(unicode) Help on class unicode in module __builtin__: class unicode(basestring) ?|? unicode(string [, encoding[, errors]]) -> object ?|? ?|? Create a new Unicode object from the given encoded string. ?|? encoding defaults to the **current default string encoding**. ?|? errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'. # ... >>> import sys >>> sys.getdefaultencoding() 'ascii' # float: cannot explicitly give encoding, even if it's the default >>> value = 1.0 >>> unicode(value)????? # [A] u'1.0' >>> unicode(value, sys.getdefaultencoding())? # [B] Traceback (most recent call last): ? File "", line 1, in ??? unicode(value, sys.getdefaultencoding()) TypeError: coercing to Unicode: need string or buffer, float found >>> unicode(value, "utf-8") # (... also TypeError) # byte string: must explicitly give encoding (which makes perfect sense) >>> value = '\xc3\xa9' >>> unicode(value) Traceback (most recent call last): ? File "", line 1, in ??? unicode(value) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) >>> unicode(value, "utf-8") u'\xe9' Thank you! Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From zebra05 at gmail.com Fri Aug 22 23:23:40 2014 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Fri, 22 Aug 2014 23:23:40 +0200 Subject: [Tutor] Preparing virtualenvwrapper for Django 1.6 development Message-ID: Hi everyone, I am developing on a Windows 8.1 machine and wold like to setup virtualenvironment via virtualenvwrapper so as to have a properly set up Python development environment. I am referring to Jeff Knupp's guide at http://www.jeffknupp.com/blog/2013/12/18/starting-a-django-16-project-the-right-way/ After installation of virtualenvwrapper via pip, the guide says: " After it's installed, add the following lines to your shell's start-up file (.zshrc, .bashrc, .profile, etc). export WORKON_HOME=$HOME/.virtualenvs export PROJECT_HOME=$HOME/directory-you-do-development-in source /usr/local/bin/virtualenvwrapper.sh " My issue is, I do not understand what these lines are doing (I have a vague idea but assumptions can be deadly). Moreover, it is clear that the instructions were authored with a UNIX environment in mind. Would anyone be so kind as to translate this to Windows speak, as well as perhaps pointing out what file this would go into in a Windows environment? Thanks in advance :) Kind regards, Sithu. -- Regards, Sithu Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Sat Aug 23 00:08:21 2014 From: davea at davea.name (Dave Angel) Date: Fri, 22 Aug 2014 18:08:21 -0400 (EDT) Subject: [Tutor] simple unicode question References: <1408741821.17328.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam Wrote in message: > Hi, > > I have data that is either floats or byte strings in utf-8. I need to cast both to unicode strings. I am probably missing something simple, but.. in the code below, under "float", why does [B] throw an error but [A] does not? > >.......... >>>> unicode(value, sys.getdefaultencoding()) # [B] > > Traceback (most recent call last): > File "", line 1, in > unicode(value, sys.getdefaultencoding()) > TypeError: coercing to Unicode: need string or buffer, float found >>>> unicode(value, "utf-8") > # (... also TypeError) > Unicode has no encoding, so trying to specify one during a float conversion is nonsensical. Only byte-strings have encodings. You decode them to Unicode, and the result has no encoding. -- DaveA From dyoo at hashcollision.org Sat Aug 23 02:53:14 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 22 Aug 2014 17:53:14 -0700 Subject: [Tutor] simple unicode question In-Reply-To: <1408741821.17328.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <1408741821.17328.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On Fri, Aug 22, 2014 at 2:10 PM, Albert-Jan Roskam wrote: > Hi, > > I have data that is either floats or byte strings in utf-8. I need to cast both to unicode strings. Just to be sure, I'm parsing the problem statement above as: data :== float | utf-8-encoded-byte-string because the alternative way to parse the statement in English: data :== float-in-utf-8 | byte-string-in-utf-8 doesn't make any technical sense. :P > I am probably missing something simple, but.. in the code below, under "float", why does [B] throw an error but [A] does not? > > # float: cannot explicitly give encoding, even if it's the default >>>> value = 1.0 >>>> unicode(value) # [A] > u'1.0' >>>> unicode(value, sys.getdefaultencoding()) # [B] > > Traceback (most recent call last): > File "", line 1, in > unicode(value, sys.getdefaultencoding()) > TypeError: coercing to Unicode: need string or buffer, float found Yeah. Unfortunately, you're right: this doesn't make too much sense. What's happening is that the standard library overloads two _different_ behaviors to the same function unicode(). It's conditioned on whether we're passing in a single value, or if we're passing in two. I would not try to reconcile a single, same behavior for both uses: treat them as two distinct behaviors. Reference: https://docs.python.org/2/library/functions.html#unicode Specifically, the two arg case is meant where you've got an uninterpreted source of bytes that should be decoded to Unicode using the provided encoding. So for your problem statement, the function should look something like: ############################### def convert(data): if isinstance(data, float): return unicode(data) if isinstance(data, bytes): return unicode(data, "utf-8") raise ValueError("Unexpected data", data) ############################### where you must use unicode with either the 1-arg or 2-arg variant based on your input data. From dyoo at hashcollision.org Sat Aug 23 03:07:15 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 22 Aug 2014 18:07:15 -0700 Subject: [Tutor] simple unicode question In-Reply-To: References: <1408741821.17328.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: Hi Albert, Just following up: I consider the 2 (or 3) arg form of unicode() to be a design flaw in the Standard Library. It's redundant because the bytes type already has a decode() method: https://docs.python.org/3/library/stdtypes.html#bytes.decode So I would personally write convert() like this: ###################################### def convert(data): if isinstance(data, float): return unicode(data) if isinstance(data, bytes): return data.decode("utf-8") raise ValueError("Unexpected data", data) ###################################### From ben+python at benfinney.id.au Sat Aug 23 03:27:07 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 23 Aug 2014 11:27:07 +1000 Subject: [Tutor] simple unicode question References: <1408741821.17328.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: <857g20yp04.fsf@benfinney.id.au> Danny Yoo writes: > Hi Albert, > > Just following up: I consider the 2 (or 3) arg form of unicode() to be > a design flaw in the Standard Library. It's redundant because the > bytes type already has a decode() method: > > https://docs.python.org/3/library/stdtypes.html#bytes.decode > > > So I would personally write convert() like this: > > ###################################### > def convert(data): > if isinstance(data, float): > return unicode(data) > if isinstance(data, bytes): > return data.decode("utf-8") > raise ValueError("Unexpected data", data) > ###################################### Since the type of ?data? is the only thing which determines whether an error is raised, the error message might be improved by stating the type:: def convert(data): if isinstance(data, float): return unicode(data) if isinstance(data, bytes): return data.decode("utf-8") raise ValueError( "Unexpected type {type} for data {data!r}".format( type=type(data), data=data)) which makes the errors more self-explanatory, IMO:: >>> convert(17.3) '17.3' >>> convert(b'\x53\x70\x61\x6d') 'Spam' >>> convert(12) Traceback (most recent call last): File "", line 1, in File "", line 9, in convert ValueError: Unexpected type for data 12 >>> convert('Spam') Traceback (most recent call last): File "", line 1, in File "", line 9, in convert ValueError: Unexpected type for data 'Spam' -- \ ?Anyone who puts a small gloss on [a] fundamental technology, | `\ calls it proprietary, and then tries to keep others from | _o__) building on it, is a thief.? ?Tim O'Reilly, 2000-01-25 | Ben Finney From steve at pearwood.info Sat Aug 23 03:56:53 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Aug 2014 11:56:53 +1000 Subject: [Tutor] simple unicode question In-Reply-To: <1408741821.17328.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <1408741821.17328.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: <20140823015653.GW25957@ando> On Fri, Aug 22, 2014 at 02:10:21PM -0700, Albert-Jan Roskam wrote: > Hi, > > I have data that is either floats or byte strings in utf-8. I need to > cast both to unicode strings. I am probably missing something simple, > but.. in the code below, under "float", why does [B] throw an error > but [A] does not? Unicode in Python 2 is a little more confusing than in Python 3. But let's see what is going on: > >>> value = 1.0 > >>> unicode(value)????? # [A] > u'1.0' This works for the same reason that str(value) works. By definition, the value 1.0 can only be converted into a single [text or byte] string, namely 1.0. (Well, to be absolutely pedantic, Python could support other languages, like ?.? which is Arabic, but it doesn't.) > >>> unicode(value, sys.getdefaultencoding())? # [B] > > Traceback (most recent call last): > ? File "", line 1, in > ??? unicode(value, sys.getdefaultencoding()) > TypeError: coercing to Unicode: need string or buffer, float found Here, on the other hand, unicode sees that you are providing a second argument, so it expects a string or buffer object, but gets a float so it raises an error. You're probably thinking something along these lines: "Unicode strings need an encoding, so I want to convert 1.0 into Unicode using the ASCII encoding (or the UTF-8 encoding)" but that's not how it works. Unicode strings DON'T need an encoding. The Unicode string "1.0", or for that matter "????", is a string of exactly those characters and nothing else. In the same way that ASCII defines 127 characters, including A, B, C, ... Unicode defines (up to) 1114112 characters. There's no need to specify an encoding, because Unicode *is* the encoding. You only need to use an encoding when converting from Unicode to bytes, or visa versa. -- Steven From kwpolska at gmail.com Sat Aug 23 09:54:13 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sat, 23 Aug 2014 09:54:13 +0200 Subject: [Tutor] Preparing virtualenvwrapper for Django 1.6 development In-Reply-To: References: Message-ID: On Fri, Aug 22, 2014 at 11:23 PM, Sithembewena Lloyd Dube wrote: > Hi everyone, > > I am developing on a Windows 8.1 machine and wold like to setup > virtualenvironment via virtualenvwrapper so as to have a properly set up > Python development environment. > > I am referring to Jeff Knupp's guide at > http://www.jeffknupp.com/blog/2013/12/18/starting-a-django-16-project-the-right-way/ > > After installation of virtualenvwrapper via pip, the guide says: > " > After it's installed, add the following lines to your shell's start-up file > (.zshrc, .bashrc, .profile, etc). > > export WORKON_HOME=$HOME/.virtualenvs > export PROJECT_HOME=$HOME/directory-you-do-development-in > source /usr/local/bin/virtualenvwrapper.sh > " > > My issue is, I do not understand what these lines are doing (I have a vague > idea but assumptions can be deadly). Moreover, it is clear that the > instructions were authored with a UNIX environment in mind. > > Would anyone be so kind as to translate this to Windows speak, as well as > perhaps pointing out what file this would go into in a Windows environment? virtualenvwrapper does not work in Windows. You should use regular virtualenv instead. Read this: http://virtualenv.readthedocs.org/en/latest/virtualenv.html#usage Note that this blog post is HEAVILY *nix-specific, and that Windows is a bad environment for Python development (especially Web development). I personally recommend you just get a virtual machine running some Linux instead of playing with Windows. -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From alan.gauld at btinternet.com Sat Aug 23 21:37:04 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Aug 2014 20:37:04 +0100 Subject: [Tutor] Preparing virtualenvwrapper for Django 1.6 development In-Reply-To: References: Message-ID: On 23/08/14 08:54, Chris ?Kwpolska? Warrick wrote: > Note that this blog post is HEAVILY *nix-specific, and that Windows is > a bad environment for Python development (especially Web development). While I wouldn't say its the best environment I don't think its fair to say Windows is "a bad environment for Python". Any experienced Windows programmer will find it much easier to use Python on Windows than to learn a whole new OS and development environment. And if they use the ActiveState version of Python (or IronPython) they should feel quite at home. OTOH If they already know Linux and have a choice then I'd agree *nix is a better match. But modern Windows (post Win2k say) is not so bad that you need a new OS. IMHO at least. [ And for context, I run Linux on my main desktop, MacOS on my laptop, and Windows 8.1 on a second desktop - used mainly for photography/video processing. And I use Python on all 3 of them) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From mimiouyang at hotmail.com Sat Aug 23 16:16:11 2014 From: mimiouyang at hotmail.com (Mimi Ou Yang) Date: Sat, 23 Aug 2014 14:16:11 +0000 Subject: [Tutor] =?utf-8?q?Shorter_way_for_a_little_program?= Message-ID: age = input("K") age = int(age) if (age == 1) or (age == 2) or (age == 3) or (age == 4): print ("LOL") else: print ("K") Is there a shorter way to do this program??? -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sat Aug 23 21:49:09 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 23 Aug 2014 15:49:09 -0400 Subject: [Tutor] Shorter way for a little program In-Reply-To: References: Message-ID: On Sat, Aug 23, 2014 at 10:16 AM, Mimi Ou Yang wrote: > age = input("K") > > age = int(age) > > if (age == 1) or (age == 2) or (age == 3) or (age == 4): > print ("LOL") > > else: > print ("K") > > > > Is there a shorter way to do this program??? > age = int(input("K")) if age in (1,2,3,4): print "LOL") else: print age # or do you really want to print "K" ? > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From alan.gauld at btinternet.com Sat Aug 23 21:54:59 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Aug 2014 20:54:59 +0100 Subject: [Tutor] Shorter way for a little program In-Reply-To: References: Message-ID: On 23/08/14 15:16, Mimi Ou Yang wrote: > age = input("K") > age = int(age) > if (age == 1) or (age == 2) or (age == 3) or (age == 4): > print ("LOL") > else: > print ("K") > > Is there a shorter way to do this program??? Yes you could do this: print('LOL' if int(input('K')) in (1,2,3,4) else 'K') Its shorter, but it suffers from the usual problems of being shorter: 1) Its much harder to debug if it goes wrong 2) Almost any modifications are much harder. Having said that there are some valid reductions you could consider: age = int(input("K")) if age in (1,2,3,4): # or: if 1 <= age <= 4: print ("LOL") else: print ("K") HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From kwpolska at gmail.com Sun Aug 24 17:37:37 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sun, 24 Aug 2014 17:37:37 +0200 Subject: [Tutor] Preparing virtualenvwrapper for Django 1.6 development In-Reply-To: References: Message-ID: On Sat, Aug 23, 2014 at 9:37 PM, Alan Gauld wrote: > While I wouldn't say its the best environment I don't think its > fair to say Windows is "a bad environment for Python". Any > experienced Windows programmer will find it much easier to use Python on > Windows than to learn a whole new OS and development environment. There are various pitfalls that happen on Windows and that don?t on Linux. Some packages outright assume Windows does not exist, and this leads to failing code. In other cases, you must compile a C extension, which is not easy to configure ? and not ever package has wheels/.exes available? Linux tries to follow POSIX standards, and also acknowledges people may want to be programmers. Also, OP did not state whether they are experienced Windows programmers, experienced platform-independent programmers or newcomers to programming in general. > [ And for context, I run Linux on my main desktop, MacOS on my > laptop, and Windows 8.1 on a second desktop - used mainly for > photography/video processing. And I use Python on all 3 of them) context: I have a dual-boot Arch Linux/Windows 7 system. Python installed on both OSes (and even in some Windows VMs). -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From mimiouyang at hotmail.com Sun Aug 24 16:11:34 2014 From: mimiouyang at hotmail.com (Mimi Ou Yang) Date: Sun, 24 Aug 2014 14:11:34 +0000 Subject: [Tutor] =?utf-8?q?NameError?= Message-ID: name = input("Enter your name: ") age = int(input("Enter your age: ")) gb = input("Are you a boy or a girl? ") op = input("How are you feeling today? ") if (age in (1,2,3,4,5,6,7,8,9,10,11,12)): print (name,"you are a little",gb,"that is feeling",op,"today.") if (age in (13,14,15,16,17)): print (name,"you are a teenage",gb,"that is feeling",op,"today.") if (age in (18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33)) and (gb == boy): print (name,"you are a young man that is feeling",op,"today.") if (age in (18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33)) and (gb == girl): print (name,"you are a young woman that is feeling",op,"today.") if (age in (34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56)) and (gb == boy): print (name,"you are a man that is feeling",op,"today.") if (age in (34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56)) and (gb == girl): print (name,"you are a woman that is feeling",op,"today.") if (age >= 56) and (gb == boy): print (name,"you are a grandpa that is feeling",op,"today.") if (age >= 56) and (gb == girl): print (name,"you are a grandma that is feeling",op,"today.") when I run it it says: Enter your name: jimmy Enter your age: 45 Are you a boy or a girl? boy How are you feeling today? good Traceback (most recent call last): File "C:\Users\Jimmy\Desktop\Python\3.4.1 Projects\TEST1.py", line 21, in if (age in (34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56)) and (gb == boy): NameError: name 'boy' is not defined >>> can you tell me what should I do -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Aug 24 20:39:32 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Aug 2014 19:39:32 +0100 Subject: [Tutor] NameError In-Reply-To: References: Message-ID: On 24/08/14 15:11, Mimi Ou Yang wrote: > age = int(input("Enter your age: ")) > gb = input("Are you a boy or a girl? ") input() returns a string so the values here should be 'boy' or 'girl' - Notice the quote signs. > op = input("How are you feeling today? ") > > if (age in (1,2,3,4,5,6,7,8,9,10,11,12)): > print (name,"you are a little",gb,"that is feeling",op,"today.") If you are using loing sequences of values you should consider using the range() function instead or use a comparison check: either if age in (range(1,13): # last value not included or if 1 <= age <= 12: Its less typing and easier to see the intention. For small numbers of values the tuple approach is fine but once you get more than say, 7 values its harder to read. The exception is if you are testing for non contiguous values, in that case an explicit tuple will be needed. > if (age in (18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33)) and (gb == > boy): Notice that you are testing .... and (gb == boy): no quotes so Python looks for a variable called boy. > if (age in (18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33)) and (gb == > girl): The same here for girl > (34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56)) > and (gb == boy): > NameError: name 'boy' is not defined > >>> So use quotes when testing for string values you might also like to force the input to lowercase so that users can type Boy or BOY if they wish: .... (gb.lower() == 'boy') HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From emile at fenx.com Sun Aug 24 22:25:17 2014 From: emile at fenx.com (Emile van Sebille) Date: Sun, 24 Aug 2014 13:25:17 -0700 Subject: [Tutor] Shorter way for a little program In-Reply-To: References: Message-ID: On 8/23/2014 7:16 AM, Mimi Ou Yang wrote: > age = input("K") > > age = int(age) > > if (age == 1) or (age == 2) or (age == 3) or (age == 4): > print ("LOL") > > else: > print ("K") > > > > Is there a shorter way to do this program??? print ('LOL','K')[int(input("k"))>4] From alan.gauld at btinternet.com Mon Aug 25 01:01:14 2014 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 25 Aug 2014 00:01:14 +0100 Subject: [Tutor] NameError In-Reply-To: References: Message-ID: <1408921274.94610.YahooMailNeo@web186004.mail.ir2.yahoo.com> forwarding to the group. Please use ReplyAll when responding to the list. ? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos >________________________________ > From: D.V.N.Sarma ??.??.???.???? >To: Alan Gauld >Sent: Sunday, 24 August 2014, 23:54 >Subject: Re: [Tutor] NameError > > > >In the six places you have gb == boy or gb == girl, put 'boy' and 'girl'. >I did and it works. > > >regards, >Sarma. > > >On Mon, Aug 25, 2014 at 12:09 AM, Alan Gauld wrote: > >On 24/08/14 15:11, Mimi Ou Yang wrote: >> >> >>age = int(input("Enter your age: ")) >>>gb = input("Are you a boy or a girl? ") >>> >> input() returns a string so the values here >>should be 'boy' or 'girl' - Notice the quote signs. >> >> >> >>op = input("How are you feeling today? ") >>> >>>if (age in (1,2,3,4,5,6,7,8,9,10,11,12)): >>>? ? ?print (name,"you are a little",gb,"that is feeling",op,"today.") >>> >> If you are using loing sequences of values you should consider using the range() function instead or use a comparison check: >> >>either >> >>if age in (range(1,13):? ? # last value not included >> >>or >> >>if 1 <= age <= 12: >> >>Its less typing and easier to see the intention. >>For small numbers of values the tuple approach is >>fine but once you get more than say, 7 values its >>harder to read. >> >>The exception is if you are testing for non >>contiguous values, in that case an explicit tuple >>will be needed. >> >> >> >>if (age in (18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33)) and (gb == >>>boy): >>> >> Notice that you are testing >> >>.... and (gb == boy): >> >>no quotes so Python looks for a variable called boy. >> >> >> >> >>if (age in (18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33)) and (gb == >>>girl): >>> >> The same here for girl >> >> >> >> >>(34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56)) >>>and (gb == boy): >>>NameError: name 'boy' is not defined >>>?>>> >>> >> So use quotes when testing for string values >> >>you might also like to force the input to lowercase so that users can type Boy or BOY if they wish: >> >>.... (gb.lower() == 'boy') >> >>HTH >>-- >>Alan G >>Author of the Learn to Program web site >>http://www.alan-g.me.uk/ >>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 >> > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From akleider at sonic.net Mon Aug 25 02:23:35 2014 From: akleider at sonic.net (Alex Kleider) Date: Sun, 24 Aug 2014 17:23:35 -0700 Subject: [Tutor] Using unittest module for Test Driven Development Message-ID: Given $ cat compare.py #!/usr/bin/env python3 import os import sys def get_args(): try: args = sys.argv[1:] except IndexError: return return [arg for arg in args if os.path.isfile(arg)] if __name__ == "__main__": print(get_args()) How can one unittest get_args()? It seems to me that 'unittest'ing only works to test functions and methods, not programs. Here's my attempt at a testing module: $ cat testing.py #!/usr/bin/env python3 import unittest import compare_sizes class CompareTesting(unittest.TestCase): def setUp(self): pass def test_nothing(self): self.assertEqual(not False, True) def test_get_file_param(self): self.assertTrue(compare_sizes.get_args() == ['file1', 'file2']) if __name__ == '__main__': unittest.main() Is there a way that I can provide the file name command line parameters to compare.py so that its get_args function can be tested? Thanks in advance for any advice. AlexK ps I'm on Ubuntu14.4, using Python3.4.0 From steve at pearwood.info Mon Aug 25 03:57:17 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 25 Aug 2014 11:57:17 +1000 Subject: [Tutor] Using unittest module for Test Driven Development In-Reply-To: References: Message-ID: <20140825015717.GL25957@ando> On Sun, Aug 24, 2014 at 05:23:35PM -0700, Alex Kleider wrote: > Given > $ cat compare.py > #!/usr/bin/env python3 > import os > import sys > > def get_args(): > try: > args = sys.argv[1:] > except IndexError: > return > return [arg for arg in args if os.path.isfile(arg)] The try...except block is redundant, because you are taking a slice, not an index, it cannot fail. If the bounds are outside of the actual list, the empty list is returned: py> [1, 2][100:1000] [] By the way, is there significance to the name "compare.py"? Because it's not really doing any comparisons... > if __name__ == "__main__": > print(get_args()) > > How can one unittest get_args()? > It seems to me that 'unittest'ing only works to test functions and > methods, not programs. Well, technically "unit testing" refers to testing individual "units" (that is, classes, functions, modules etc.) of a program, not the entire program all at once. But it's also flexible enough to test the entire program. To test get_args() alone, I would do something like this: import sys import unittest import compare class Test_Get_Args(unittest.TestCase): def setUp(self): # Create some known files. open('/tmp/aaa', 'w').close() open('/tmp/bbb', 'w').close() # Make sure another file doesn't exist. if os.path.exists('/tmp/ccc'): os.unlink('/tmp/ccc') def tearDown(self): # Clean up once we're done. for file in ('/tmp/aaa', '/tmp/bbb'): if os.path.exists(file): os.unlink(file) def test_existing_files(self): sys.argv = ['testing', '/tmp/aaa', '/tmp/bbb'] result = compare.get_args() self.assertEqual(result, ['/tmp/aaa', '/tmp/bbb']) def test_nonexisting_files(self): sys.argv = ['testing', '/tmp/ccc'] result = compare.get_args() self.assertEqual(result, []) def test_not_files(self): sys.argv = ['testing', '/tmp', '/'] result = compare.get_args() self.assertEqual(result, []) The paths I used are suitable for Unix, Linux or Mac. You will need to adapt them for Windows. To avoid having to write to sys.argv, give your get_args function an optional argument: def get_args(args=None): if args is None: args = sys.argv[1:] return [arg for arg in args if os.path.isfile(arg)] then in your tests, just pass the list directly to the function. > Here's my attempt at a testing module: > $ cat testing.py > #!/usr/bin/env python3 > import unittest > import compare_sizes What's compare_sizes ? > class CompareTesting(unittest.TestCase): > > def setUp(self): > pass If you're not doing anything in setUp, just don't override the method. The default method does nothing, so you don't need this. > def test_nothing(self): > self.assertEqual(not False, True) What is the purpose of this test? How is it testing *your* code? That would be necessary as a test of Python's built-ins. > def test_get_file_param(self): > self.assertTrue(compare_sizes.get_args() == ['file1', 'file2']) You should use assertEqual(a, b) rather than assertTrue(a == b). > if __name__ == '__main__': > unittest.main() > > Is there a way that I can provide the file name command line parameters > to compare.py so that its get_args function can be tested? sys.argv is writeable, or better still, provide get_args() an optional argument to use instead of sys.argv. -- Steven From akleider at sonic.net Mon Aug 25 05:20:26 2014 From: akleider at sonic.net (Alex Kleider) Date: Sun, 24 Aug 2014 20:20:26 -0700 Subject: [Tutor] Using unittest module for Test Driven Development In-Reply-To: <20140825015717.GL25957@ando> References: <20140825015717.GL25957@ando> Message-ID: <3afd8e4f91ccc8737b4b6df0bee328d3@sonic.net> Thank you very much, Steven. This is just the help I needed. Forgive me for causing confusion- I pared down my code for presentation but not enough and also left the names which now out of context, don't make sense. In line explanations provided below although it would probably be of little interest. You did ask so I feel I owe you an explanation. Gratefully, Alex On 2014-08-24 18:57, Steven D'Aprano wrote: > On Sun, Aug 24, 2014 at 05:23:35PM -0700, Alex Kleider wrote: >> Given >> $ cat compare.py >> #!/usr/bin/env python3 >> import os >> import sys >> >> def get_args(): >> try: >> args = sys.argv[1:] >> except IndexError: >> return >> return [arg for arg in args if os.path.isfile(arg)] > > The try...except block is redundant, because you are taking a slice, > not > an index, it cannot fail. If the bounds are outside of the actual list, > the empty list is returned: > > py> [1, 2][100:1000] > [] This I did not know. Good to know. > > > By the way, is there significance to the name "compare.py"? Because > it's > not really doing any comparisons... That's the ultimate goal of the script but I've a ways to go before that is evident! > > >> if __name__ == "__main__": >> print(get_args()) >> >> How can one unittest get_args()? >> It seems to me that 'unittest'ing only works to test functions and >> methods, not programs. > > > Well, technically "unit testing" refers to testing individual "units" > (that is, classes, functions, modules etc.) of a program, not the > entire > program all at once. But it's also flexible enough to test the entire > program. That's good to hear. > > To test get_args() alone, I would do something like this: > > > import sys > import unittest > import compare > > class Test_Get_Args(unittest.TestCase): > def setUp(self): > # Create some known files. > open('/tmp/aaa', 'w').close() > open('/tmp/bbb', 'w').close() > # Make sure another file doesn't exist. > if os.path.exists('/tmp/ccc'): > os.unlink('/tmp/ccc') > > def tearDown(self): > # Clean up once we're done. > for file in ('/tmp/aaa', '/tmp/bbb'): > if os.path.exists(file): > os.unlink(file) > > def test_existing_files(self): > sys.argv = ['testing', '/tmp/aaa', '/tmp/bbb'] > result = compare.get_args() > self.assertEqual(result, ['/tmp/aaa', '/tmp/bbb']) > > def test_nonexisting_files(self): > sys.argv = ['testing', '/tmp/ccc'] > result = compare.get_args() > self.assertEqual(result, []) > > def test_not_files(self): > sys.argv = ['testing', '/tmp', '/'] > result = compare.get_args() > self.assertEqual(result, []) > > > The paths I used are suitable for Unix, Linux or Mac. You will need to > adapt them for Windows. M$ Windows is of little interest to me:-) > > To avoid having to write to sys.argv, give your get_args function an > optional argument: > > def get_args(args=None): > if args is None: > args = sys.argv[1:] > return [arg for arg in args if os.path.isfile(arg)] > > then in your tests, just pass the list directly to the function. > > > >> Here's my attempt at a testing module: >> $ cat testing.py >> #!/usr/bin/env python3 >> import unittest >> import compare_sizes > > What's compare_sizes ? > OOPS! In editing for presentation to the list I forgot to change this instance of compare_sizes to compare. The ultimate goal is to compare file sizes and so I am trying to do TDD of compare_sizes.py which I forgot to rename to 'compare' in the import statement. > >> class CompareTesting(unittest.TestCase): >> >> def setUp(self): >> pass > > If you're not doing anything in setUp, just don't override the method. > The default method does nothing, so you don't need this. I stuck it in as a place holder expecting to soon need it. Should have removed it for presentation. > > >> def test_nothing(self): >> self.assertEqual(not False, True) > > What is the purpose of this test? How is it testing *your* code? That > would be necessary as a test of Python's built-ins. > Since I'm learning I wanted to start with a test that I 'knew' shouldn't fail. I should have deleted it for presentation- sorry. > >> def test_get_file_param(self): >> self.assertTrue(compare_sizes.get_args() == ['file1', >> 'file2']) > > You should use assertEqual(a, b) rather than assertTrue(a == b). > Thanks for this tip. I remember reading about that. >> if __name__ == '__main__': >> unittest.main() >> >> Is there a way that I can provide the file name command line >> parameters >> to compare.py so that its get_args function can be tested? > > sys.argv is writeable, or better still, provide get_args() an optional > argument to use instead of sys.argv.o I don't understand what you mean by "sys.argv is writeable". Thks again ak From dyoo at hashcollision.org Mon Aug 25 06:30:48 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 24 Aug 2014 21:30:48 -0700 Subject: [Tutor] Using unittest module for Test Driven Development In-Reply-To: <3afd8e4f91ccc8737b4b6df0bee328d3@sonic.net> References: <20140825015717.GL25957@ando> <3afd8e4f91ccc8737b4b6df0bee328d3@sonic.net> Message-ID: >>> Is there a way that I can provide the file name command line parameters >>> to compare.py so that its get_args function can be tested? >> >> sys.argv is writeable, or better still, provide get_args() an optional >> argument to use instead of sys.argv.o > > > I don't understand what you mean by "sys.argv is writeable". Hi Alex, I think Steven's suggestion to have get_args() take in an explicit args argument makes the most sense: it allows the function to be testable. If the behavior of the "function" depends on something outside of the function, making that thing an explicit parameter allows you to capture it. It makes the free variable something under your control. What "sys.argv is writeable" means is that you can take a sledgehammer approach: you can save the old value of sys.argv somewhere in another temporary variable, assign sys.argv to the test value, do your tests, and then assign the original value back to sys.argv. But this approach is very fragile: anything else that depends on sys.argv can suddenly stop working. From akleider at sonic.net Mon Aug 25 09:04:14 2014 From: akleider at sonic.net (Alex Kleider) Date: Mon, 25 Aug 2014 00:04:14 -0700 Subject: [Tutor] Using unittest module for Test Driven Development In-Reply-To: References: <20140825015717.GL25957@ando> <3afd8e4f91ccc8737b4b6df0bee328d3@sonic.net> Message-ID: On 2014-08-24 21:30, Danny Yoo wrote: >>>> Is there a way that I can provide the file name command line >>>> parameters >>>> to compare.py so that its get_args function can be tested? >>> >>> sys.argv is writeable, or better still, provide get_args() an >>> optional >>> argument to use instead of sys.argv.o >> >> >> I don't understand what you mean by "sys.argv is writeable". > > > Hi Alex, > > I think Steven's suggestion to have get_args() take in an explicit > args argument makes the most sense: it allows the function to be > testable. If the behavior of the "function" depends on something > outside of the function, making that thing an explicit parameter > allows you to capture it. It makes the free variable something under > your control. > > > What "sys.argv is writeable" means is that you can take a sledgehammer > approach: you can save the old value of sys.argv somewhere in another > temporary variable, assign sys.argv to the test value, do your tests, > and then assign the original value back to sys.argv. But this > approach is very fragile: anything else that depends on sys.argv can > suddenly stop working. Thanks, Danny; yes, as I spent more time looking over Steven's suggested approach I began to understand what he meant. I appreciate your further elucidation, like your 'sledge hammer' metaphor and thank you for the fragility warning. I expect with in such a limited scope, the dangers are not great. Cheers, AlexK From marc.tompkins at gmail.com Mon Aug 25 10:10:18 2014 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 25 Aug 2014 01:10:18 -0700 Subject: [Tutor] Using unittest module for Test Driven Development In-Reply-To: References: <20140825015717.GL25957@ando> <3afd8e4f91ccc8737b4b6df0bee328d3@sonic.net> Message-ID: On Mon, Aug 25, 2014 at 12:04 AM, Alex Kleider wrote: > I appreciate your further elucidation, like your 'sledge hammer' metaphor and thank you for the fragility warning. I expect within such a limited scope, the dangers are not great. As someone who has been burned by this sort of thinking, please allow me to urge you: get into good habits now! At various points in my career when I've been learning a new language/technology/paradigm, I've decided to take shortcuts when writing my early "toy" programs. Unfortunately, in several cases, my "toy" programs ended up evolving into production code - shortcuts and all. In particular, I used to assume that my code - since it was either a learning exercise or a utility for myself alone - would only ever run in a single-user/single-tasking environment, and that when I wrote the "real" program later (in my copious free time) I would take the necessary precautions. Please, take a fool's advice: always assume that any program you write (more complex than "Hello world") will eventually be running in a busy environment, or that your user will manage to invoke five copies of it instead of one, or... From akleider at sonic.net Mon Aug 25 11:45:33 2014 From: akleider at sonic.net (Alex Kleider) Date: Mon, 25 Aug 2014 02:45:33 -0700 Subject: [Tutor] Using unittest module for Test Driven Development In-Reply-To: References: <20140825015717.GL25957@ando> <3afd8e4f91ccc8737b4b6df0bee328d3@sonic.net> Message-ID: On 2014-08-25 01:10, Marc Tompkins wrote: > On Mon, Aug 25, 2014 at 12:04 AM, Alex Kleider > wrote: > >> I appreciate your further elucidation, like your 'sledge hammer' >> metaphor and thank you for the fragility warning. I expect within such >> a limited scope, the dangers are not great. > > As someone who has been burned by this sort of thinking, please allow > me to urge you: get into good habits now! At various points in my > career when I've been learning a new language/technology/paradigm, > I've decided to take shortcuts when writing my early "toy" programs. > Unfortunately, in several cases, my "toy" programs ended up evolving > into production code - shortcuts and all. In particular, I used to > assume that my code - since it was either a learning exercise or a > utility for myself alone - would only ever run in a > single-user/single-tasking environment, and that when I wrote the > "real" program later (in my copious free time) I would take the > necessary precautions. Please, take a fool's advice: always assume > that any program you write (more complex than "Hello world") will > eventually be running in a busy environment, or that your user will > manage to invoke five copies of it instead of one, or... Thanks for the sage advice; so much to learn. Since this is in a unittest module, it's unlikely that it'll get out into the sort of situation you describe, n'est pas? From diliupg at gmail.com Tue Aug 26 06:26:55 2014 From: diliupg at gmail.com (diliup gabadamudalige) Date: Tue, 26 Aug 2014 09:56:55 +0530 Subject: [Tutor] time vs. timeit Message-ID: Hi all, 1. why do some say that the time module is more accurate than the timeit module? s = time.time() or s = timeit.timeit() 2. Why is it that both modules never return the same answer on each run? Thank you for your response. -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ********************************************************************************************** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ********************************************************************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwpolska at gmail.com Tue Aug 26 10:34:15 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Tue, 26 Aug 2014 10:34:15 +0200 Subject: [Tutor] time vs. timeit In-Reply-To: References: Message-ID: On Tue, Aug 26, 2014 at 6:26 AM, diliup gabadamudalige wrote: > Hi all, > > 1. why do some say that the time module is more accurate than the timeit > module? > s = time.time() > or > s = timeit.timeit() > > 2. Why is it that both modules never return the same answer on each run? The two functions have completely different uses, and do completely different things. >>> help(time.time) Help on built-in function time in module time: time(...) time() -> floating point number Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. In other words, return this: http://en.wikipedia.org/wiki/Unix_time >>> help(timeit) NAME timeit - Tool for measuring execution time of small code snippets. [?] | timeit(self, number=1000000) | Time 'number' executions of the main statement. | | To be precise, this executes the setup statement once, and | then returns the time it takes to execute the main statement | a number of times, as a float measured in seconds. The | argument is the number of times through the loop, defaulting | to one million. The main statement, the setup statement and | the timer function to be used are passed to the constructor. -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From fomcl at yahoo.com Tue Aug 26 12:58:17 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 26 Aug 2014 03:58:17 -0700 Subject: [Tutor] simple unicode question In-Reply-To: References: <1408741821.17328.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: <1409050697.2601.YahooMailNeo@web163806.mail.gq1.yahoo.com> ----- Original Message ----- > From: Danny Yoo > To: Albert-Jan Roskam > Cc: Python Tutor Mailing List > Sent: Saturday, August 23, 2014 2:53 AM > Subject: Re: [Tutor] simple unicode question > > On Fri, Aug 22, 2014 at 2:10 PM, Albert-Jan Roskam > wrote: >>? Hi, >> >>? I have data that is either floats or byte strings in utf-8. I need to cast > both to unicode strings. > > > Just to be sure, I'm parsing the problem statement above as: > > ? ? data :== float > ? ? ? ? ? ? ? ? | utf-8-encoded-byte-string Yep, that's how I meant it :-) > because the alternative way to parse the statement in English: > > ? ? data :== float-in-utf-8 > ? ? ? ? ? ? ? ? | byte-string-in-utf-8 > > doesn't make any technical sense.? :P > > > > >>? I am probably missing something simple, but.. in the code below, under > "float", why does [B] throw an error but [A] does not? >> > >>? # float: cannot explicitly give encoding, even if it's the default >>>>>? value = 1.0 >>>>>? unicode(value)? ? ? # [A] >>? u'1.0' >>>>>? unicode(value, sys.getdefaultencoding())? # [B] >> >>? Traceback (most recent call last): >> ?? File "", line 1, in >> ? ?? unicode(value, sys.getdefaultencoding()) >>? TypeError: coercing to Unicode: need string or buffer, float found > > > Yeah.? Unfortunately, you're right: this doesn't make too much sense. > > What's happening is that the standard library overloads two > _different_ behaviors to the same function unicode(). It's conditioned > on whether we're passing in a single value, or if we're passing in > two.? I would not try to reconcile a single, same behavior for both > uses: treat them as two distinct behaviors. > > Reference: https://docs.python.org/2/library/functions.html#unicode Hi, ? First, THANKS for all your replies! Aahh, the first two lines in the link clarify things: unicode(object='') unicode(object[, encoding[, errors]]) I would? find it better/clearer if the docstring also started with these two lines, or, alternatively, with unicode(*args) I have tried to find these two functions in the source code, but I can?t find them (but I don't speak C). Somewhere near line 1200 perhaps? http://hg.python.org/cpython/file/74236c8bf064/Objects/unicodeobject.c > Specifically, the two arg case is meant where you've got an > uninterpreted source of bytes that should be decoded to Unicode using > the provided encoding. > > > So for your problem statement, the function should look something like: > > ############################### > def convert(data): > ? ? if isinstance(data, float): > ? ? ? ? return unicode(data) > ? ? if isinstance(data, bytes): > ? ? ? ? return unicode(data, "utf-8") > ? ? raise ValueError("Unexpected data", data) > ############################### > > where you must use unicode with either the 1-arg or 2-arg variant > based on your input data. Interesting, you follow a "look before you leap" approach here, whereas `they` always say it is easier to ?ask forgiveness than permission? in python. But LBYL is much faster, which is relevant because the function could be called millions and millions of times. If have noticed before that try-except is quite an expensive structure to initialize (for instance membership testing with ?in? is cheaper than try-except-KeyError when?getting items from a dictionary) In [1]: def convert1(data): ...:???????? if isinstance(data, float): ...:???????????????? return unicode(data) ...:???????? if isinstance(data, bytes): ...:???????????????? return unicode(data, "utf-8") ...:???????? raise ValueError("Unexpected data", data) ...: In [2]: %%timeit map(convert1, map(float, range(10)) + list("abcdefghij")) 10000 loops, best of 3: 19 us per loop In [3]: def convert2(data): ....:???????? try: ....:???????????????? return unicode(data, encoding="utf-8") ....:???????? except TypeError: ....:???????????????? return unicode(data) ....:???????? raise ValueError("Unexpected data", data) ....: In [4]: %timeit map(convert2, map(float, range(10)) + list("abcdefghij")) 10000 loops, best of 3: 40.4 us per loop??? From steve at pearwood.info Tue Aug 26 13:31:10 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 26 Aug 2014 21:31:10 +1000 Subject: [Tutor] time vs. timeit In-Reply-To: References: Message-ID: <20140826113110.GQ25957@ando> On Tue, Aug 26, 2014 at 09:56:55AM +0530, diliup gabadamudalige wrote: > Hi all, > > 1. why do some say that the time module is more accurate than the timeit > module? > s = time.time() > or > s = timeit.timeit() You will have to ask them. Since the two functions do very different things, I don't understand how they are comparing them. That's a bit like saying that len() is more accurate than math.sin(). > 2. Why is it that both modules never return the same answer on each run? time.time() returns the current time, in seconds since the start of the Unix Epoch. At midnight, 1st January 1970 UTC, time.time() would have returned 0. One second later, it would return 1. At 3:15:20am Friday 2nd January 1970, it would return 98120. I can check my calculation: py> import time py> time.ctime(98120) 'Fri Jan 2 13:15:20 1970' My local timezone is 10 hours ahead of UTC, so that is correct. time.time() will not return the same value because time keeps moving forward. The only way to get it to return the same value would be to set the computer's clock backwards. timeit.timeit is not like time(). It doesn't return an absolute time, but a *difference* between two times. It measures how long it takes to run some code. For example, on my computer: py> timeit.timeit("x = len([])") 0.1940888217650354 getting the length of the empty list [] one million times takes 0.19 seconds, or about 0.19?s each. On your computer, it may be faster, or slower. If I do it again: py> timeit.timeit("x = len([])") 0.19202891178429127 I get *about* the same value, but not exactly. It's not exactly the same speed because my computer is not doing exactly the same thing each time. There are other processes running: background tasks, virus checkers, internet downloads, the operating system is busy doing whatever it is that the operating system does. If I look on my computer, right now, there are at least 260 processes running: [steve at ando ~]$ ps aux | wc -l 260 The amount of time that timeit() reports will depend very slightly on how busy the computer is doing other things. You know that for yourself: if the computer is overloaded, doing too much, everything slows down. -- Steven From steve at pearwood.info Tue Aug 26 14:08:33 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 26 Aug 2014 22:08:33 +1000 Subject: [Tutor] simple unicode question In-Reply-To: <1409050697.2601.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1408741821.17328.YahooMailNeo@web163801.mail.gq1.yahoo.com> <1409050697.2601.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: <20140826120832.GR25957@ando> On Tue, Aug 26, 2014 at 03:58:17AM -0700, Albert-Jan Roskam wrote: > Interesting, you follow a "look before you leap" approach here, > whereas `they` always say it is easier to ?ask forgiveness than > permission? in python. Anyone who says it is *ALWAYS* easier is lying or confused :-) It is *often*, perhaps even *usually* better to use a AFTP approach, but not necessarily easier. Sometimes it is more work, but safer, or better. For instance, it is wrong (i.e. buggy) to use a LBYL approach here: if os.path.exists(filename): f = open(filename) process(f.read()) Why is it wrong? Just because the file exists, doesn't mean you can open it for reading. And just because it exists at the instant you do the test, doesn't mean it will still exist a millisecond later when Python tries to open the file. Perhaps another process or user has deleted it in the fraction of a second between the two lines. But sometimes AFTP is the wrong approach too. Consider a case where you have to do a number of things, and only if *all* of them can be done do you want to proceed. For example, baking a cake: - pour the cake mix and milk into a bowl; - mix; - pour into a pan; - put into the oven; - cook for 30 minutes. If you don't have an oven, there's no point mixing the cake mix and milk together, you'll just waste it. So you need to LBYL, make sure you have the cake mix AND the milk AND a bowl AND a pan AND an oven before you even start. If even one thing is missing, you don't proceed. > But LBYL is much faster, which is relevant > because the function could be called millions and millions of times. Not necessarily! It depends on how often you have failures. Let's time two examples: looking up something in a dict, where the key is never missing. Copy and paste this code: from timeit import Timer setup = 'd = {"a": 1, "b": 2}' t1 = Timer(""" if "a" in d: x = d["a"] if "b" in d: x = d["b"] """, setup) # LBYL version t2 = Timer(""" try: x = d["a"] except KeyError: pass try: x = d["b"] except KeyError: pass """, setup) # AFTP version And here are the results when I run it: py> min(t1.repeat()) 0.3348677200265229 py> min(t2.repeat()) 0.23994551179930568 So in this case, the LBYL example is significantly slower. Now let's try it again, only this time the key will be missing half the time: t3 = Timer(""" if "a" in d: x = d["a"] if "c" in d: x = d["c"] """, setup) # LBYL version t4 = Timer(""" try: x = d["a"] except KeyError: pass try: x = d["c"] except KeyError: pass """, setup) # AFTP version And the results: py> min(t3.repeat()) 0.24967589927837253 py> min(t4.repeat()) 0.8413973557762802 Now the LBYL version is faster. > If have noticed before that try-except is quite an expensive structure > to initialize (for instance membership testing with ?in? is cheaper > than try-except-KeyError when?getting items from a dictionary) Funny you should say that :-) Actually, try...except is almost free to *initialise*. Setting up the try block is very, very cheap, it takes hardly any time: py> timeit.timeit("len([])") # No try 0.19250816199928522 py> timeit.timeit(""" ... try: ... len([]) ... except: pass""") # With try 0.21191818173974752 That's not a lot of difference: less than 0.02?s. But, *catching* the exception is quite expensive. So the overhead of putting code inside a try block is negligible, virtually free, but the cost of actually catching the exception is quite heavy. So if there are lots and lots of exceptions, LBYL will probably be faster. But if they are rare, then the cost of looking before you leap isn't worth it, you should just leap. The exact crossover point will depend on how costly it is to look first versus the cost of the exception, but as a very rough rule of thumb, I go by: if *fewer* than 1 in 10 operations will raise an exception, then use try...except; but if *more* than 1 in 10 operations will raise an exception, and it is safe to do so, then LBYL may be appropriate. -- Steven From wprins at gmail.com Tue Aug 26 15:54:19 2014 From: wprins at gmail.com (Walter Prins) Date: Tue, 26 Aug 2014 14:54:19 +0100 Subject: [Tutor] Preparing virtualenvwrapper for Django 1.6 development In-Reply-To: References: Message-ID: Hi, To add: On 23 August 2014 08:54, Chris ?Kwpolska? Warrick wrote: > > On Fri, Aug 22, 2014 at 11:23 PM, Sithembewena Lloyd Dube > wrote: > > I am developing on a Windows 8.1 machine and wold like to setup > > virtualenvironment via virtualenvwrapper so as to have a properly set up > > Python development environment. > > > Would anyone be so kind as to translate this to Windows speak, as well as > > perhaps pointing out what file this would go into in a Windows environment? > > virtualenvwrapper does not work in Windows. You should use regular > virtualenv instead. Read this: > http://virtualenv.readthedocs.org/en/latest/virtualenv.html#usage On Windows I'd also suggest looking at virtualenvwrapper-powershell, which is a PowerShell version of virtualenvwrapper, (PowerShell being the effective de-facto modern-day shell for current Windows): https://pypi.python.org/pypi/virtualenvwrapper-powershell/2.7.1 http://www.tylerbutler.com/2012/05/how-to-install-python-pip-and-virtualenv-on-windows-with-powershell/ Walter From anirudh.tamsekar at gmail.com Tue Aug 26 11:10:30 2014 From: anirudh.tamsekar at gmail.com (Anirudh Tamsekar) Date: Tue, 26 Aug 2014 14:40:30 +0530 Subject: [Tutor] datetime substraction Message-ID: Hi, I'm writing a script to monitor rsyslog (second level check). Overview: We have Monit for monitoring rsyslog, however we need a script to do a second level checks. I'm looking for a script which will check if rsyslog is being updated, also log rotation is happening. Incase of the new file created by logrotate, script should monitor the latest file. Also monitor last modified time and tail of the log. Filename Ex. 20140826_debug_log (datechanges with log rotate) In case of any issues such as file not being updated within the interval of 5 min, alert with disk status. I have written a script, however I'm not able to get the date substraction math right, getting the following error (Searched google and other resources too). *Traceback (most recent call last):* * File "./rsyslog_check.py", line 22, in * * difft=cur_time-mt* *TypeError: unsupported operand type(s) for -: 'str' and 'str'* Request your help. Also point any good documentation where I can get quick reference. ########################## #! /usr/bin/python # import libraries import os import sys import datetime import time import smtplib import Queue import threading import subprocess # Defining main variables tfile='/local/rsyslog/20140727_msg_debug.log' dt = datetime.datetime.now().strftime("%Y%m%d") file = "_msg_debug.log" filename = "%s%s" % (dt,file) filepath = '/local/rsyslog/'+filename ct = time.ctime(os.path.getctime(tfile)) mt = time.ctime(os.path.getctime(tfile)) cur_time = time.ctime() difft=int(cur_time-mt) tdelta=datetime.timedelta(minute=5) # Main if os.path.isfile(filepath) == True: print "%s exists \n" % (tfile) print "This file was created at %s UTC \n" % (ct) * if difft > tdelta:* * print "File is not modified, last modified at %s UTC" % (mt)* * else:* * print "File is being modified"* *else:* * os.path.isfile(filepath)* # Tailing the file tailq = Queue.Queue(maxsize=10) # buffer at most 100 lines def tail_forever(filepath): p = subprocess.Popen(["tail", tfile], stdout=subprocess.PIPE) while 1: line = p.stdout.readline() tailq.put(line) if not line: break threading.Thread(target=tail_forever, args=(tfile,)).start() print "\n # Tailing Log file %s" % (tfile) print "\n ***********************************" print tailq.get() # blocks print tailq.get_nowait() # throws Queue.Empty if there are no lines to read exit() -Thanks, Anirudh Tamsekar -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Aug 26 18:47:34 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 27 Aug 2014 02:47:34 +1000 Subject: [Tutor] datetime substraction In-Reply-To: References: Message-ID: <20140826164733.GT25957@ando> On Tue, Aug 26, 2014 at 02:40:30PM +0530, Anirudh Tamsekar wrote: > I have written a script, however I'm not able to get the date substraction > math right, getting the following error > (Searched google and other resources too). > > *Traceback (most recent call last):* > * File "./rsyslog_check.py", line 22, in * > * difft=cur_time-mt* > *TypeError: unsupported operand type(s) for -: 'str' and 'str'* cur_time and mt are strings. You cannot subtract strings. os.path.getctime(filename) returns the ctime of the file as a number. You then convert that number into a string. Don't. Just leave it as a number: mt = os.path.getctime(tfile) cur_time = time.time() difft = cur_time - mt -- Steven From alan.gauld at btinternet.com Tue Aug 26 18:55:10 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Aug 2014 17:55:10 +0100 Subject: [Tutor] datetime substraction In-Reply-To: References: Message-ID: On 26/08/14 10:10, Anirudh Tamsekar wrote: > *Traceback (most recent call last):* > * File "./rsyslog_check.py", line 22, in * > * difft=cur_time-mt* > *TypeError: unsupported operand type(s) for -: 'str' and 'str'* > > Request your help. Also point any good documentation where I can get > quick reference. > > ct = time.ctime(os.path.getctime(tfile)) > mt = time.ctime(os.path.getctime(tfile)) You are converting the times to strings before you subtract them. Don't do that, subtract the times as returned by os.path.getctime() and time.time(). > cur_time = time.ctime() > difft=int(cur_time-mt) You need to subtract the numeric versions of the times not the strings. The best quick references are the dir() and help() builtin functions. For more detail read the documentation for time, os.path (and maybe datetime) modules. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Tue Aug 26 18:55:41 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 26 Aug 2014 09:55:41 -0700 Subject: [Tutor] datetime substraction In-Reply-To: References: Message-ID: > > I have written a script, however I'm not able to get the date substraction > math right, getting the following error > (Searched google and other resources too). > > Traceback (most recent call last): > File "./rsyslog_check.py", line 22, in > difft=cur_time-mt > TypeError: unsupported operand type(s) for -: 'str' and 'str' Hi Anirudh, This error message suggests that 'cur_time' and 'mt' here are not dates. Rather, they're strings. I'd trust the error message and turn the question from: "How do I subtract date subtraction math right?" to: "Why are these values that I expect to be dates actually strings?" Let's see... oh, you're using the time.ctime() function here: > mt = time.ctime(os.path.getctime(tfile)) > cur_time = time.ctime() > difft=int(cur_time-mt) What is this doing? Let's check. We can look at the standard library documentation: https://docs.python.org/2/library/index.html Searching... so this code first uses os.path.getctime(), which takes a file name and returns the number of seconds since the Epoch. https://docs.python.org/2/library/os.path.html#os.path.getctime What's the meaning of time.ctime? https://docs.python.org/2/library/time.html#time.ctime Ok, from reading time.ctime(), I think you should not be using this function. It takes the number of seconds since the Epoch, and formats it as a nice string for people to read in their local time zone. So it's almost useless for doing any mechanical calculations. To put it in perspective, it's as if you are trying to do arithmetic with roman numerals. Don't do that. As Stephen points out, you've got the two dates in terms of seconds since the Epoch, so you might as well just subtract to get the number of seconds altogether. If you truly want to treat dates as algebraic objects, consider the datetime library. https://docs.python.org/2/library/datetime.html You can use the datetime.fromtimestamp() function to take the seconds since the Epoch and transform them into datetime objects: https://docs.python.org/2/library/datetime.html#datetime.datetime.fromtimestamp From najam.qasim at yahoo.com Wed Aug 27 03:41:35 2014 From: najam.qasim at yahoo.com (Najam Qasim) Date: Tue, 26 Aug 2014 21:41:35 -0400 Subject: [Tutor] Tutor Digest, Vol 126, Issue 64 In-Reply-To: References: Message-ID: <89718EE7-22CE-4BF0-AC30-0DCA16144355@yahoo.com> What is preferable method to debug and execute python code in Mac? I do not like the cmd/terminal execution. Thank you. > On Aug 26, 2014, at 6:00 AM, tutor-request at python.org wrote: > > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. time vs. timeit (diliup gabadamudalige) > 2. Re: time vs. timeit (Chris ?Kwpolska? Warrick) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 26 Aug 2014 09:56:55 +0530 > From: diliup gabadamudalige > To: "tutor at python.org" > Subject: [Tutor] time vs. timeit > Message-ID: > > Content-Type: text/plain; charset="utf-8" > > Hi all, > > 1. why do some say that the time module is more accurate than the timeit > module? > s = time.time() > or > s = timeit.timeit() > > 2. Why is it that both modules never return the same answer on each run? > > Thank you for your response. > > -- > Diliup Gabadamudalige > > http://www.diliupg.com > http://soft.diliupg.com/ > > ********************************************************************************************** > This e-mail is confidential. It may also be legally privileged. If you are > not the intended recipient or have received it in error, please delete it > and all copies from your system and notify the sender immediately by return > e-mail. Any unauthorized reading, reproducing, printing or further > dissemination of this e-mail or its contents is strictly prohibited and may > be unlawful. Internet communications cannot be guaranteed to be timely, > secure, error or virus-free. The sender does not accept liability for any > errors or omissions. > ********************************************************************************************** > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 2 > Date: Tue, 26 Aug 2014 10:34:15 +0200 > From: Chris ?Kwpolska? Warrick > To: diliup gabadamudalige > Cc: "tutor at python.org" > Subject: Re: [Tutor] time vs. timeit > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > On Tue, Aug 26, 2014 at 6:26 AM, diliup gabadamudalige > wrote: >> Hi all, >> >> 1. why do some say that the time module is more accurate than the timeit >> module? >> s = time.time() >> or >> s = timeit.timeit() >> >> 2. Why is it that both modules never return the same answer on each run? > > The two functions have completely different uses, and do completely > different things. > >>>> help(time.time) > Help on built-in function time in module time: > > time(...) > time() -> floating point number > > Return the current time in seconds since the Epoch. > Fractions of a second may be present if the system clock provides them. > > > In other words, return this: http://en.wikipedia.org/wiki/Unix_time > > >>>> help(timeit) > NAME > timeit - Tool for measuring execution time of small code snippets. > > [?] > | timeit(self, number=1000000) > | Time 'number' executions of the main statement. > | > | To be precise, this executes the setup statement once, and > | then returns the time it takes to execute the main statement > | a number of times, as a float measured in seconds. The > | argument is the number of times through the loop, defaulting > | to one million. The main statement, the setup statement and > | the timer function to be used are passed to the constructor. > > -- > Chris ?Kwpolska? Warrick > PGP: 5EAAEA16 > stop html mail | always bottom-post | only UTF-8 makes sense > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 126, Issue 64 > ************************************** From alan.gauld at btinternet.com Wed Aug 27 09:30:24 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 27 Aug 2014 08:30:24 +0100 Subject: [Tutor] Tutor Digest, Vol 126, Issue 64 In-Reply-To: <89718EE7-22CE-4BF0-AC30-0DCA16144355@yahoo.com> References: <89718EE7-22CE-4BF0-AC30-0DCA16144355@yahoo.com> Message-ID: On 27/08/14 02:41, Najam Qasim wrote: > What is preferable method to debug and execute python code in Mac? > I do not like the cmd/terminal execution. That is a very personal choice. You don't tell us what you don't like about the terminal or what features you consider important in your choice of tools. You also don't tell us if you have any previous programming experience and what tools you used there. On the basis that you want a non CLI tool I can only offer some suggestions in increasing order of complexity: Emacs Python mode - If you use emacs for other programming languages then this will be familiar to you. Integrates Python development with the other emacs functions. Really only a sensible option if you already use emacs. IDLE - comes with Python, offers a very basic GUI text editor and debugger in addition to a Python >>> prompt. IPython - offers a more sophisticated version of the >>> prompt including notebook facilities for retrieving previous sessions (and much more) XCode - The standard developers tool on a Mac. Integrates with GUI tools for building Cocoa applications Eclipse - The industry standard IDE supports editing, execution and debugging of code plus integration with version control. Also has plugins for a host of other functions such as design and testing. Netbeans - Another popular tool in industry, similar to Xcode and Eclipse in complexity and power. You will need to look at the various web sites and try them out to decide which one suits you best. There are some commercial tools too but I've stuck with free for now. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From najamqasim at gmail.com Wed Aug 27 13:14:10 2014 From: najamqasim at gmail.com (Najam Qasim) Date: Wed, 27 Aug 2014 07:14:10 -0400 Subject: [Tutor] debug and execute python code in Mac Message-ID: > What is preferable method to debug and execute python code in Mac? > I do not like the cmd/terminal execution. Thanks ! -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Wed Aug 27 16:57:51 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 27 Aug 2014 07:57:51 -0700 Subject: [Tutor] simple unicode question In-Reply-To: <20140826120832.GR25957@ando> References: <1408741821.17328.YahooMailNeo@web163801.mail.gq1.yahoo.com> <1409050697.2601.YahooMailNeo@web163806.mail.gq1.yahoo.com> <20140826120832.GR25957@ando> Message-ID: <1409151471.90968.YahooMailNeo@web163806.mail.gq1.yahoo.com> ----- Original Message ----- > From: Steven D'Aprano > To: tutor at python.org > Cc: > Sent: Tuesday, August 26, 2014 2:08 PM > Subject: Re: [Tutor] simple unicode question > > On Tue, Aug 26, 2014 at 03:58:17AM -0700, Albert-Jan Roskam wrote: > >> Interesting, you follow a "look before you leap" approach here, >> whereas `they` always say it is easier to ?ask forgiveness than >> permission? in python. > > Anyone who says it is *ALWAYS* easier is lying or confused :-) > > It is *often*, perhaps even *usually* better to use a AFTP approach, but > not necessarily easier. Sometimes it is more work, but safer, or better. > For instance, it is wrong (i.e. buggy) to use a LBYL approach here: > > > if os.path.exists(filename): > ? ? f = open(filename) > ? ? process(f.read()) > > Why is it wrong? Just because the file exists, doesn't mean you can open > it for reading. And just because it exists at the instant you do the > test, doesn't mean it will still exist a millisecond later when Python > tries to open the file. Perhaps another process or user has deleted it > in the fraction of a second between the two lines. > > But sometimes AFTP is the wrong approach too. Consider a case where you > have to do a number of things, and only if *all* of them can be done do > you want to proceed. For example, baking a cake: > > - pour the cake mix and milk into a bowl; > - mix; > - pour into a pan; > - put into the oven; > - cook for 30 minutes. > > If you don't have an oven, there's no point mixing the cake mix and milk > > together, you'll just waste it. So you need to LBYL, make sure you have > the cake mix AND the milk AND a bowl AND a pan AND an oven before you > even start. If even one thing is missing, you don't proceed. > > >> But LBYL is much faster, which is relevant >> because the function could be called millions and millions of times. > > Not necessarily! It depends on how often you have failures. Let's time > two examples: looking up something in a dict, where the key is never > missing. Copy and paste this code: > > > from timeit import Timer > setup = 'd = {"a": 1, "b": 2}' > > t1 = Timer(""" > if "a" in d: x = d["a"] > if "b" in d: x = d["b"] > """, setup)? # LBYL version > > t2 = Timer(""" > try: > ? ? x = d["a"] > except KeyError: > ? ? pass > try: > ? ? x = d["b"] > except KeyError: > ? ? pass > """, setup)? # AFTP version > > > > And here are the results when I run it: > > py> min(t1.repeat()) > 0.3348677200265229 > py> min(t2.repeat()) > 0.23994551179930568 > > So in this case, the LBYL example is significantly slower. > > Now let's try it again, only this time the key will be missing half the > time: > > > t3 = Timer(""" > if "a" in d: x = d["a"] > if "c" in d: x = d["c"] > """, setup)? # LBYL version > > t4 = Timer(""" > try: > ? ? x = d["a"] > except KeyError: > ? ? pass > try: > ? ? x = d["c"] > except KeyError: > ? ? pass > """, setup)? # AFTP version > > > And the results: > > py> min(t3.repeat()) > 0.24967589927837253 > py> min(t4.repeat()) > 0.8413973557762802 > > Now the LBYL version is faster. > > >> If have noticed before that try-except is quite an expensive structure >> to initialize (for instance membership testing with ?in? is cheaper >> than try-except-KeyError when?getting items from a dictionary) > > Funny you should say that :-) > > Actually, try...except is almost free to *initialise*. Setting up the > try block is very, very cheap, it takes hardly any time: > > py> timeit.timeit("len([])")? # No try > 0.19250816199928522 > py> timeit.timeit(""" > ... try: > ...? ? len([]) > ... except: pass""")? # With try > 0.21191818173974752 > > That's not a lot of difference: less than 0.02?s. > > But, *catching* the exception is quite expensive. So the overhead of > putting code inside a try block is negligible, virtually free, but the > cost of actually catching the exception is quite heavy. So if there are > lots and lots of exceptions, LBYL will probably be faster. But if they > are rare, then the cost of looking before you leap isn't worth it, you > should just leap. The exact crossover point will depend on how costly it > is to look first versus the cost of the exception, but as a very rough > rule of thumb, I go by: > > if *fewer* than 1 in 10 operations will raise an exception, then use > try...except; but if *more* than 1 in 10 operations will raise an > exception, and it is safe to do so, then LBYL may be appropriate. ? Thanks a lot, Steven! This kind of stuff should be in a book. I haven't seen any Python book where this kind of "it depends on your data" kind of considerations are discussed. Do you know of any real life examples where the code is written in such a way that it could switch from AFTP to LBYL and vice versa? It would probably look ugly, and it would have overhead. But if you would switch strategy after processing, say, 1000 records, then why not do it if it saves time? ? regards, ALbert-Jan From jake_andrews at btinternet.com Wed Aug 27 15:40:59 2014 From: jake_andrews at btinternet.com (Jake) Date: Wed, 27 Aug 2014 14:40:59 +0100 Subject: [Tutor] Python Programming Message-ID: To whom it may concern, My name is Jake and I have recently started the GCSE computing course with school. As summer holidays homework we have been asked to make a game. So I have made a Capital Cities Quiz. When I run my program this part of my coding does not seem to work: answera = input() if answera == ["Oslo" or "oslo"]: print ("CORRECT!!") score = score + 1 else: print("INCORRECT!!") When I type Oslo or oslo as my answer it keeps telling me that it is incorrect. I was wondering if it would be possible for you to tell me what I have done wrong and hopefully point me in the right direction. I look forward to hearing from you, Jake From pathunstrom at gmail.com Wed Aug 27 14:47:26 2014 From: pathunstrom at gmail.com (Patrick Thunstrom) Date: Wed, 27 Aug 2014 08:47:26 -0400 Subject: [Tutor] debug and execute python code in Mac In-Reply-To: References: Message-ID: On Wed, Aug 27, 2014 at 7:14 AM, Najam Qasim wrote: > What is preferable method to debug and execute python code in Mac? > > I do not like the cmd/terminal execution. Thanks ! > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > I don't know many ways to debug code that don't involve the terminal in some fashion. Even with a good IDE you're going to have a terminal built in for output. From anirudh.tamsekar at gmail.com Wed Aug 27 16:12:33 2014 From: anirudh.tamsekar at gmail.com (Anirudh Tamsekar) Date: Wed, 27 Aug 2014 19:42:33 +0530 Subject: [Tutor] datetime substraction In-Reply-To: References: Message-ID: Hi Alan/Danny/Steve, Thank you very much, I'm able to get the script working. -Regards, Anirudh Tamsekar On Tue, Aug 26, 2014 at 10:25 PM, Alan Gauld wrote: > On 26/08/14 10:10, Anirudh Tamsekar wrote: > > *Traceback (most recent call last):* >> * File "./rsyslog_check.py", line 22, in * >> * difft=cur_time-mt* >> *TypeError: unsupported operand type(s) for -: 'str' and 'str'* >> >> >> Request your help. Also point any good documentation where I can get >> quick reference. >> >> ct = time.ctime(os.path.getctime(tfile)) >> mt = time.ctime(os.path.getctime(tfile)) >> > > You are converting the times to strings before you subtract them. Don't do > that, subtract the times as returned by os.path.getctime() and time.time(). > > cur_time = time.ctime() >> difft=int(cur_time-mt) >> > > You need to subtract the numeric versions of the times not the strings. > > The best quick references are the dir() and help() builtin functions. > For more detail read the documentation for time, os.path (and maybe > datetime) modules. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Aug 27 20:57:12 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 27 Aug 2014 19:57:12 +0100 Subject: [Tutor] Python Programming In-Reply-To: References: Message-ID: On 27/08/14 14:40, Jake wrote: > To whom it may concern, > My name is Jake and I have recently started the GCSE computing course with school. > answera = input() > if answera == ["Oslo" or "oslo"]: This doesn't do what you think it does. ["Oslo" or "oslo"] is a list "Oslo" or "oslo" is the content of the list and is a boolean expression which evaluates to True. (Each non-empty string is considered True by Python) So your 'if' line looks to Python like: if answera == [True]: But answera is a string so it will never equal a list with a single boolean value so you go to the else clause. A better way to do what you want is to convert the input to lowercase using the string lower() method and compare that to the string you want, like so: if answera.lower() == "oslo": If you need to check multiple possible answers you can use a list of strings and the 'in' operator like this: if answera.lower() in ['amsterdam', 'london', 'oslo']: HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Wed Aug 27 21:09:36 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 27 Aug 2014 20:09:36 +0100 Subject: [Tutor] simple unicode question In-Reply-To: <1409151471.90968.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1408741821.17328.YahooMailNeo@web163801.mail.gq1.yahoo.com> <1409050697.2601.YahooMailNeo@web163806.mail.gq1.yahoo.com> <20140826120832.GR25957@ando> <1409151471.90968.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On 27/08/14 15:57, Albert-Jan Roskam wrote: >> if *fewer* than 1 in 10 operations will raise an exception, then use >> try...except; but if *more* than 1 in 10 operations will raise an >> exception, and it is safe to do so, then LBYL may be appropriate. > > > Thanks a lot, Steven! This kind of stuff should be in a book. It is in lots of books but they aren't Python books; they are generic software engineering books. Because this is not really a language specific type design issue, its general software design. > Do you know of any real life examples where the code is written > in such a way that it could switch from AFTP to LBYL It would be very unlikely since it would almost always be a case of premature optimisation. You would need to be inside a very tight loop to make that kind of optimisation worthwhile in real world scenarios. (And the cost of evaluating it would probably outweigh any gains.) Much more important is to make the code correct and maintainable than to worry about slight performance issues before they are a proven issue. Building those kind of self modifying control flows makes code much more error prone and difficult to modify. The vast majority of performance issues in software are to do with blockages in IO processing(network, disk access, human input, etc) or database processing (big data or complex searches) or in traversing complex/deep data structures. Very few real-world performance issues are related to simple code execution issues. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From crushed26 at gmail.com Thu Aug 28 00:45:41 2014 From: crushed26 at gmail.com (Crush) Date: Wed, 27 Aug 2014 18:45:41 -0400 Subject: [Tutor] Interacting with stderr Message-ID: <77745CA4-8F7D-410C-800D-F0A3C711D2F2@gmail.com> Hello, it has been a while and I hope I am sending to the correct email. How would I go about running a conditional statement against the contents of stderr. For instance, if "blah blah blah" is in stderr do X, else do Y. CODE: SELECT ALL #!/usr/bin/env python import subprocess from subprocess import PIPE i = 0 while i < 10: p = subprocess.call("avconv -v verbose -re -analyzeduration 1000 -i http://localhost:6498/ms2/1382097438004/0MediaPlayer+0+/octoshape+hVV+octolive.americaone.com+V+aone+V+live+V+ONECONNXT_DEMO1_HD_flv/aoneliveONECONNXTDEMO1HDflv -c:v rawvideo -c:a pcm_s16le -ar 48000 -f nut - | ./bmdplay -m 12 -f pipe:0", shell=True) i += 1 if i == 10: print "Gave up" The above code works and I get no tracebacks, however I need to add to it and check the contents of stderr. Avconv by default sends the audio and video to stdout, which then sends the signal to a capture card in the machine. Avconv is sending the status of the broadcasted signal i.e. frames, time, fps, etc. to stderr, which is displayed in the terminal. Bo -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Thu Aug 28 00:55:39 2014 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 28 Aug 2014 08:55:39 +1000 Subject: [Tutor] Interacting with stderr In-Reply-To: <77745CA4-8F7D-410C-800D-F0A3C711D2F2@gmail.com> References: <77745CA4-8F7D-410C-800D-F0A3C711D2F2@gmail.com> Message-ID: <20140827225539.GA55624@cskk.homeip.net> On 27Aug2014 18:45, Crush wrote: >Hello, it has been a while and I hope I am sending to the correct email. > >How would I go about running a conditional statement against the contents of >stderr. For instance, if "blah blah blah" is in stderr do X, else do Y. > > > #!/usr/bin/env python > import subprocess > from subprocess import PIPE > i = 0 > while i < 10: > p = subprocess.call("avconv -v verbose -re -analyzeduration 1000 -i http://localhost:6498/ms2/1382097438004/0MediaPlayer+0+/octoshape+hVV+octolive.americaone.com+V+aone+V+live+V+ONECONNXT_DEMO1_HD_flv/aoneliveONECONNXTDEMO1HDflv -c:v rawvideo -c:a pcm_s16le -ar 48000 -f nut - | ./bmdplay -m 12 -f pipe:0", shell=True) > i += 1 > if i == 10: > print "Gave up" > >The above code works and I get no tracebacks, however I need to add to it and >check the contents of stderr. Avconv by default sends the audio and video to >stdout, which then sends the signal to a capture card in the machine. Avconv >is sending the status of the broadcasted signal i.e. frames, time, fps, etc. >to stderr, which is displayed in the terminal. Send stderr to a file, using a parameter like: stderr=open('stderr.out', 'w') in your call() call. Then open 'stderr.out' and look for the relevant information. Obviously in a "real" program you'd take care to make that a temporary file with a unique name using the functions from the "tempfile" module, etc. But make it work first. Cheers, Cameron Simpson The Few. The Proud. The Politically Incorrect. - Steve Masticola From alan.gauld at btinternet.com Thu Aug 28 01:31:08 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Aug 2014 00:31:08 +0100 Subject: [Tutor] debug and execute python code in Mac In-Reply-To: References: Message-ID: On 27/08/14 13:47, Patrick Thunstrom wrote: >> I do not like the cmd/terminal execution. Thanks ! > > I don't know many ways to debug code that don't involve the terminal > in some fashion. Even with a good IDE you're going to have a terminal > built in for output. Not necessarily. A text display widget within a GUI is very different from a text based terminal. Many graphical debuggers display data structures in a hierarchical model where you can expand/close the various levels etc. But I think the OP is specifically wanting to avoid command prompts. The question is: Does he mean all prompts (including Python's) or just the OS prompt? If its all prompts then it gets much harder to find an IDE that will suit. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Thu Aug 28 01:38:09 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Aug 2014 00:38:09 +0100 Subject: [Tutor] Interacting with stderr In-Reply-To: <77745CA4-8F7D-410C-800D-F0A3C711D2F2@gmail.com> References: <77745CA4-8F7D-410C-800D-F0A3C711D2F2@gmail.com> Message-ID: On 27/08/14 23:45, Crush wrote: > Hello, it has been a while and I hope I am sending to the correct email. > > How would I go about running a conditional statement against the > contents of stderr. For instance, if "blah blah blah" is in stderr do X, > else do Y. You can access stderr just like you access stdout. The recommended way is via communicate: --------------- Popen.communicate(input=None, timeout=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be data to be sent to the child process, or None, if no data should be sent to the child. The type of input must be bytes or, if universal_newlines was True, a string. communicate() returns a tuple (stdoutdata, stderrdata). Note that if you want to send data to the process?s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too. -------------------- HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From crushed26 at gmail.com Thu Aug 28 02:28:58 2014 From: crushed26 at gmail.com (Crush) Date: Wed, 27 Aug 2014 20:28:58 -0400 Subject: [Tutor] Interacting with stderr In-Reply-To: References: Message-ID: As far as sending the contents of stderr to a tmp file...hmmm, i will try that. My only concern is, many of these systems run live demo feeds for many days...10+. Im afraid the file will fill up very quickly and present problems. Stderr=PIPE causes the terminal to hang. I can not wait for the process to terminate, i need to read stderr as it is being fed data.. Would fifos be of any use here? I will research the tempfile module. Bo > On Aug 27, 2014, at 7:38 PM, tutor-request at python.org wrote: > > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Python Programming (Alan Gauld) > 2. Re: simple unicode question (Alan Gauld) > 3. Interacting with stderr (Crush) > 4. Re: Interacting with stderr (Cameron Simpson) > 5. Re: debug and execute python code in Mac (Alan Gauld) > 6. Re: Interacting with stderr (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 27 Aug 2014 19:57:12 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Python Programming > Message-ID: > Content-Type: text/plain; charset=windows-1252; format=flowed > >> On 27/08/14 14:40, Jake wrote: >> To whom it may concern, >> My name is Jake and I have recently started the GCSE computing course with school. > >> answera = input() >> if answera == ["Oslo" or "oslo"]: > > This doesn't do what you think it does. > > ["Oslo" or "oslo"] is a list > > "Oslo" or "oslo" is the content of the list and > is a boolean expression which evaluates to True. > (Each non-empty string is considered True by Python) > > So your 'if' line looks to Python like: > > if answera == [True]: > > But answera is a string so it will never equal a list > with a single boolean value so you go to the else > clause. > > A better way to do what you want is to convert the input > to lowercase using the string lower() method and compare > that to the string you want, like so: > > if answera.lower() == "oslo": > > If you need to check multiple possible answers you can use > a list of strings and the 'in' operator like this: > > if answera.lower() in ['amsterdam', 'london', 'oslo']: > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 2 > Date: Wed, 27 Aug 2014 20:09:36 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] simple unicode question > Message-ID: > Content-Type: text/plain; charset=utf-8; format=flowed > > On 27/08/14 15:57, Albert-Jan Roskam wrote: > >>> if *fewer* than 1 in 10 operations will raise an exception, then use >>> try...except; but if *more* than 1 in 10 operations will raise an >>> exception, and it is safe to do so, then LBYL may be appropriate. >> >> >> Thanks a lot, Steven! This kind of stuff should be in a book. > > It is in lots of books but they aren't Python books; they are generic > software engineering books. Because this is not really a language > specific type design issue, its general software design. > >> Do you know of any real life examples where the code is written >> in such a way that it could switch from AFTP to LBYL > > It would be very unlikely since it would almost always be a case of > premature optimisation. You would need to be inside a very tight loop to > make that kind of optimisation worthwhile in real world scenarios. > (And the cost of evaluating it would probably outweigh any gains.) > > Much more important is to make the code correct and maintainable than to > worry about slight performance issues before they are a proven issue. > Building those kind of self modifying control flows makes code much more > error prone and difficult to modify. > > The vast majority of performance issues in software are to do with > blockages in IO processing(network, disk access, human input, etc) > or database processing (big data or complex searches) or in traversing > complex/deep data structures. Very few real-world performance issues > are related to simple code execution issues. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 3 > Date: Wed, 27 Aug 2014 18:45:41 -0400 > From: Crush > To: "tutor at python.org" > Subject: [Tutor] Interacting with stderr > Message-ID: <77745CA4-8F7D-410C-800D-F0A3C711D2F2 at gmail.com> > Content-Type: text/plain; charset="us-ascii" > > Hello, it has been a while and I hope I am sending to the correct email. > > How would I go about running a conditional statement against the contents of stderr. For instance, if "blah blah blah" is in stderr do X, else do Y. > > CODE: SELECT ALL > > #!/usr/bin/env python > import subprocess > from subprocess import PIPE > i = 0 > while i < 10: > p = subprocess.call("avconv -v verbose -re -analyzeduration 1000 -i http://localhost:6498/ms2/1382097438004/0MediaPlayer+0+/octoshape+hVV+octolive.americaone.com+V+aone+V+live+V+ONECONNXT_DEMO1_HD_flv/aoneliveONECONNXTDEMO1HDflv -c:v rawvideo -c:a pcm_s16le -ar 48000 -f nut - | ./bmdplay -m 12 -f pipe:0", shell=True) > i += 1 > if i == 10: > print "Gave up" > > > The above code works and I get no tracebacks, however I need to add to it and check the contents of stderr. Avconv by default sends the audio and video to stdout, which then sends the signal to a capture card in the machine. Avconv is sending the status of the broadcasted signal i.e. frames, time, fps, etc. to stderr, which is displayed in the terminal. > > Bo > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 4 > Date: Thu, 28 Aug 2014 08:55:39 +1000 > From: Cameron Simpson > To: "tutor at python.org" > Subject: Re: [Tutor] Interacting with stderr > Message-ID: <20140827225539.GA55624 at cskk.homeip.net> > Content-Type: text/plain; charset=us-ascii; format=flowed > >> On 27Aug2014 18:45, Crush wrote: >> Hello, it has been a while and I hope I am sending to the correct email. >> >> How would I go about running a conditional statement against the contents of >> stderr. For instance, if "blah blah blah" is in stderr do X, else do Y. >> >> >> #!/usr/bin/env python >> import subprocess >> from subprocess import PIPE >> i = 0 >> while i < 10: >> p = subprocess.call("avconv -v verbose -re -analyzeduration 1000 -i http://localhost:6498/ms2/1382097438004/0MediaPlayer+0+/octoshape+hVV+octolive.americaone.com+V+aone+V+live+V+ONECONNXT_DEMO1_HD_flv/aoneliveONECONNXTDEMO1HDflv -c:v rawvideo -c:a pcm_s16le -ar 48000 -f nut - | ./bmdplay -m 12 -f pipe:0", > shell=True) >> i += 1 >> if i == 10: >> print "Gave up" >> >> The above code works and I get no tracebacks, however I need to add to it and >> check the contents of stderr. Avconv by default sends the audio and video to >> stdout, which then sends the signal to a capture card in the machine. Avconv >> is sending the status of the broadcasted signal i.e. frames, time, fps, etc. >> to stderr, which is displayed in the terminal. > > Send stderr to a file, using a parameter like: > > stderr=open('stderr.out', 'w') > > in your call() call. Then open 'stderr.out' and look for the relevant > information. > > Obviously in a "real" program you'd take care to make that a temporary file > with a unique name using the functions from the "tempfile" module, etc. But > make it work first. > > Cheers, > Cameron Simpson > > The Few. The Proud. The Politically Incorrect. - Steve Masticola > > > ------------------------------ > > Message: 5 > Date: Thu, 28 Aug 2014 00:31:08 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] debug and execute python code in Mac > Message-ID: > Content-Type: text/plain; charset=windows-1252; format=flowed > > On 27/08/14 13:47, Patrick Thunstrom wrote: > >>> I do not like the cmd/terminal execution. Thanks ! >> >> I don't know many ways to debug code that don't involve the terminal >> in some fashion. Even with a good IDE you're going to have a terminal >> built in for output. > > Not necessarily. A text display widget within a GUI is very different > from a text based terminal. Many graphical debuggers display data > structures in a hierarchical model where you can expand/close the > various levels etc. > > But I think the OP is specifically wanting to avoid command prompts. The > question is: Does he mean all prompts (including > Python's) or just the OS prompt? If its all prompts then it gets > much harder to find an IDE that will suit. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 6 > Date: Thu, 28 Aug 2014 00:38:09 +0100 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Interacting with stderr > Message-ID: > Content-Type: text/plain; charset=windows-1252; format=flowed > >> On 27/08/14 23:45, Crush wrote: >> Hello, it has been a while and I hope I am sending to the correct email. >> >> How would I go about running a conditional statement against the >> contents of stderr. For instance, if "blah blah blah" is in stderr do X, >> else do Y. > > You can access stderr just like you access stdout. > The recommended way is via communicate: > > --------------- > Popen.communicate(input=None, timeout=None) > > Interact with process: Send data to stdin. Read data from stdout and > stderr, until end-of-file is reached. Wait for process to terminate. The > optional input argument should be data to be sent to the child process, > or None, if no data should be sent to the child. The type of input must > be bytes or, if universal_newlines was True, a string. > > communicate() returns a tuple (stdoutdata, stderrdata). > > Note that if you want to send data to the process?s stdin, you need to > create the Popen object with stdin=PIPE. Similarly, to get anything > other than None in the result tuple, you need to give stdout=PIPE and/or > stderr=PIPE too. > -------------------- > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 126, Issue 69 > ************************************** From dvnsarma at gmail.com Thu Aug 28 02:45:20 2014 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Thu, 28 Aug 2014 06:15:20 +0530 Subject: [Tutor] Python Programming In-Reply-To: References: Message-ID: change the line if answera == ["Oslo" or "oslo"]: to if answera == "Oslo" or answera == "oslo": and see if it works. regards, Sarma. On Thu, Aug 28, 2014 at 12:27 AM, Alan Gauld wrote: > On 27/08/14 14:40, Jake wrote: > >> To whom it may concern, >> My name is Jake and I have recently started the GCSE computing course >> with school. >> > > answera = input() >> if answera == ["Oslo" or "oslo"]: >> > > This doesn't do what you think it does. > > ["Oslo" or "oslo"] is a list > > "Oslo" or "oslo" is the content of the list and > is a boolean expression which evaluates to True. > (Each non-empty string is considered True by Python) > > So your 'if' line looks to Python like: > > if answera == [True]: > > But answera is a string so it will never equal a list > with a single boolean value so you go to the else > clause. > > A better way to do what you want is to convert the input > to lowercase using the string lower() method and compare > that to the string you want, like so: > > if answera.lower() == "oslo": > > If you need to check multiple possible answers you can use > a list of strings and the 'in' operator like this: > > if answera.lower() in ['amsterdam', 'london', 'oslo']: > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Thu Aug 28 02:58:33 2014 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 28 Aug 2014 10:58:33 +1000 Subject: [Tutor] Interacting with stderr In-Reply-To: References: Message-ID: <20140828005833.GA64728@cskk.homeip.net> Before we proceed, two requests: Please do not top post. Post below, and trim the irrelevant content, so things read like a conversation. Please consider reading the list on an article-by-article basis instead of as a digest. You will get a better discussion view and we will see your messages in a nice threaded chain. By replying to a digest you have broken the chaining (because the digest is not part of the chain). If you find it noisy, just add a filter to your mailer to send list messages to their own folder. For example, I have a "python" mail folder which receives several python related lists, keeping it out of my main inbox. Returning to your subprocess questions... On 27Aug2014 20:28, Crush wrote: >As far as sending the contents of stderr to a tmp file...hmmm, i >will try that. My only concern is, many of these systems run live >demo feeds for many days...10+. Im afraid the file will fill up >very quickly and present problems. Ok. Then a file may not be entirely suitable to your task. >Stderr=PIPE causes the terminal to hang. I can not wait for the process to terminate, i need to read stderr as it is being fed data.. Would fifos be of any use here? First off, stderr=PIPE _is_ a FIFO; it constructs a pipe between the subprocess and your python program. However, if you need to read the stream as it occurs then you should not use "call()", which inherently waits for the command to finish. Instead, use the Popen constructor (also part of the subprocess module). Crude and incomplete and untested example: from subprocess import Popen, PIPE P = Popen("avconv ... lots of arguments...", shell=True, stderr=PIPE) for line in P.stderr: ... examine the line from stderr ... # ok, we have read all of stderr now xit = P.wait() if xit != 0: ... command was unsuccessful, complain, maybe abort ... Cheers, Cameron Simpson ep0: 3c509 in test mode. Erase pencil mark! This means that someone has scribbled with pencil in the test area on the card. Erase the pencil mark and reboot. (This is not a joke). - OpenBSD 2.3 ep(4) ethernet drive manual entry From dyoo at hashcollision.org Thu Aug 28 03:56:48 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 27 Aug 2014 18:56:48 -0700 Subject: [Tutor] Interacting with stderr In-Reply-To: <20140828005833.GA64728@cskk.homeip.net> References: <20140828005833.GA64728@cskk.homeip.net> Message-ID: > Crude and incomplete and untested example: > > from subprocess import Popen, PIPE > > P = Popen("avconv ... lots of arguments...", shell=True, stderr=PIPE) > > for line in P.stderr: > ... examine the line from stderr ... > > # ok, we have read all of stderr now > xit = P.wait() > if xit != 0: > ... command was unsuccessful, complain, maybe abort ... The subprocess documentation has a few good examples of pipelines that should apply to this scenario. I'd recommend the original questioner look at the documentation here closely, because he or she is using a feature of 'subprocess' that is a bit iffy, namely, the use of "shell=True". Try to avoid "shell=True" unless you really have no choice. Rather than construct the pipeline through the shell, do it through Python if you can. See: https://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline Also, prefer the use of communicate() rather than wait() in the scenario above. Otherwise, the code is susceptible to PIPEs getting overflowed. See: https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate Best of wishes! From cs at zip.com.au Thu Aug 28 04:59:19 2014 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 28 Aug 2014 12:59:19 +1000 Subject: [Tutor] Interacting with stderr In-Reply-To: References: Message-ID: <20140828025919.GA61370@cskk.homeip.net> On 27Aug2014 18:56, Danny Yoo wrote: >> Crude and incomplete and untested example: >> >> from subprocess import Popen, PIPE >> >> P = Popen("avconv ... lots of arguments...", shell=True, stderr=PIPE) >> >> for line in P.stderr: >> ... examine the line from stderr ... >> >> # ok, we have read all of stderr now >> xit = P.wait() >> if xit != 0: >> ... command was unsuccessful, complain, maybe abort ... > >The subprocess documentation has a few good examples of pipelines that >should apply to this scenario. I'd recommend the original questioner >look at the documentation here closely, because he or she is using a >feature of 'subprocess' that is a bit iffy, namely, the use of >"shell=True". Try to avoid "shell=True" unless you really have no >choice. Yes, but I was deliberately avoiding that aspect until the OP had their stderr issue worked out. >Rather than construct the pipeline through the shell, do it through >Python if you can. See: > https://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline But his use case is not using a shell pipeline, so irrelevant. It just makes things more complex for him. >Also, prefer the use of communicate() rather than wait() in the >scenario above. Otherwise, the code is susceptible to PIPEs getting >overflowed. See: > https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate Again, disagree. In this specific case, disagree strongly. Firstly, the OP is not feeding stuff to stdin nor collecting stdout. Secondly, the OP has made it clear that they're not in a position to wait for the command to finish; they need to read stderr as it occurs because the run time is very long and they need to act earlier than process completion. Thirdly, I generally consider advice to use .communicate bad advise. .communicate has many potential issues: Primarily, it hides all the mechanics. He will learn nothing. Next, if .call() is not doing what he needs (and it is not), then .communicate will not help either. Also, .communicate() reads in all of stdout and stderr. This has issues. He's already suggested stdout has to go somewhere else, and that he needs to read stderr in a streaming fashion. Also, by reading in all of stdout and stderr, .communicate can consume an unbounded amount of memory: either of these two streams may be more than fits in the machine's memory, or more than one wishes to use. Particularly in audio/video processing (as he is doing) there is a lot of scope for output streams to be very large. Further, the doco on .communicate does not say _how_ stdout and stderr are read. Is one read, and then the other? Are threads spawned and both read in parallel? Is there some awful select/epoll based event loop involved? None of these things is specified. If one is read and then then other, there is scope for deadlock or just arbitrary stallage. Personally, I pretty much never have a use for .call or .communicate. Using .pipe keeps the requirements on me clear and leaves me maximum flexibility to handle I/O and process completion as I see fit. As you can see from my example code, it is hardly difficult to use Popen directly in the OP's use case, and arguably better. Cheers, Cameron Simpson So YOU recant your IRRATIONAL Assertion right now or we will not LIKE YOU any more. - drieux From dyoo at hashcollision.org Thu Aug 28 07:42:09 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 27 Aug 2014 22:42:09 -0700 Subject: [Tutor] Interacting with stderr In-Reply-To: <20140828025919.GA61370@cskk.homeip.net> References: <20140828025919.GA61370@cskk.homeip.net> Message-ID: >> Rather than construct the pipeline through the shell, do it through >> Python if you can. See: >> >> https://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline > > But his use case is not using a shell pipeline, so irrelevant. It just makes > things more complex for him. Did I misread the code? Here's the snippet I thought was part of the question: >> p = subprocess.call("avconv -v verbose -re -analyzeduration 1000 -ihttp://localhost:6498/ms2/1382097438004/0MediaPlayer+0+/octoshape+hVV+octolive.americaone.com+V+aone+V+live+V+ONECONNXT_DEMO1_HD_flv/aoneliveONECONNXTDEMO1HDflv -c:v rawvideo -c:a pcm_s16le -ar 48000 -f nut - | ./bmdplay -m 12 -f pipe:0", > shell=True) where there's a pipeline between the avconv process mbdplay process. > Again, disagree. In this specific case, disagree strongly. > > Firstly, the OP is not feeding stuff to stdin nor collecting stdout. > > Secondly, the OP has made it clear that they're not in a position to wait > for the command to finish; they need to read stderr as it occurs because the > run time is very long and they need to act earlier than process completion. The OP's situation is somewhat unusual. My apologies for not reading the thread thoroughly and closely. I got distracted by the initial digest message. > Thirdly, I generally consider advice to use .communicate bad advise. > > .communicate has many potential issues: > > Primarily, it hides all the mechanics. He will learn nothing. If it helps, let me qualify the statement that communicate() is usually an appropriate solution. For simple, common cases where the interaction isn't that large or long-running, Popen.communicate() is probably the right tool. That is, I would usually recommend Popen.communicate() _unless_ the details made it the wrong tool. I misread the problem statement, so yeah, my bad. The OP's requirements are unusual: it's a long running process, it's generating a dynamic, large amount of stderr output, it's disregarding stdout, and there's a desire to process the stderr on the fly. In that situation, your solution sounds reasonable. From sebastian at fuentelibre.org Thu Aug 28 02:08:21 2014 From: sebastian at fuentelibre.org (Sebastian Silva) Date: Wed, 27 Aug 2014 19:08:21 -0500 Subject: [Tutor] debug and execute python code in Mac In-Reply-To: References: Message-ID: <1409184501.13360.1@smtp.gmail.com> I stumbled today upon this IDE for the mac http://plotdevice.io/ From the looks of it, it seems like a nice tool for teaching/learning Python. Too bad it's mac only. If you try it, do share your experience. I don't use non-free operating systems, so I can't try it myself. Regards, Sebastian El mi?, 27 de ago 2014 a las 6:14 AM, Najam Qasim escribi?: >> What is preferable method to debug and execute python code in Mac? >> I do not like the cmd/terminal execution. Thanks ! -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Thu Aug 28 08:30:02 2014 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 28 Aug 2014 16:30:02 +1000 Subject: [Tutor] Interacting with stderr In-Reply-To: References: Message-ID: <20140828063002.GA70657@cskk.homeip.net> On 27Aug2014 22:42, Danny Yoo wrote: >>> Rather than construct the pipeline through the shell, do it through >>> Python if you can. See: >>> >>> https://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline >> >> But his use case is not using a shell pipeline, so irrelevant. It just makes >> things more complex for him. > >Did I misread the code? Here's the snippet I thought was part of the question: > >>> p = subprocess.call("avconv -v verbose -re -analyzeduration 1000 -ihttp://localhost:6498/ms2/1382097438004/0MediaPlayer+0+/octoshape+hVV+octolive.americaone.com+V+aone+V+live+V+ONECONNXT_DEMO1_HD_flv/aoneliveONECONNXTDEMO1HDflv -c:v rawvideo -c:a pcm_s16le -ar 48000 -f nut - | ./bmdplay -m 12 -f pipe:0", >> shell=True) > >where there's a pipeline between the avconv process mbdplay process. You didn't misread it. I did; I missed the pipe symbol. Nonetheless, for the sake of getting his stuff working it should perhaps be chased later. In any case, he could easily be moving to putting that pipeline in a small shell script and just invoking the script from python. I've got any number of one or two line shell scripts like that. I agree that using shell=True is usually worth trying to avoid. >> Again, disagree. In this specific case, disagree strongly. >> >> Firstly, the OP is not feeding stuff to stdin nor collecting stdout. >> >> Secondly, the OP has made it clear that they're not in a position to wait >> for the command to finish; they need to read stderr as it occurs because the >> run time is very long and they need to act earlier than process completion. > >The OP's situation is somewhat unusual. My apologies for not reading >the thread thoroughly and closely. I got distracted by the initial >digest message. I can imagine. I'm not a big fan of digests. >> Thirdly, I generally consider advice to use .communicate bad advise. >> >> .communicate has many potential issues: >> >> Primarily, it hides all the mechanics. He will learn nothing. > >If it helps, let me qualify the statement that communicate() is >usually an appropriate solution. For simple, common cases where the >interaction isn't that large or long-running, Popen.communicate() is >probably the right tool. That is, I would usually recommend >Popen.communicate() _unless_ the details made it the wrong tool. I >misread the problem statement, so yeah, my bad. > >The OP's requirements are unusual: it's a long running process, it's >generating a dynamic, large amount of stderr output, it's disregarding >stdout, and there's a desire to process the stderr on the fly. In >that situation, your solution sounds reasonable. Ta. The other thing about communicate and (less so) call is that they do so much. When a particular part isn't working, figuring out what to fix is harder. On a tutor list, what's our stance on exploring the operation at a lower level so the OP gets a better feel for what's going on? I'm aware we don't need to agree on that stance:-) Cheers, Cameron Simpson It is very easy to be blinded to the essential uselessness of them by the sense of achievement you get from getting them to work at all. In other words - their fundamental design flaws are completely hidden by their superficial design flaws. - Douglas Adams on VCRs etc From alan.gauld at btinternet.com Thu Aug 28 09:13:33 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Aug 2014 08:13:33 +0100 Subject: [Tutor] Interacting with stderr In-Reply-To: <20140828063002.GA70657@cskk.homeip.net> References: <20140828063002.GA70657@cskk.homeip.net> Message-ID: On 28/08/14 07:30, Cameron Simpson wrote: > On a tutor list, what's our stance on exploring the operation at a lower > level so the OP gets a better feel for what's going on? I'm aware we > don't need to agree on that stance:-) Its OK if the OP will understand it. Just explaining the detail of itself is not always helpful when dealing with a real programming beginner. But if the OP (or a subsequent participant) demonstrates that a fuller explanation of the mechanisms involved is worthwhile then by akll means do so. hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From shak1email at googlemail.com Thu Aug 28 13:20:35 2014 From: shak1email at googlemail.com (Shakoor Hajat) Date: Thu, 28 Aug 2014 12:20:35 +0100 Subject: [Tutor] Regression analysis using statsmodels: linear combinations Message-ID: Hello I would very much appreciate any help with the following query: I am running a regression analysis in Python using statsmodels and wish to obtain the combined effect of a number of the explanatory variables in the model. I could simply sum the individual coefficients to obtain my effect estimate but this wouldn't work for the standard errors due to covariance. Is there a straightforward way in statsmodels to derive the linear combination of coefficients? Many thanks in advance. S -------------- next part -------------- An HTML attachment was scrubbed... URL: From wrw at mac.com Thu Aug 28 14:41:51 2014 From: wrw at mac.com (William Ray Wing) Date: Thu, 28 Aug 2014 08:41:51 -0400 Subject: [Tutor] debug and execute python code in Mac In-Reply-To: <1409184501.13360.1@smtp.gmail.com> References: <1409184501.13360.1@smtp.gmail.com> Message-ID: <8840D54E-97AF-4088-906B-264A1A2A0E1F@mac.com> On Aug 27, 2014, at 8:08 PM, Sebastian Silva wrote: > I stumbled today upon this IDE for the mac http://plotdevice.io/ > > From the looks of it, it seems like a nice tool for teaching/learning Python. Too bad it's mac only. If you try it, do share your experience. I don't use non-free operating systems, so I can't try it myself. > > Regards, > > Sebastian Just as an aside ? Apple has stopped charging for OS-X. -Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwpolska at gmail.com Thu Aug 28 14:49:37 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Thu, 28 Aug 2014 14:49:37 +0200 Subject: [Tutor] debug and execute python code in Mac In-Reply-To: <8840D54E-97AF-4088-906B-264A1A2A0E1F@mac.com> References: <1409184501.13360.1@smtp.gmail.com> <8840D54E-97AF-4088-906B-264A1A2A0E1F@mac.com> Message-ID: On Thu, Aug 28, 2014 at 2:41 PM, William Ray Wing wrote: > On Aug 27, 2014, at 8:08 PM, Sebastian Silva wrote: >> Too bad it's mac only. If you try it, do share your experience. I don't use non-free operating systems, so I can't try it myself. > > Just as an aside ? Apple has stopped charging for OS-X. Sebastan probably meant ?free? as in Stallman: http://www.gnu.org/philosophy/free-sw.html (most people believe free = $0. FSF people, however, want to steal that word for their concept. Not very successful at that, as you can see.) -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From crushed26 at gmail.com Thu Aug 28 15:42:17 2014 From: crushed26 at gmail.com (Crush) Date: Thu, 28 Aug 2014 09:42:17 -0400 Subject: [Tutor] Interacting with stderr In-Reply-To: <20140828063002.GA70657@cskk.homeip.net> References: <20140828063002.GA70657@cskk.homeip.net> Message-ID: So, are yall done arguing haha...jk! Seriously, thank you for taking the time to pick this issue apart with me. Cameron your "learning" comment was right on; my ultimate goal in posting here is to learn and of course to figure out my code. As far as the pipe in... "avconv -v verbose -re -analyzeduration 1000 -ihttp://localhost:6498/ms2/1382097438004/0MediaPlayer+0+/octoshape+hVV+octolive.americaone.com+V+aone+V+live+V+ONECONNXTDEMO1_HD_flv/aoneliveONECONNXTDEMO1HDflv -c:v rawvideo -c:a pcm_s16le -ar 48000 -f nut - | ./bmdplay -m 12 -f pipe:0" ...it has to be there. Currently, i am running a shell script that is handling this decoding process i.e. the real long avconv/bmdplay command. So you are saying leave the shell script and invoke it from a python script...something like "p = subprocess.Popen("./my_script.sh")? How will the above allow me to interact with stderr in oppose to running the avconv/bmdplay command directly in python? As far as not using "shell=True," if I dont have it set to True, the terminal hangs and will not display stderr to the screen as it is currently does. Bo From alan.gauld at btinternet.com Thu Aug 28 18:41:04 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Aug 2014 17:41:04 +0100 Subject: [Tutor] Regression analysis using statsmodels: linear combinations In-Reply-To: References: Message-ID: On 28/08/14 12:20, Shakoor Hajat wrote: > I would very much appreciate any help with the following query: > I am running a regression analysis in Python using statsmodels and wish > to obtain the combined effect of a number of the explanatory variables > in the model. I could simply sum the individual coefficients to obtain > my effect estimate but this wouldn't work for the standard errors due to > covariance. Is there a straightforward way in statsmodels to derive the > linear combination of coefficients? This list is for people learning the basic python language and standard library. This question looks a tad advanced for that audience. In fact I suspect that many(most?) of the folks on this list (including me) have only a hazy idea what you are talking about in your post. However there are some data analysts amongst us so they may be able to help. If we knew what toolkits you were using to do the analysis we might be able to suggest a better forum? eg numpy, RPy or pandas? Also what version of Python you had( 2 or 3?). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From abidsaied at gmail.com Thu Aug 28 14:02:39 2014 From: abidsaied at gmail.com (abid saied) Date: Thu, 28 Aug 2014 13:02:39 +0100 Subject: [Tutor] Tutoring Message-ID: <515C2D31-767E-4C4F-B165-6EA3956D8B36@gmail.com> Hi, would anyone like to provide some face to face guidance/tutoring? My post code is BL3 2LR, I?m happy to offer a nice meal, my wife makes some really good curries! thanks. Abid Saied abidsaied at gmail.com From alan.gauld at btinternet.com Thu Aug 28 18:48:54 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Aug 2014 17:48:54 +0100 Subject: [Tutor] Tutoring In-Reply-To: <515C2D31-767E-4C4F-B165-6EA3956D8B36@gmail.com> References: <515C2D31-767E-4C4F-B165-6EA3956D8B36@gmail.com> Message-ID: On 28/08/14 13:02, abid saied wrote: > would anyone like to provide some face to face guidance/tutoring? > My post code is BL3 2LR, That looks like a UK post code? Are you in the UK? This list is international in membership, we have folks from the US, Canada, Australia, India, Japan, all over in fact. We don't normally do 1 on 1 tutorship but if you are lucky and somebody volunteers that's OK. But if you want to post questions here we will all do our best to answer them. > I?m happy to offer a nice meal, my wife makes some > really good curries! Yum... :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From leamhall at gmail.com Thu Aug 28 20:03:03 2014 From: leamhall at gmail.com (leam hall) Date: Thu, 28 Aug 2014 14:03:03 -0400 Subject: [Tutor] Import from project's lib directory? Message-ID: python 2.4.3 on Red Hat Linux. I'm starting a project and want to break the scripts into "input", "output", and "ddl". I'd like to have a "lib" library directory for local modules. The library directory would be at the same level as the others. How do I get the library modules? import '../lib/mymodule' Fails on syntax. Thanks! Leam -- Mind on a Mission From dyoo at hashcollision.org Thu Aug 28 20:19:44 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 28 Aug 2014 11:19:44 -0700 Subject: [Tutor] Import from project's lib directory? In-Reply-To: References: Message-ID: On Thu, Aug 28, 2014 at 11:03 AM, leam hall wrote: > python 2.4.3 on Red Hat Linux. > > I'm starting a project and want to break the scripts into "input", > "output", and "ddl". I'd like to have a "lib" library directory for > local modules. The library directory would be at the same level as the > others. > > How do I get the library modules? > > import '../lib/mymodule' You're looking for relative imports: https://docs.python.org/2.5/whatsnew/pep-328.html So for your case, perhaps: from ..lib import mymodule Alternatively, perhaps refer to the modules by toplevel package instead of relative path? From leamhall at gmail.com Thu Aug 28 21:13:42 2014 From: leamhall at gmail.com (leam hall) Date: Thu, 28 Aug 2014 15:13:42 -0400 Subject: [Tutor] Import from project's lib directory? In-Reply-To: References: Message-ID: On Thu, Aug 28, 2014 at 2:19 PM, Danny Yoo wrote: > On Thu, Aug 28, 2014 at 11:03 AM, leam hall wrote: >> python 2.4.3 on Red Hat Linux. >> >> I'm starting a project and want to break the scripts into "input", >> "output", and "ddl". I'd like to have a "lib" library directory for >> local modules. The library directory would be at the same level as the >> others. >> >> How do I get the library modules? >> >> import '../lib/mymodule' > > > You're looking for relative imports: > > https://docs.python.org/2.5/whatsnew/pep-328.html > > So for your case, perhaps: > > from ..lib import mymodule > > Alternatively, perhaps refer to the modules by toplevel package > instead of relative path? Fails on both Python 2.4 and 2.6 with either ".lib" or "..lib". ### code #!/usr/bin/env python from ..lib import mymodule #### In python/ddl, referencing ../lib/mymodule.py ./import_test.py Traceback (most recent call last): File "./import_test.py", line 3, in from .lib import mymodule ValueError: Attempted relative import in non-package ls ../lib mymodule.py -- Mind on a Mission From dyoo at hashcollision.org Thu Aug 28 21:27:05 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 28 Aug 2014 12:27:05 -0700 Subject: [Tutor] Import from project's lib directory? In-Reply-To: References: Message-ID: > > Fails on both Python 2.4 and 2.6 with either ".lib" or "..lib". > > ### code > #!/usr/bin/env python > > from ..lib import mymodule > #### > > In python/ddl, referencing ../lib/mymodule.py > > ./import_test.py > Traceback (most recent call last): > File "./import_test.py", line 3, in > from .lib import mymodule > ValueError: Attempted relative import in non-package The word "package" has a technical meaning. Here's a description: https://docs.python.org/2/tutorial/modules.html#packages Can you use packages to structure your code directory? You'll need "__init__.py" files in the directories that are to be treated as packages. If you can structure your program into packages, then intra-package imports should work: https://docs.python.org/2/tutorial/modules.html#intra-package-references From leamhall at gmail.com Thu Aug 28 22:19:44 2014 From: leamhall at gmail.com (leam hall) Date: Thu, 28 Aug 2014 16:19:44 -0400 Subject: [Tutor] Import from project's lib directory? In-Reply-To: References: Message-ID: On Thu, Aug 28, 2014 at 3:27 PM, Danny Yoo wrote: >> >> Fails on both Python 2.4 and 2.6 with either ".lib" or "..lib". >> >> ### code >> #!/usr/bin/env python >> >> from ..lib import mymodule >> #### >> >> In python/ddl, referencing ../lib/mymodule.py >> >> ./import_test.py >> Traceback (most recent call last): >> File "./import_test.py", line 3, in >> from .lib import mymodule >> ValueError: Attempted relative import in non-package > > > The word "package" has a technical meaning. Here's a description: > > https://docs.python.org/2/tutorial/modules.html#packages > > Can you use packages to structure your code directory? You'll need > "__init__.py" files in the directories that are to be treated as > packages. > > > If you can structure your program into packages, then intra-package > imports should work: > > https://docs.python.org/2/tutorial/modules.html#intra-package-references I put empty __init.py__ files in both directories and a few parents. Still no go. -- Mind on a Mission From alan.gauld at btinternet.com Thu Aug 28 23:36:56 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Aug 2014 22:36:56 +0100 Subject: [Tutor] Import from project's lib directory? In-Reply-To: References: Message-ID: On 28/08/14 19:03, leam hall wrote: > python 2.4.3 on Red Hat Linux. > > I'm starting a project and want to break the scripts into "input", > "output", and "ddl". I'd like to have a "lib" library directory for > local modules. The library directory would be at the same level as the > others. > > How do I get the library modules? Add lib to the sys.path list? That may not be viable if you need it to be portable across systems, although using os.getcwd to locate the current folder or an environment variable to store the app root folder might be options there. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From cs at zip.com.au Fri Aug 29 00:12:28 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 29 Aug 2014 08:12:28 +1000 Subject: [Tutor] Interacting with stderr In-Reply-To: References: Message-ID: <20140828221228.GA84495@cskk.homeip.net> On 28Aug2014 09:42, Crush wrote: >As far as the pipe in... > >"avconv -v verbose -re -analyzeduration 1000 -ihttp://localhost:6498/ms2/1382097438004/0MediaPlayer+0+/octoshape+hVV+octolive.americaone.com+V+aone+V+live+V+ONECONNXTDEMO1_HD_flv/aoneliveONECONNXTDEMO1HDflv -c:v rawvideo -c:a pcm_s16le -ar 48000 -f nut - | ./bmdplay -m 12 -f pipe:0" > >...it has to be there. Indeed. We're not arguing about that. Leave it there for. >Currently, i am running a shell script that is handling this decoding process i.e. the real long avconv/bmdplay command. So you are saying leave the shell script and invoke it from a python script...something like "p = subprocess.Popen("./my_script.sh")? How will the above allow me to interact with stderr in oppose to running the avconv/bmdplay command directly in python? No, we're no saying that. You could (and presumably do) have this long incantation in your shell script. As far as the Python stuff goes, that does not change anything: you can invoke your shell script or invoke your long command directly. Either way you need to grab the stderr on the fly and work with it. Personally, I would keep the pipeline in the shell script where it is easier to edit and invoke the script from Python (easier to read). Your call. >As far as not using "shell=True," if I dont have it set to True, the terminal hangs and will not display stderr to the screen as it is currently does. Let's tackle shell=True later. What you need to do is examine stderr before the shell script/pipeline is complete, and for that you need to separate starting the process, reading stderr, and waiting for process completion into distinct parts, which was what my example code was doing. I'll recite it again here: from subprocess import Popen, PIPE P = Popen("avconv ... lots of arguments...", shell=True, stderr=PIPE) for line in P.stderr: ... examine the line from stderr ... # ok, we have read all of stderr now xit = P.wait() if xit != 0: ... command was unsuccessful, complain, maybe abort ... Please try adapting your Python code to that and see where you end up. Put a print statement as the first line in the for-loop so you can see if you are receiving stderr lines as intended. Cheers, Cameron Simpson As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs. - Maurice Wilkes discovers debugging, 1949 From crushed26 at gmail.com Fri Aug 29 00:25:48 2014 From: crushed26 at gmail.com (Crush) Date: Thu, 28 Aug 2014 18:25:48 -0400 Subject: [Tutor] Quick question for Tutor admin. Message-ID: <97D16479-EC96-4CC3-A424-CCF0EE13D23A@gmail.com> Am I allowed to attach screen shots to my emails? Bo From cs at zip.com.au Fri Aug 29 00:39:48 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 29 Aug 2014 08:39:48 +1000 Subject: [Tutor] Import from project's lib directory? In-Reply-To: References: Message-ID: <20140828223948.GA47105@cskk.homeip.net> On 28Aug2014 22:36, Alan Gauld wrote: >On 28/08/14 19:03, leam hall wrote: >>python 2.4.3 on Red Hat Linux. >> >>I'm starting a project and want to break the scripts into "input", >>"output", and "ddl". I'd like to have a "lib" library directory for >>local modules. The library directory would be at the same level as the >>others. >> >>How do I get the library modules? > >Add lib to the sys.path list? > >That may not be viable if you need it to be portable across systems, >although using os.getcwd to locate the current folder or an >environment variable to store the app root folder might be >options there. I tend to modify $PYTHONPATH outside the script. It means the script is not responsible for figuring this stuff out, and it also makes it easier to run the "development" version when working. For example, if I'm off modifying stuff in a copy of the code I test it by issuing the command: dev python -m the.python.module arguments... "dev" is a short shell script of my own whose purpose it to set things up to run "here", and then run the command supplied ("python"). Among other things it prepends "$PWD/lib/python" to $PYTHONPATH, as that is where my modules live. In this way it runs the hacked module instead of running the "official" version. The OP would prepend "$PWD/lib" in the same scenario. Cheers, Cameron Simpson Invoking the supernatural can explain anything, and hence explains nothing. - University of Utah bioengineering professor Gregory Clark From cs at zip.com.au Fri Aug 29 00:45:50 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 29 Aug 2014 08:45:50 +1000 Subject: [Tutor] Regression analysis using statsmodels: linear combinations In-Reply-To: References: Message-ID: <20140828224550.GA65981@cskk.homeip.net> On 28Aug2014 17:41, Alan Gauld wrote: >On 28/08/14 12:20, Shakoor Hajat wrote: >>I would very much appreciate any help with the following query: >>I am running a regression analysis in Python using statsmodels and wish >>to obtain the combined effect of a number of the explanatory variables >>in the model. I could simply sum the individual coefficients to obtain >>my effect estimate but this wouldn't work for the standard errors due to >>covariance. Is there a straightforward way in statsmodels to derive the >>linear combination of coefficients? > >This list is for people learning the basic python language and >standard library. This question looks a tad advanced for that >audience. In fact I suspect that many(most?) of the folks on >this list (including me) have only a hazy idea what you are >talking about in your post. > >However there are some data analysts amongst us so they may >be able to help. > >If we knew what toolkits you were using to do the analysis we >might be able to suggest a better forum? eg numpy, RPy or pandas? >Also what version of Python you had( 2 or 3?). It looks like he's using this: http://statsmodels.sourceforge.net/ Works in python 2 and 3, but does not seem to have a dedicated mailing list. Shakoor, if you get no responses here, ask again on python-list: I know there are some statistics and floating point savvy people there. Cheers, Cameron Simpson To be positive: To be mistaken at the top of one's voice. Ambrose Bierce (1842-1914), U.S. author. The Devil's Dictionary (1881-1906). From cs at zip.com.au Fri Aug 29 00:51:32 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 29 Aug 2014 08:51:32 +1000 Subject: [Tutor] Quick question for Tutor admin. In-Reply-To: <97D16479-EC96-4CC3-A424-CCF0EE13D23A@gmail.com> References: <97D16479-EC96-4CC3-A424-CCF0EE13D23A@gmail.com> Message-ID: <20140828225132.GA74421@cskk.homeip.net> On 28Aug2014 18:25, Crush wrote: >Am I allowed to attach screen shots to my emails? I am not the list admin, but generally no. Please insert plain text into your posts. Many lists strip attachments, and many people on technical lists are (deliberately) working in a purely text environment. If your screenshot is inherently graphical, publish it elsewhere (eg save it to Dropbox and get a "public link") and mention the link in your post, with some textual description. But for text, we like it inline in the message itself. Cheers, Cameron Simpson in rec.moto, jsh wrote: > Dan Nitschke wrote: > > Ged Martin wrote: > > > On Sat, 17 May 1997 16:53:33 +0000, Dan Nitschke scribbled: > > > >(And you stay *out* of my dreams, you deviant little > > > >weirdo.) > > > Yeah, yeah, that's what you're saying in _public_.... > > Feh. You know nothing of my dreams. I dream entirely in text (New Century > > Schoolbook bold oblique 14 point), and never in color. I once dreamed I > > was walking down a flowchart of my own code, and a waterfall of semicolons > > was chasing me. (I hid behind a global variable until they went by.) > You write code in a proportional serif? No wonder you got extra > semicolons falling all over the place. No, I *dream* about writing code in a proportional serif font. It's much more exciting than my real life. /* dan: THE Anti-Ged -- Ignorant Yank (tm) #1, none-%er #7 */ Dan Nitschke peDANtic at best.com nitschke at redbrick.com From dyoo at hashcollision.org Fri Aug 29 00:52:12 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 28 Aug 2014 15:52:12 -0700 Subject: [Tutor] Quick question for Tutor admin. In-Reply-To: <97D16479-EC96-4CC3-A424-CCF0EE13D23A@gmail.com> References: <97D16479-EC96-4CC3-A424-CCF0EE13D23A@gmail.com> Message-ID: On Thu, Aug 28, 2014 at 3:25 PM, Crush wrote: > Am I allowed to attach screen shots to my emails? Hi Bo, If the informational content can be represented textually, then please try to avoid screenshots in favor of copy-and-paste. There are a few reasons for it. But one major reason why text is preferable because search engines work effectively with text. If I see a question that uses a certain unusual term, the first instinct I have is to enter that term into a search engine. As a concrete example, see: https://mail.python.org/pipermail/tutor/2014-August/102347.html As a point of confession: for the message above, I knew absolutely nothing about what the questioner was asking about. But I do know how to use a search engine fairly well. :P This sort of archaeology becomes much harder if screenshots are the norm. So try to avoid them, at least for technical forums where UI is not the focus. Thanks! From cs at zip.com.au Fri Aug 29 01:06:11 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 29 Aug 2014 09:06:11 +1000 Subject: [Tutor] Regression analysis using statsmodels: linear combinations In-Reply-To: <20140828224550.GA65981@cskk.homeip.net> References: <20140828224550.GA65981@cskk.homeip.net> Message-ID: <20140828230611.GA7027@cskk.homeip.net> On 29Aug2014 08:45, Cameron Simpson wrote: >It looks like he's using this: > http://statsmodels.sourceforge.net/ >Works in python 2 and 3, but does not seem to have a dedicated mailing list. Hmm. There's a mailing list here: https://groups.google.com/forum/?hl=en#!forum/pystatsmodels That is probably the best place to ask. Cheers, Cameron Simpson My computer always does exactly what I tell it to do but sometimes I have trouble finding out what it was that I told it to do. - Dick Wexelblat From alan.gauld at btinternet.com Fri Aug 29 01:49:47 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 29 Aug 2014 00:49:47 +0100 Subject: [Tutor] Quick question for Tutor admin. In-Reply-To: <97D16479-EC96-4CC3-A424-CCF0EE13D23A@gmail.com> References: <97D16479-EC96-4CC3-A424-CCF0EE13D23A@gmail.com> Message-ID: On 28/08/14 23:25, Crush wrote: > Am I allowed to attach screen shots to my emails? We can't stop you, but we prefer text. Not least because some members can't receive anything but text. Also some pay by the byte and images tend to be big and thus expensive. So you would limit the visibility and hence the potential numbers who can respond. If its a shot of your terminal session then you can simply cut n paste the text from the Terminal into your mail. Many other dev tools/editors permit the same. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From lnartist at yahoo.com Fri Aug 29 02:52:35 2014 From: lnartist at yahoo.com (LN A-go-go) Date: Thu, 28 Aug 2014 17:52:35 -0700 Subject: [Tutor] sorting distances for nearest neighbor Message-ID: <1409273555.47158.YahooMailNeo@web161304.mail.bf1.yahoo.com> Python Gurus, How do you sort distances to prepare for nearest neighbor when the results returned look like this from the below statements? DR=distance(n,XCOORDINATE, YCOORDINATE, IDCODE) DZ=switch(n,XCOORDINATE, YCOORDINATE, IDCODE) Distance from 1 to 16 is 43763.0757603 19 is 126516.988978 18 is 131011.694135 15 is 156251.651191 17 is 157090.833596 14 is 170437.744646 13 is 174344.799177 20 is 175368.495745 11 is 235415.474428 10 is 236267.509404 12 is 240007.657586 9 is 253298.673506 4 is 318134.525162 2 is 342924.627433 5 is 344436.98248 6 is 371599.399488 3 is 374494.086068 8 is 389923.9631 7 is 393889.530199 Distance from 2 to 3 is 32471.4335994 9 is 126093.246845 6 is 135032.661234 10 is 145083.703082 11 is 153462.088152 12 is 155269.121206 4 is 156434.810704 7 is 161054.471841 5 is 161119.250867 20 is 169483.547284 8 is 173243.878103 17 is 210880.788362 18 is 216248.340803 19 is 218147.66971 13 is 220831.360318 14 is 225608.192449 15 is 226192.408803 16 is 305477.356444 1 is 342924.627433 Distance from 3 to..................... LN -------------- next part -------------- An HTML attachment was scrubbed... URL: From diliupg at gmail.com Fri Aug 29 11:00:10 2014 From: diliupg at gmail.com (diliup gabadamudalige) Date: Fri, 29 Aug 2014 14:30:10 +0530 Subject: [Tutor] extracting a cPickle/pickle file from inside a zip file Message-ID: HI! To all, with open(from_dir + "\\" + name_py,"wb") as outfile: cPickle.dump(str1,outfile) after doing above I zip the file with some other files into a password secured zip file using win rar. I can extract all other files except the py file. pload = cPickle.load(zf.open("my.py",pwd=password)) this gives an EOF . Does any body know why? Can anyone show how to extract a pickle file from a zipfile? Thanks in advance Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ********************************************************************************************** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ********************************************************************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From amonroe at columbus.rr.com Fri Aug 29 12:30:05 2014 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Fri, 29 Aug 2014 06:30:05 -0400 Subject: [Tutor] sorting distances for nearest neighbor In-Reply-To: <1409273555.47158.YahooMailNeo@web161304.mail.bf1.yahoo.com> References: <1409273555.47158.YahooMailNeo@web161304.mail.bf1.yahoo.com> Message-ID: <1071257314.20140829063005@columbus.rr.com> > How do you sort distances to prepare for nearest neighbor when the > results returned look like this Have you read up on the "key" parameter for Python's sort() function? You can use that, along with split() to do this. Alan From alan.gauld at btinternet.com Fri Aug 29 13:31:06 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 29 Aug 2014 12:31:06 +0100 Subject: [Tutor] extracting a cPickle/pickle file from inside a zip file In-Reply-To: References: Message-ID: On 29/08/14 10:00, diliup gabadamudalige wrote: > pload = cPickle.load(zf.open("my.py",pwd=password)) > this gives an EOF > > . Does any body know why? I've never used zipfile so I don't know, but could it be related to the fact that your pickle file is binary? Do you need any flags to tell zipfile that you're extracting a binary file? Just a thought, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From davea at davea.name Fri Aug 29 14:02:50 2014 From: davea at davea.name (Dave Angel) Date: Fri, 29 Aug 2014 08:02:50 -0400 (EDT) Subject: [Tutor] sorting distances for nearest neighbor References: <1409273555.47158.YahooMailNeo@web161304.mail.bf1.yahoo.com> Message-ID: LN A-go-go Wrote in message: > Please tell your email program to use text when posting here, The html you used can cause numerous problems. One of them prevents me from quoting context. If you can get your data to a list of tuples, then you can sort that list by something like sorteddata = sorted (data, key = dist) Of course you have to write dist. Something like def dist (tup): return distance (tup [3], tup [0], tup [1], tup [2] But of course this depends greatly on the contents of the tuple. You can also skip the sorting if you just want the lowest value by doing mintuple = min (data, key= dist) Or if you need the 3 closest, you can use heapq.nsmallest -- DaveA From leamhall at gmail.com Fri Aug 29 15:07:06 2014 From: leamhall at gmail.com (leam hall) Date: Fri, 29 Aug 2014 09:07:06 -0400 Subject: [Tutor] Import from project's lib directory? In-Reply-To: <20140828223948.GA47105@cskk.homeip.net> References: <20140828223948.GA47105@cskk.homeip.net> Message-ID: On Thu, Aug 28, 2014 at 6:39 PM, Cameron Simpson wrote: > On 28Aug2014 22:36, Alan Gauld wrote: >> >> On 28/08/14 19:03, leam hall wrote: >>> >>> python 2.4.3 on Red Hat Linux. >>> >>> I'm starting a project and want to break the scripts into "input", >>> "output", and "ddl". I'd like to have a "lib" library directory for >>> local modules. The library directory would be at the same level as the >>> others. >>> >>> How do I get the library modules? >> >> >> Add lib to the sys.path list? >> >> That may not be viable if you need it to be portable across systems, >> although using os.getcwd to locate the current folder or an >> environment variable to store the app root folder might be >> options there. The code will be imported to other machines so whatever I'm doing must be portable. Right now my code looks like this: ### ## lib/mymodule.py #!/usr/bin/env python def howdy(): print("in mymodule") ### ## input/test_lib.py #!/usr/bin/env python from ..lib import mymodule mymodule.howdy() ### ## Directory tree: . ./input ./input/__init.py__ ./input/test_lib.py ./lib ./lib/mymodule.py ./lib/__init.py__ ./output ## In input, running test_lib.py ./test_lib.py Traceback (most recent call last): File "./test_lib.py", line 3, in from ..lib import mymodule ValueError: Attempted relative import in non-package ## the __init.py__ files are empty. -- Mind on a Mission From leamhall at gmail.com Fri Aug 29 16:25:24 2014 From: leamhall at gmail.com (leam hall) Date: Fri, 29 Aug 2014 10:25:24 -0400 Subject: [Tutor] Import from project's lib directory? In-Reply-To: References: <20140828223948.GA47105@cskk.homeip.net> Message-ID: On Fri, Aug 29, 2014 at 9:39 AM, diliup gabadamudalige wrote: > this is the easiest way to do this > > # one.py is in the \data\ directory > # two.py is in the \data\img\ directory > # three.py is in the \data\img\sc\ directory > > ## this program is in the learn_music dir > > ## expanding the file path add a . before the new dir > > ## each directory you need to load a module from needs to have __init__.py > file inside the directory. It can be an empty file but it needs to be there. > That's how python knows that you can load a module from this directory. my > one.py, two.py and three.py modules each have a string called a in it. You > can have classes or functions which can be called in the same way. > > from data import one # / data/ > from data .img import two # /data/img/ > from data .img.sc import three # /data/img/sc/ > > print one.a, two.a, three.a > > hope this helps So far this doesn't work. I'm pretty convinced it's either a Python version issue (2.4.3 and 2.6.6.) or pure Operator Error. Leaning towards the latter. Thanks! Leam -- Mind on a Mission From diliupg at gmail.com Fri Aug 29 15:19:47 2014 From: diliupg at gmail.com (diliup gabadamudalige) Date: Fri, 29 Aug 2014 18:49:47 +0530 Subject: [Tutor] extracting a cPickle/pickle file from inside a zip file In-Reply-To: References: Message-ID: http://stackoverflow.com/questions/3006727/load-a-pickle-file-from-a-zipfile zf = czipfile.ZipFile(r"cpickletest.zip") pyfromzip = zf.read ("cPickletest.py", pwd="python") print pyfromzip, type(pyfromzip) this prints the following to the console (dp1 S'kola.jpg' p2 S'CSVTQq#w. at lm' p3 sS'p2.jpg' p4 S'CSVT$S. at lm' p5 sS'p1.jpg' p6 S'CSVT3S. at lm' p7 s. most probably this is the dictionary file written to disk as the keys and values are all there. now if i do this outfile = cStringIO.StringIO() outfile.write(pyfromzip) z=cPickle.load(outfile) it returns -> EOFError: I tried various experiments and the code below worked. filenames # this is a dictionary with open(p + "\\coded\\" + name_py,"wb") as outfile: cPickle.dump(str(filenames), outfile) # pickled dumped the dictionary as a string now the file is locked up in a pwd prtected zipfile using winrar zf = czipfile.ZipFile(r"cpickletest.zip") pyfromzip = zf.read ("cPickletest.py", pwd="password") c = pyfromzip.partition('"')[-1].rpartition('"')[0] c = eval(c) print c, type(c) # this gave back the original dictionary can someone think of a better way? On Fri, Aug 29, 2014 at 6:25 PM, diliup gabadamudalige wrote: > Alan, thanks for the reply. > nope. I tried both ways. Btw I am using Python 2.7.8. > This seem to be a problem with python itself. > > > http://stackoverflow.com/questions/3006727/load-a-pickle-file-from-a-zipfile > > zf = czipfile.ZipFile(r"cpickletest.zip") > pyfromzip = zf.read ("cPickletest.py", pwd="python") > print pyfromzip, type(pyfromzip) > > this prints the following to the console > > (dp1 > S'kola.jpg' > p2 > S'CSVTQq#w. at lm' > p3 > sS'p2.jpg' > p4 > S'CSVT$S. at lm' > p5 > sS'p1.jpg' > p6 > S'CSVT3S. at lm' > p7 > s. > > most probably this is the dictionary file written to disk as the keys and > values are all there. > > now if i do this > > outfile = cStringIO.StringIO() > outfile.write(pyfromzip) > z=cPickle.load(outfile) > it returns -> EOFError: > > > > On Fri, Aug 29, 2014 at 5:01 PM, Alan Gauld > wrote: > >> On 29/08/14 10:00, diliup gabadamudalige wrote: >> >> pload = cPickle.load(zf.open("my.py",pwd=password)) >>> this gives an EOF >>> >>> . Does any body know why? >>> >> >> I've never used zipfile so I don't know, but could it be >> related to the fact that your pickle file is binary? >> Do you need any flags to tell zipfile that you're >> extracting a binary file? >> >> Just a thought, >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> 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 >> > > > > -- > Diliup Gabadamudalige > > http://www.diliupg.com > http://soft.diliupg.com/ > > > ********************************************************************************************** > This e-mail is confidential. It may also be legally privileged. If you are > not the intended recipient or have received it in error, please delete it > and all copies from your system and notify the sender immediately by return > e-mail. Any unauthorized reading, reproducing, printing or further > dissemination of this e-mail or its contents is strictly prohibited and may > be unlawful. Internet communications cannot be guaranteed to be timely, > secure, error or virus-free. The sender does not accept liability for any > errors or omissions. > > ********************************************************************************************** > > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ********************************************************************************************** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ********************************************************************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From dillonrw at comcast.net Fri Aug 29 17:01:17 2014 From: dillonrw at comcast.net (Richard Dillon) Date: Fri, 29 Aug 2014 08:01:17 -0700 Subject: [Tutor] Python 3.4.1 question for Mac users Message-ID: <6B42F399-C5B9-41E5-BC1F-2145E9770364@comcast.net> I?m teaching myself Python 3.4.1 on a Mac and the book I?m using is written for Windows users. I?m trying to open a file on the desktop and I created a path using the example in the book. Any Mac users out there with a solution? My main drive is named ?OS?. Here?s my code: def main(): my_file = input('Enter file to open: ') infile = open(r'\OS\Users\richarddillon\Desktop\my_file','r') file_contents = infile.read() infile.close() print(file.contents) main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwpolska at gmail.com Fri Aug 29 18:37:41 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Fri, 29 Aug 2014 18:37:41 +0200 Subject: [Tutor] Python 3.4.1 question for Mac users In-Reply-To: <6B42F399-C5B9-41E5-BC1F-2145E9770364@comcast.net> References: <6B42F399-C5B9-41E5-BC1F-2145E9770364@comcast.net> Message-ID: On Fri, Aug 29, 2014 at 5:01 PM, Richard Dillon wrote: > I?m teaching myself Python 3.4.1 on a Mac and the book I?m using is written > for Windows users. > > I?m trying to open a file on the desktop and I created a path using the > example in the book. > > > > Any Mac users out there with a solution? My main drive is named ?OS?. > > Here?s my code: > > > > def main(): > > my_file = input('Enter file to open: ') > > infile = open(r'\OS\Users\richarddillon\Desktop\my_file','r') > > file_contents = infile.read() > > infile.close() > > print(file.contents) > > > > main() > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From kwpolska at gmail.com Fri Aug 29 18:39:49 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Fri, 29 Aug 2014 18:39:49 +0200 Subject: [Tutor] Python 3.4.1 question for Mac users In-Reply-To: <6B42F399-C5B9-41E5-BC1F-2145E9770364@comcast.net> References: <6B42F399-C5B9-41E5-BC1F-2145E9770364@comcast.net> Message-ID: Sorry for the errorneous quote-only response, gmail managed to send it without me typing a thing. On Fri, Aug 29, 2014 at 5:01 PM, Richard Dillon wrote: > infile = open(r'\OS\Users\richarddillon\Desktop\my_file','r') On the Mac, you don?t need to specify a drive there; the main drive is just /. Also, the path separator is a forward slash (/). This also lets you remove the r in front of the string, which is needed for backslashes unless you escape them. The corrected code is: infile = open('/Users/richarddillon/Desktop/my_file', 'r') -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From a.bull at pubdmgroup.com Fri Aug 29 18:55:38 2014 From: a.bull at pubdmgroup.com (Al Bull) Date: Fri, 29 Aug 2014 11:55:38 -0500 Subject: [Tutor] Python 3.4.1 question for Mac users In-Reply-To: References: <6B42F399-C5B9-41E5-BC1F-2145E9770364@comcast.net> Message-ID: <00ff01cfc3aa$10005e70$30011b50$@pubdmgroup.com> -----Original Message----- From: Tutor [mailto:tutor-bounces+a.bull=pubdmgroup.com at python.org] On Behalf Of Chris ?Kwpolska? Warrick Sent: Friday, August 29, 2014 11:40 AM To: Richard Dillon Cc: tutor at python.org Subject: Re: [Tutor] Python 3.4.1 question for Mac users Sorry for the errorneous quote-only response, gmail managed to send it without me typing a thing. On Fri, Aug 29, 2014 at 5:01 PM, Richard Dillon wrote: > infile = open(r'\OS\Users\richarddillon\Desktop\my_file','r') On the Mac, you don?t need to specify a drive there; the main drive is just /. Also, the path separator is a forward slash (/). This also lets you remove the r in front of the string, which is needed for backslashes unless you escape them. The corrected code is: infile = open('/Users/richarddillon/Desktop/my_file', 'r') -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor [Al Bull] Isn't he still mixing a string and a string variable is his open statement? My_file is a string variable. I'm still learning Python myself so I could very well be incorrect.. :) From kwpolska at gmail.com Fri Aug 29 20:06:47 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Fri, 29 Aug 2014 20:06:47 +0200 Subject: [Tutor] Python 3.4.1 question for Mac users In-Reply-To: References: <6B42F399-C5B9-41E5-BC1F-2145E9770364@comcast.net> Message-ID: Please make sure to add tutor at python.org to the To: field so everyone gets to read your answer. Also, please don?t post in HTML. On Fri, Aug 29, 2014 at 7:39 PM, Richard Dillon wrote: > Still getting an error message. > > > It is trying to open a file named 'my_file' on your desktop, which does not exist. In this case, you want: infile = open('/Users/richarddillon/Desktop/' + my_file, 'r') This concatenates (puts together) the string with the path to your desktop and the variable my_file. Also, .rtf files are not going to work well with Python, you need a plain text file (.txt). -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Screen Shot 2014-08-29 at 10.37.02 AM.png Type: image/png Size: 184041 bytes Desc: not available URL: From derektjenkins at gmail.com Fri Aug 29 21:17:13 2014 From: derektjenkins at gmail.com (Derek Jenkins) Date: Fri, 29 Aug 2014 15:17:13 -0400 Subject: [Tutor] Printing a list count - Help Message-ID: Hi everybody, I have a list that I want to go through and finally print a total count of particular items. In this case, I want to print the result of how many A's and B's are in the list. honor_roll_count = 0 student_grades = ["A", "C", "B", "B", "C", "A", "F", "B", "B", "B", "C", "A"] for grades in student_grades: honor_roll_count = honor_roll_count + 1 if grades == "A" or grades == "B": print honor_roll_count The above code prints 8 lines, each being an entry for which item in the list was either A or B. Again, I'm looking for the result to be the number 8 itself - the total number of instances that A or B occurs in the list. I'm sure there are a handful of easy solutions for this, I just haven't hit the right combo yet and I thought I'd reach out to the tutor list for a bit of advice. Please and thank you! From dyoo at hashcollision.org Fri Aug 29 21:24:46 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 29 Aug 2014 12:24:46 -0700 Subject: [Tutor] sorting distances for nearest neighbor In-Reply-To: <1409273555.47158.YahooMailNeo@web161304.mail.bf1.yahoo.com> References: <1409273555.47158.YahooMailNeo@web161304.mail.bf1.yahoo.com> Message-ID: > How do you sort distances to prepare for nearest neighbor when the results > returned look like this from the below statements? It's unclear what you're asking. 1. Are you showing us the file content in the raw form: > Distance from 1 to > 16 is 43763.0757603 > 19 is 126516.988978 > 18 is 131011.694135 [text cut] and you're asking how to parse the content that you presented? 2. Or are you asking how to use the sort routines in Python? 3. Or are you asking how to write nearest neighbor? 4. Or are you asking for something else? I have no idea how to interpret what you mean by: DR=distance(n,XCOORDINATE, YCOORDINATE, IDCODE) DZ=switch(n,XCOORDINATE, YCOORDINATE, IDCODE) in your problem statement, given you don't say what DR, distance, switch, n, or IDCODE are. So I don't understand the terms being used in large portions of your problem statement. The question you're presenting has much more ambiguity than I'm comfortable with. Rather than try to cover all the bases, if you can scope the request to something more manageable, it'll probably make it easier to answer. Please clarify. Thanks! From dyoo at hashcollision.org Fri Aug 29 21:32:47 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 29 Aug 2014 12:32:47 -0700 Subject: [Tutor] extracting a cPickle/pickle file from inside a zip file In-Reply-To: References: Message-ID: > now if i do this > > outfile = cStringIO.StringIO() > outfile.write(pyfromzip) > z=cPickle.load(outfile) Do you have to rewind the outfile so that the read is properly positioned? The following interaction: ############################# >>> import StringIO >>> out = StringIO.StringIO() >>> out.write("hello world") >>> out.read() '' ############################# shows that if we immediately read what you write, we get nothing: the file position is not at the beginning. But as soon as we do a seek(): ############################## >>> out.seek(0) >>> out.read() 'hello world' ############################## then we're good. Alternatively, can you do this instead? ######################################### >>> out = StringIO.StringIO("hello, this is a test") >>> out.read() 'hello, this is a test' ######################################### In your case, construct the StringIO object with the content of pyfromzip, up front, rather than with a separate call to write(). From dyoo at hashcollision.org Fri Aug 29 21:37:55 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 29 Aug 2014 12:37:55 -0700 Subject: [Tutor] Printing a list count - Help In-Reply-To: References: Message-ID: > > The above code prints 8 lines, each being an entry for which item in > the list was either A or B. Again, I'm looking for the result to be > the number 8 itself - the total number of instances that A or B occurs > in the list. Hi Derek, Hint: the code currently prints a variable within the loop. But you can print the value of your variable _outside_ the loop, after all the student_grades have been processed. From derektjenkins at gmail.com Fri Aug 29 21:49:11 2014 From: derektjenkins at gmail.com (Derek Jenkins) Date: Fri, 29 Aug 2014 15:49:11 -0400 Subject: [Tutor] Printing a list count - Help In-Reply-To: References: Message-ID: honor_roll_count = 0 student_grades = ["A", "C", "B", "B", "C", "A", "F", "B", "B", "B", "C", "A"] for grades in student_grades: if grades == "A" or grades == "B": honor_roll_count = honor_roll_count + 1 print honor_roll_count That works more to my liking. Thanks a million, Danny and Bob! On Fri, Aug 29, 2014 at 3:42 PM, boB Stepp wrote: > On Fri, Aug 29, 2014 at 2:17 PM, Derek Jenkins wrote: >> Hi everybody, >> >> I have a list that I want to go through and finally print a total >> count of particular items. In this case, I want to print the result of >> how many A's and B's are in the list. >> >> honor_roll_count = 0 >> student_grades = ["A", "C", "B", "B", "C", "A", "F", "B", "B", "B", "C", "A"] >> >> for grades in student_grades: >> honor_roll_count = honor_roll_count + 1 >> if grades == "A" or grades == "B": >> print honor_roll_count >> > > Are you sure you have your increment of honor_roll_count where you > want it? As it is placed you are counting how many grades of any kind > there are. > > -- > boB From leamhall at gmail.com Fri Aug 29 21:52:31 2014 From: leamhall at gmail.com (leam hall) Date: Fri, 29 Aug 2014 15:52:31 -0400 Subject: [Tutor] Import from project's lib directory? In-Reply-To: References: <20140828223948.GA47105@cskk.homeip.net> Message-ID: Am I asking the wrong question? How do older apps with older versions of python (2.4.x) separate code into sub-directories? Do they? -- Mind on a Mission From derektjenkins at gmail.com Fri Aug 29 21:55:43 2014 From: derektjenkins at gmail.com (Derek Jenkins) Date: Fri, 29 Aug 2014 15:55:43 -0400 Subject: [Tutor] Printing a list count - Help In-Reply-To: <4d610e5aeab38586c94fe3dc0d02b1b5@sonic.net> References: <4d610e5aeab38586c94fe3dc0d02b1b5@sonic.net> Message-ID: Alex, Thanks for taking this one step further! I do appreciate it... +1 On Fri, Aug 29, 2014 at 3:48 PM, Alex Kleider wrote: > On 2014-08-29 12:17, Derek Jenkins wrote: >> >> Hi everybody, >> >> I have a list that I want to go through and finally print a total >> count of particular items. In this case, I want to print the result of >> how many A's and B's are in the list. >> >> honor_roll_count = 0 >> student_grades = ["A", "C", "B", "B", "C", "A", "F", "B", "B", "B", "C", >> "A"] >> >> for grades in student_grades: >> honor_roll_count = honor_roll_count + 1 >> if grades == "A" or grades == "B": >> print honor_roll_count >> >> The above code prints 8 lines, each being an entry for which item in >> the list was either A or B. Again, I'm looking for the result to be >> the number 8 itself - the total number of instances that A or B occurs >> in the list. > > > Try the following: > print("Running Python3 script: 'tutor.py'.......") > > > student_grades = ["A", "C", "B", "B", "C", "A", "F", > "B", "B", "B", "C", "A"] > > grades = {} > > for grade in student_grades: > grades[grade] = grades.get(grade, 0) + 1 > > for grade in sorted(grades.keys()): > print("'{}': {}".format(grade, grades[grade])) > > If you are using Python 2, I believe the get method is called something > else; you can look it up if need be. > > From alan.gauld at btinternet.com Fri Aug 29 22:24:34 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 29 Aug 2014 21:24:34 +0100 Subject: [Tutor] Printing a list count - Help In-Reply-To: References: Message-ID: On 29/08/14 20:17, Derek Jenkins wrote: > Hi everybody, > > I have a list that I want to go through and finally print a total > count of particular items. In this case, I want to print the result of > how many A's and B's are in the list. > > honor_roll_count = 0 > student_grades = ["A", "C", "B", "B", "C", "A", "F", "B", "B", "B", "C", "A"] > > for grades in student_grades: > honor_roll_count = honor_roll_count + 1 > if grades == "A" or grades == "B": > print honor_roll_count > lists have a count() method. try this: honor_roll_count = student_grades.count('A') + student_grades.count('B') For more complex data sets you could use the itertools groupby function too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From crushed26 at gmail.com Fri Aug 29 23:13:02 2014 From: crushed26 at gmail.com (Crush) Date: Fri, 29 Aug 2014 17:13:02 -0400 Subject: [Tutor] Interacting with stderr In-Reply-To: <20140828221228.GA84495@cskk.homeip.net> References: <20140828221228.GA84495@cskk.homeip.net> Message-ID: <5E4E82B2-676E-4CAD-B3C5-89721BC26E87@gmail.com> I am now able to print stderr to the screen, however I still can not run conditional statements against stderr. Please see the screenshots(SS) here... https://www.dropbox.com/sh/31wyjtvqymo94uk/AAAZaxwB27nw1nmz7tz69I5La?dl=0 Bo > On Aug 28, 2014, at 6:12 PM, Cameron Simpson wrote: > >> On 28Aug2014 09:42, Crush wrote: >> As far as the pipe in... >> >> "avconv -v verbose -re -analyzeduration 1000 -ihttp://localhost:6498/ms2/1382097438004/0MediaPlayer+0+/octoshape+hVV+octolive.americaone.com+V+aone+V+live+V+ONECONNXTDEMO1_HD_flv/aoneliveONECONNXTDEMO1HDflv -c:v rawvideo -c:a pcm_s16le -ar 48000 -f nut - | ./bmdplay -m 12 -f pipe:0" >> >> ...it has to be there. > > Indeed. We're not arguing about that. Leave it there for. > >> Currently, i am running a shell script that is handling this decoding process i.e. the real long avconv/bmdplay command. So you are saying leave the shell script and invoke it from a python script...something like "p = subprocess.Popen("./my_script.sh")? How will the above allow me to interact with stderr in oppose to running the avconv/bmdplay command directly in python? > > No, we're no saying that. > > You could (and presumably do) have this long incantation in your shell script. As far as the Python stuff goes, that does not change anything: you can invoke your shell script or invoke your long command directly. Either way you need to grab the stderr on the fly and work with it. > > Personally, I would keep the pipeline in the shell script where it is easier to edit and invoke the script from Python (easier to read). Your call. > >> As far as not using "shell=True," if I dont have it set to True, the terminal hangs and will not display stderr to the screen as it is currently does. > > Let's tackle shell=True later. > > What you need to do is examine stderr before the shell script/pipeline is complete, and for that you need to separate starting the process, reading stderr, and waiting for process completion into distinct parts, which was what my example code was doing. I'll recite it again here: > > from subprocess import Popen, PIPE > > P = Popen("avconv ... lots of arguments...", shell=True, stderr=PIPE) > > for line in P.stderr: > ... examine the line from stderr ... > > # ok, we have read all of stderr now > xit = P.wait() > if xit != 0: > ... command was unsuccessful, complain, maybe abort ... > > Please try adapting your Python code to that and see where you end up. > Put a print statement as the first line in the for-loop so you can see if you are receiving stderr lines as intended. > > Cheers, > Cameron Simpson > > As soon as we started programming, we found to our surprise that it wasn't as > easy to get programs right as we had thought. Debugging had to be discovered. > I can remember the exact instant when I realized that a large part of my life > from then on was going to be spent in finding mistakes in my own programs. > - Maurice Wilkes discovers debugging, 1949 -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Aug 29 23:16:12 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 29 Aug 2014 23:16:12 +0200 Subject: [Tutor] Import from project's lib directory? References: <20140828223948.GA47105@cskk.homeip.net> Message-ID: leam hall wrote: > Am I asking the wrong question? How do older apps with older versions > of python (2.4.x) separate code into sub-directories? Do they? Even new versions allow relative imports only inside packages. Given a tree $ tree . ??? alpha ? ??? beta ? ? ??? __init__.py ? ? ??? one.py ? ??? gamma ? ? ??? __init__.py ? ? ??? two.py ? ??? __init__.py ??? elsewhere ??? __init__.py ??? three.py You have to ensure that the *parent* of alpha is in sys.path. Then you can refer from alpha/beta/one.py to alpha/gamma/two.py with the statement # in file alpha/beta.one.py from ..gamma import two but as far as I know no combination of dots lets you refer to modules outside the package (like elswhere/three.py in the example). You need an absolute import for that. From dyoo at hashcollision.org Fri Aug 29 23:54:40 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 29 Aug 2014 14:54:40 -0700 Subject: [Tutor] extracting a cPickle/pickle file from inside a zip file In-Reply-To: References: Message-ID: Hi Dillup, One other comment other than the zipfile stuff: you might want to consider something other than pickle format if you want interchangeability with other tools. JSON, for example, is pretty well-supported in the json library: https://docs.python.org/2/library/json.html and it has an interface similar to that of pickle, so it's easy to switch to it. I recommend this instead of pickle, unless your situation favors pickle. JSON has a looser coupling to Python, and more importantly, fewer security concerns. Pickle can do some very dynamic stuff, including eval-like behavior, which can be a worry. See: http://stackoverflow.com/questions/10282175/attacking-pythons-pickle for example. If you're trying to represent dictionaries of string keys and values, that's something that JSON can handle very well. From dyoo at hashcollision.org Sat Aug 30 00:06:41 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 29 Aug 2014 15:06:41 -0700 Subject: [Tutor] Interacting with stderr In-Reply-To: <5E4E82B2-676E-4CAD-B3C5-89721BC26E87@gmail.com> References: <20140828221228.GA84495@cskk.homeip.net> <5E4E82B2-676E-4CAD-B3C5-89721BC26E87@gmail.com> Message-ID: On Fri, Aug 29, 2014 at 2:13 PM, Crush wrote: > I am now able to print stderr to the screen, however I still can not run > conditional statements against stderr. > > Please see the screenshots(SS) here... > > https://www.dropbox.com/sh/31wyjtvqymo94uk/AAAZaxwB27nw1nmz7tz69I5La?dl=0 Hi Bo, Consider case sensitivity. ################ >>> "a" == "A" False ################ Also, in the screenshots you're presenting, you very much should want to do a copy-and-paste of the text content and include it in your question text. The reason is because, for all the Tutor folks who aren't in a GUI right now, they can't see your program. For the sake of the others on the list: your first screenshot has the following: ########################## for line in p.stderr: print line if "segmentation" in line: print "Yes it is" ... ########################### and your second screenshot has the content: ############################## ... 11265 Segmentation fault | ./bmdplay -m 12 -f pipe:0 Gave up ############################## From dyoo at hashcollision.org Sat Aug 30 00:12:44 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 29 Aug 2014 15:12:44 -0700 Subject: [Tutor] Interacting with stderr In-Reply-To: References: <20140828221228.GA84495@cskk.homeip.net> <5E4E82B2-676E-4CAD-B3C5-89721BC26E87@gmail.com> Message-ID: Hi Bo, One other thing: if you can avoid running commands as root, I'd strongly suggest doing so. Your second screenshot shows that you're running as root superuser, and the imaginary security demon that sits on my left shoulder is laughing uproariously as we speak. From leamhall at gmail.com Sat Aug 30 00:12:43 2014 From: leamhall at gmail.com (leam hall) Date: Fri, 29 Aug 2014 18:12:43 -0400 Subject: [Tutor] Import from project's lib directory? In-Reply-To: References: <20140828223948.GA47105@cskk.homeip.net> Message-ID: On Fri, Aug 29, 2014 at 5:16 PM, Peter Otten <__peter__ at web.de> wrote: > leam hall wrote: > >> Am I asking the wrong question? How do older apps with older versions >> of python (2.4.x) separate code into sub-directories? Do they? > You have to ensure that the *parent* of alpha is in sys.path. Then you can > refer from alpha/beta/one.py to alpha/gamma/two.py with the statement Ah, so I can use sys.path.insert()! That's what I needed, thanks! Leam -- Mind on a Mission From crushed26 at gmail.com Sat Aug 30 00:31:40 2014 From: crushed26 at gmail.com (Crush) Date: Fri, 29 Aug 2014 18:31:40 -0400 Subject: [Tutor] Interacting with stderr In-Reply-To: References: <20140828221228.GA84495@cskk.homeip.net> <5E4E82B2-676E-4CAD-B3C5-89721BC26E87@gmail.com> Message-ID: <2D3A76AF-9BD5-416B-BC0E-2EB12FC2761E@gmail.com> Ok so no links to dropbox? Man im confused...i thought links to dropbox were ok? Wow i feel like such an idiot haha. I should have caught that capitolization error! Im sorry to have waisted your time. Bo > On Aug 29, 2014, at 6:06 PM, Danny Yoo wrote: > >> On Fri, Aug 29, 2014 at 2:13 PM, Crush wrote: >> I am now able to print stderr to the screen, however I still can not run >> conditional statements against stderr. >> >> Please see the screenshots(SS) here... >> >> https://www.dropbox.com/sh/31wyjtvqymo94uk/AAAZaxwB27nw1nmz7tz69I5La?dl=0 > > > Hi Bo, > > > Consider case sensitivity. > > ################ >>>> "a" == "A" > False > ################ > > > Also, in the screenshots you're presenting, you very much should want > to do a copy-and-paste of the text content and include it in your > question text. The reason is because, for all the Tutor folks who > aren't in a GUI right now, they can't see your program. > > > For the sake of the others on the list: your first screenshot has the following: > > > ########################## > for line in p.stderr: > print line > if "segmentation" in line: > print "Yes it is" > ... > ########################### > > > and your second screenshot has the content: > > > ############################## > ... > 11265 Segmentation fault | ./bmdplay -m 12 -f pipe:0 > > Gave up > ############################## From crushed26 at gmail.com Sat Aug 30 00:35:35 2014 From: crushed26 at gmail.com (Crush) Date: Fri, 29 Aug 2014 18:35:35 -0400 Subject: [Tutor] Interacting with stderr In-Reply-To: References: <20140828221228.GA84495@cskk.homeip.net> <5E4E82B2-676E-4CAD-B3C5-89721BC26E87@gmail.com> Message-ID: Haha Yes I am aware of people like you who are just itching to exploit vulnerabilities like that; however, the programs my company uses to broadcast will only run as root. Bo > On Aug 29, 2014, at 6:12 PM, Danny Yoo wrote: > > Hi Bo, > > One other thing: if you can avoid running commands as root, I'd > strongly suggest doing so. Your second screenshot shows that you're > running as root superuser, and the imaginary security demon that sits > on my left shoulder is laughing uproariously as we speak. From cs at zip.com.au Sat Aug 30 01:35:54 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 30 Aug 2014 09:35:54 +1000 Subject: [Tutor] Interacting with stderr In-Reply-To: <2D3A76AF-9BD5-416B-BC0E-2EB12FC2761E@gmail.com> References: <2D3A76AF-9BD5-416B-BC0E-2EB12FC2761E@gmail.com> Message-ID: <20140829233554.GA98283@cskk.homeip.net> On 29Aug2014 18:31, Crush wrote: >Ok so no links to dropbox? Man im confused...i thought links to dropbox were ok? That was my fault. I said: If your screenshot is inherently graphical, publish it elsewhere (eg save it to Dropbox and get a "public link") and mention the link in your post, with some textual description. But unless you're showing us some drawing, this is usually not desirable. In your case, the screenshot is (apparently) of some code, and it is far better to just include the code in your post, as text. There are many advantages to text, including: It is MUCH MUCH smaller. (Applies to screenshot attachments, too.) It keeps the text with the message. Further, because it is in the message, it keeps the text in the mail archives, where it may be searche fdor. Again, because it is in the message, it _stays_ in the archives. Your dropbox link might go away at any time in the future. Being text, part of the message, it is presented in _my_ preferred font. This is just nicer, and for some people with sight issues, very important. I once had a student who needed to get up very close to the screen, _and_ use a magnifying glass. Forcing him to fetch a screenshot would not be nice. It arrives in the message, not requiring a separate act to fetch it (versus a Dropbox link). For example, your message arrives and I have to open a web browser to go and get your screenshot. Suppose I'm offline. This is realistic: my laptop fetches my email in the background all the time, but I visit the "python" folder at ad hoc times. If I'm on a long train trip, that is an ideal time to catch up on mailing lists. I can read because the messages were fetched earlier. I can reply, because my laptop has a mail system which will queue messages and send when I'm online again. But I _can't_ go and get your URL, because I'm offline. Please use inline plain text when you can. It helps everyone. >Wow i feel like such an idiot haha. I should have caught that capitolization error! No worries. Cheers, Cameron Simpson The impossible we understand right away - the obvious takes a little longer. From cs at zip.com.au Sat Aug 30 01:37:19 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 30 Aug 2014 09:37:19 +1000 Subject: [Tutor] Interacting with stderr In-Reply-To: References: Message-ID: <20140829233719.GA47475@cskk.homeip.net> On 29Aug2014 18:35, Crush wrote: >> On Aug 29, 2014, at 6:12 PM, Danny Yoo wrote: >> One other thing: if you can avoid running commands as root, I'd >> strongly suggest doing so. Your second screenshot shows that you're >> running as root superuser, and the imaginary security demon that sits >> on my left shoulder is laughing uproariously as we speak. > >Haha Yes I am aware of people like you who are just itching to exploit vulnerabilities like that; however, the programs my company uses to broadcast will only run as root. That's a really bad design decision, and rarely necessary. It is often _easy_, but it leaves your systems at much greater risk. Cheers, Cameron Simpson Please do not send me Microsoft Word files. http://en.nothingisreal.com/wiki/Please_don't_send_me_Microsoft_Word_documents From dyoo at hashcollision.org Sat Aug 30 06:20:46 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 29 Aug 2014 21:20:46 -0700 Subject: [Tutor] Fwd: Re: extracting a cPickle/pickle file from inside a zip file In-Reply-To: References: Message-ID: ---------- Forwarded message ---------- From: "diliup gabadamudalige" Date: Aug 29, 2014 8:34 PM Subject: Re: [Tutor] extracting a cPickle/pickle file from inside a zip file To: "Danny Yoo" Cc: Dear Danny, Thank for your invaluable advice which is much appreciated. My code finally ends up being exe-fied with py2exe and I have a bit of a limitation there. I have to select packages which are compatible with it. Haven't tried json or checked whether it is compatible but I will do so. On another note which is a better exe-fier? py2exe or cxfreeze? I would like your personal opinion if you have any knowledge on this matter. Thank you once again for your invaluable help. Diliupg On Sat, Aug 30, 2014 at 3:24 AM, Danny Yoo wrote: > Hi Dillup, > > One other comment other than the zipfile stuff: you might want to > consider something other than pickle format if you want > interchangeability with other tools. JSON, for example, is pretty > well-supported in the json library: > > https://docs.python.org/2/library/json.html > > and it has an interface similar to that of pickle, so it's easy to switch > to it. > > I recommend this instead of pickle, unless your situation favors > pickle. JSON has a looser coupling to Python, and more importantly, > fewer security concerns. Pickle can do some very dynamic stuff, > including eval-like behavior, which can be a worry. See: > http://stackoverflow.com/questions/10282175/attacking-pythons-pickle > for example. > > If you're trying to represent dictionaries of string keys and values, > that's something that JSON can handle very well. > -- Diliup Gabadamudalige http://www.diliupg.com http://soft.diliupg.com/ ********************************************************************************************** This e-mail is confidential. It may also be legally privileged. If you are not the intended recipient or have received it in error, please delete it and all copies from your system and notify the sender immediately by return e-mail. Any unauthorized reading, reproducing, printing or further dissemination of this e-mail or its contents is strictly prohibited and may be unlawful. Internet communications cannot be guaranteed to be timely, secure, error or virus-free. The sender does not accept liability for any errors or omissions. ********************************************************************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From robertvstepp at gmail.com Fri Aug 29 21:42:29 2014 From: robertvstepp at gmail.com (boB Stepp) Date: Fri, 29 Aug 2014 14:42:29 -0500 Subject: [Tutor] Printing a list count - Help In-Reply-To: References: Message-ID: On Fri, Aug 29, 2014 at 2:17 PM, Derek Jenkins wrote: > Hi everybody, > > I have a list that I want to go through and finally print a total > count of particular items. In this case, I want to print the result of > how many A's and B's are in the list. > > honor_roll_count = 0 > student_grades = ["A", "C", "B", "B", "C", "A", "F", "B", "B", "B", "C", "A"] > > for grades in student_grades: > honor_roll_count = honor_roll_count + 1 > if grades == "A" or grades == "B": > print honor_roll_count > Are you sure you have your increment of honor_roll_count where you want it? As it is placed you are counting how many grades of any kind there are. -- boB From dillonrw at comcast.net Sat Aug 30 18:14:39 2014 From: dillonrw at comcast.net (Richard Dillon) Date: Sat, 30 Aug 2014 09:14:39 -0700 Subject: [Tutor] reading strings and calculating totals Message-ID: <2D31ED2A-2504-4991-A8E3-0EFF0F2C83EF@comcast.net> I apologize in advance - This is my third week using Python (3.4.1 on a Mac) I need to read a text file, convert the values into numbers and calculate a total. The total I get doesn't match the values entered in the file. def main(): total = 0 infile = open('/Users/richarddillon/Desktop/numbers.txt', 'r') # read first record line = infile.readline() a = float(line) # read rest of records while line != '': total = total + a line = infile.readline() infile.close() print(total) main() From juan0christian at gmail.com Sat Aug 30 15:19:24 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sat, 30 Aug 2014 10:19:24 -0300 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" Message-ID: Hello everyone, I have a question regarding PySide 1.2.2 and Python 3.4.1 I have this code that I made following a Python tutorial , mine is a bit different because the tutorial is a bit old, and I'm trying to use Python newest features . As I read in the doc, PySide Signal and Slots now work differently, and I'm trying to use this new way (lines 32 - 34). But, as you guys can see in the pastebin link, it's not working, but I don't have a clue why. I hope someone can explain me what I did wrong. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Aug 30 22:07:26 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 30 Aug 2014 22:07:26 +0200 Subject: [Tutor] reading strings and calculating totals References: <2D31ED2A-2504-4991-A8E3-0EFF0F2C83EF@comcast.net> Message-ID: Richard Dillon wrote: > I apologize in advance - This is my third week using Python (3.4.1 on a > Mac) > > I need to read a text file, convert the values into numbers and calculate > a total. The total I get doesn't match the values entered in the file. > > def main(): > total = 0 > infile = open('/Users/richarddillon/Desktop/numbers.txt', 'r') > # read first record > line = infile.readline() > a = float(line) > # read rest of records > while line != '': > total = total + a > line = infile.readline() > infile.close() > print(total) > > main() Hint: look at the while loop. You never set `a` to a new value, you just keep adding the value found in the first line. PS: Once you have fixed this try rewriting your code with a for loop ... for line in infile: ... This is the idiomatic way in Python and will also simplify your code. From alan.gauld at btinternet.com Sat Aug 30 22:13:03 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 30 Aug 2014 21:13:03 +0100 Subject: [Tutor] reading strings and calculating totals In-Reply-To: <2D31ED2A-2504-4991-A8E3-0EFF0F2C83EF@comcast.net> References: <2D31ED2A-2504-4991-A8E3-0EFF0F2C83EF@comcast.net> Message-ID: On 30/08/14 17:14, Richard Dillon wrote: > The total I get doesn't match the values entered in the file. > > def main(): > total = 0 > infile = open('/Users/richarddillon/Desktop/numbers.txt', 'r') > # read first record > line = infile.readline() > a = float(line) Here you get the number a > # read rest of records > while line != '': > total = total + a And here you add a (calculated above) to total. > line = infile.readline() And here you end the loop so you effectively add a to total for as many lines as are in the file. You effectively calculate a * (len of file-1) You need to convert line to float and add that to total inside the loop. BUT, there is a much better way using Pythons for loop: total = 0 for line in infile: total += float(line) That automatically reads all the lines ion the file so you don't need to check for empty lines, set up the first line etc. > infile.close() And if you use Pythons 'with' structure you don't need the close either, so your whole becomes total = 0 with open('/Users/richarddillon/Desktop/numbers.txt', 'r') as infile: for line in infile: total += float(line) print(total) Which is shorter, safer, and more readable. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sat Aug 30 22:17:39 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 30 Aug 2014 21:17:39 +0100 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: On 30/08/14 14:19, Juan Christian wrote: > Hello everyone, I have a question regarding PySide 1.2.2 and Python 3.4.1 The tutor list is for people learning Python language and the standard library so Side is really a bit off topic. There are some Qt users here though so you may get a reply, but the most likely bet is the Side or Qt forums. > bit different because the tutorial is a bit old, and I'm trying to use > Python newest features . > > As I read in the doc, PySide Signal and Slots now work differently, and > I'm trying to use this new way (lines 32 - 34). I assume that means that you've checked that Side works with 3.4? Its always risky using the latest version of a language with third party libraries since support is likely to be less robust than for ones that have been out for a while and had the bugs fixed. [That's why many professionals and corporates stick to using the current version -1 (or even -2!)...] -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From dillonrw at comcast.net Sat Aug 30 22:26:57 2014 From: dillonrw at comcast.net (Richard Dillon) Date: Sat, 30 Aug 2014 13:26:57 -0700 Subject: [Tutor] reading strings and calculating totals In-Reply-To: References: <2D31ED2A-2504-4991-A8E3-0EFF0F2C83EF@comcast.net> Message-ID: When I tried total = 0 with open('/Users/richarddillon/Desktop/numbers.txt', 'r') as infile: for line in infile: total += float(line) print(total) Python returned "ValueError: could not convert string to float: " Richard On Aug 30, 2014, at 1:13 PM, Alan Gauld wrote: > total = 0 > with open('/Users/richarddillon/Desktop/numbers.txt', 'r') as infile: > for line in infile: > total += float(line) > print(total) -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Sat Aug 30 22:27:32 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sat, 30 Aug 2014 17:27:32 -0300 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: Ops, I'm sorry, didn't know about that, anyway I already fixed the issue. I was doing 'self.fromComboBox.currentIndexChanged().connect(self.update_ui)' instead of 'self.fromComboBox.currentIndexChanged.connect(self.update_ui)' - no parenthesis. Now the problem is another one... And NOT related to PySide, it's pure Python. The problem is in the 'get_date()' func ( http://pastebin.com/mPhJcXmF) - I get all the text from bankofcanada site but when I reach 'line.strip()' I get an error, "'int' object has no attribute 'strip'". 2014-08-30 17:17 GMT-03:00 Alan Gauld : > On 30/08/14 14:19, Juan Christian wrote: > >> Hello everyone, I have a question regarding PySide 1.2.2 and Python 3.4.1 >> > > The tutor list is for people learning Python language and the standard > library so Side is really a bit off topic. There are some Qt users here > though so you may get a reply, but the most likely bet is the Side or Qt > forums. > > > bit different because the tutorial is a bit old, and I'm trying to use >> Python newest features . >> >> As I read in the doc, PySide Signal and Slots now work differently, and >> I'm trying to use this new way (lines 32 - 34). >> > > I assume that means that you've checked that Side works with 3.4? > > Its always risky using the latest version of a language with > third party libraries since support is likely to be less robust > than for ones that have been out for a while and had the bugs > fixed. [That's why many professionals and corporates stick to > using the current version -1 (or even -2!)...] > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Aug 30 23:17:14 2014 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 30 Aug 2014 22:17:14 +0100 Subject: [Tutor] reading strings and calculating totals In-Reply-To: References: <2D31ED2A-2504-4991-A8E3-0EFF0F2C83EF@comcast.net> Message-ID: <1409433434.18774.YahooMailNeo@web186004.mail.ir2.yahoo.com> total = 0 >with open('/Users/richarddillon/Desktop/numbers.txt', 'r') as infile: >? ?for line in infile: >? ? ? ?total += float(line) >print(total) > > >Python returned ? ? ? ? "ValueError: could not convert string to float: " > >That means some of your lines are not floats - are there any blanks? You can find out by inserting a print line: with open('/Users/richarddillon/Desktop/numbers.txt', 'r') as infile: ? ?for line in infile: ? ? ? ?print('Line = ', line) ? ? ? ?total += float(line) And see what the offending line looks like. Once you know what the error is caused by you can add a line? or two to avoid (or handle) the problematic cases. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Sun Aug 31 00:01:08 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 30 Aug 2014 15:01:08 -0700 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: > Now the problem is another one... And NOT related to PySide, it's pure > Python. The problem is in the 'get_date()' func > (http://pastebin.com/mPhJcXmF) - I get all the text from bankofcanada site > but when I reach 'line.strip()' I get an error, "'int' object has no > attribute 'strip'". You've got a type error. Let's analyze why. What are the types we're dealing with? Let's see. In line 4 of the program: fh = urllib.request.urlopen("http://www.bankofcanada.ca/en/markets/csv/exchange_eng.csv").read() urlopen() gives us a response object, according to: https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen What is the return type of read()? https://docs.python.org/3/library/http.client.html#http.client.HTTPResponse.read It sounds like it's returning a "bytes". But what is a "bytes"? https://docs.python.org/3/library/stdtypes.html#bytes Reading... ah, there's a section in the documentation on bytes that is relevant: """While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers""" Why is this fact relevant? Because the loop here is trying to iterate over the individual elements in fh: for line in fh: And from reading the documentation, those elements are the individual byte integer values. And so the "line" in line 6: for line in fh: is not truly representing a line of text: it's representing a single numeric byte in your input. So that's the origin of the error. Correct the code by using bytes.split(). https://docs.python.org/3/library/stdtypes.html#bytes.split So the loop really should be: for line in fh.split("\n"): ... From dyoo at hashcollision.org Sun Aug 31 00:03:23 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 30 Aug 2014 15:03:23 -0700 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: > So the loop really should be: > > for line in fh.split("\n"): > ... Ah, apologies. Forgot that we're in Python 3 land. We have to be consistent with the types a lot more. This should be: for line in fh.split(b"\n"): ... Apologies. I should have tested with a Python 3 interpreter in hand. From juan0christian at gmail.com Sun Aug 31 00:18:52 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sat, 30 Aug 2014 19:18:52 -0300 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: I analyzed the code and found two mistakes: 1. I wrote 'startsWith', and not 'startswith' 2. I forgot to encode, I needed to use '.read().decode("utf-8")' rather than '.read()' only. This way I get the text correctly (http://pastebin.com/qy4SVdzK). I'm still analyzing the code and fixing things, the program isn't 100% working yet. 2014-08-30 19:03 GMT-03:00 Danny Yoo : > > So the loop really should be: > > > > for line in fh.split("\n"): > > ... > > > Ah, apologies. Forgot that we're in Python 3 land. We have to be > consistent with the types a lot more. This should be: > > for line in fh.split(b"\n"): > ... > > Apologies. I should have tested with a Python 3 interpreter in hand. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From crushed26 at gmail.com Sun Aug 31 00:31:43 2014 From: crushed26 at gmail.com (Bo Morris) Date: Sat, 30 Aug 2014 18:31:43 -0400 Subject: [Tutor] interacting with stderr Message-ID: Here is my working code. It works great in the lab, but I still need to test it on a live system. I also need to add the email notifications to it, but I purposely left them out for now; I will also adjust the sleep time to a more appropriate amount. Anyone see any issues with it or ways to make it better? #!/usr/bin/env python import subprocess from subprocess import PIPE import time import psutil import sys count = 0 restart = 0 def kill_proc(process1, process2): i = psutil.Popen(["ps", "cax"], stdout=PIPE) out, err = i.communicate() for proc in psutil.process_iter(): if proc.name == process1 and process2: proc.kill() while True: while count < 15: count += 1 kill_proc("bmdplay", "avconv") print "Starting the script", count time.sleep(2) p = subprocess.Popen("/Downloads/bmdtools/test_loop.sh", shell=True, stderr=PIPE) for line in p.stderr: print line if "Segmentation" in line: kill_proc("bmdplay", "avconv") while restart < 3: restart += 1 time.sleep(2) p = subprocess.Popen("/Downloads/bmdtools/test_loop.sh", shell=True, stderr=PIPE) for line in p.stderr: print line if restart == 3: # send email saying so sys.exit() if "storing 0x" in line: kill_proc("bmdplay", "avconv") while restart < 3: restart += 1 sleep.time(2) p = subprocess.Popen("/Downloads/bmdtools/test_loop.sh", shell=True, stderr=PIPE) for line in p.stderr: print line if restart == 3: # send email saying so sys.exit() if count == 10: print "Going to sleep, will try again in..." #send email saying so time.sleep(2) if count == 15: # send email saying so print "Gave up" break break -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Aug 31 00:53:53 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 30 Aug 2014 23:53:53 +0100 Subject: [Tutor] interacting with stderr In-Reply-To: References: Message-ID: On 30/08/14 23:31, Bo Morris wrote: > time to a more appropriate amount. Anyone see any issues with it or ways > to make it better? One obvious issue: > while True: > while count < 15: > for line in p.stderr: > if "Segmentation" in line: > while restart < 3: > for line in p.stderr: > if "storing 0x" in line: > while restart < 3: > for line in p.stderr: > print line > if count == 15: > break > break First, there are a lot of embedded loops in there, that's usually a design warning that maybe you need to look at things again. In particular I'm suspicious of those two "for line in p.stderr" loops inside a loop that is itself a "for line in p.stderr" loop. That feels wrong. I haven't worked through the detail so it might be valid but it smells bad to me. Looking closer, you are reassigning p in the middle of a loop that depends on p. That's usually not a good idea... Second, the last break does nothing except terminate the outer loop after the first time through. So you might as well miss out the initial "while True" line... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From juan0christian at gmail.com Sun Aug 31 00:32:26 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sat, 30 Aug 2014 19:32:26 -0300 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: Sorry for double-post. I did as you said, now I get this: [image: Imagem inline 1] I did a 'print(line)' and it seems to be working, " b'# The daily noon exchange rates for major foreign currencies are published every business day at about 12:30' ". Code: http://pastebin.com/SgVdeKGm 2014-08-30 19:18 GMT-03:00 Juan Christian : > I analyzed the code and found two mistakes: > > 1. I wrote 'startsWith', and not 'startswith' > 2. I forgot to encode, I needed to use '.read().decode("utf-8")' rather > than '.read()' only. > > This way I get the text correctly (http://pastebin.com/qy4SVdzK). I'm > still analyzing the code and fixing things, the program isn't 100% working > yet. > > > > > > > 2014-08-30 19:03 GMT-03:00 Danny Yoo : > > > So the loop really should be: >> > >> > for line in fh.split("\n"): >> > ... >> >> >> Ah, apologies. Forgot that we're in Python 3 land. We have to be >> consistent with the types a lot more. This should be: >> >> for line in fh.split(b"\n"): >> ... >> >> Apologies. I should have tested with a Python 3 interpreter in hand. >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image.png Type: image/png Size: 6789 bytes Desc: not available URL: From dyoo at hashcollision.org Sun Aug 31 02:09:24 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 30 Aug 2014 17:09:24 -0700 Subject: [Tutor] Interacting with stderr In-Reply-To: <20140829233719.GA47475@cskk.homeip.net> References: <20140829233719.GA47475@cskk.homeip.net> Message-ID: >>> One other thing: if you can avoid running commands as root, I'd >>> strongly suggest doing so. Your second screenshot shows that you're >>> running as root superuser, and the imaginary security demon that sits >>> on my left shoulder is laughing uproariously as we speak. >> >> Haha Yes I am aware of people like you who are just itching to exploit >> vulnerabilities like that; however, the programs my company uses to >> broadcast will only run as root. > > > That's a really bad design decision, and rarely necessary. It is often > _easy_, but it leaves your systems at much greater risk. I agree with Cameron. On a scale from 1 to 10, where 10 is "oh my god this is bad", what you're doing by running such a program as root is about an 8 or 9. But, then, I've always been an optimist. The fact that you're doing this in the context of a company, where things actually _matter_, turns the situation from what I thought was merely "dubious" into one that's closer to "criminal". Please, please get an education from your local friendly Unix system administrator about running as root superuser. From dyoo at hashcollision.org Sun Aug 31 02:33:52 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 30 Aug 2014 17:33:52 -0700 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: Hi Juan, Take out your try/except block. It's "lying" in the sense that what's problematic isn't the failure to download. The exception handling is not doing well: it's hiding the true cause of the problem. After you take the exception handler out, try again. The error message should be a lot more localized and tell you exactly what line number is raising the runtime error. Ideally, you should read the file-like object progressively, rather than suck the whole thing at once. Something like the following: ############################### import codecs import urllib.request urlString = "http://www.bankofcanada.ca/en/markets/csv/exchange_eng.csv" rawFile = urllib.request.urlopen(urlString) decodedFile = codecs.getreader("utf-8")(rawFile) for line in decodedFile: print(repr(line)) ############################### shows that you can do the decoding on-the-fly. From dyoo at hashcollision.org Sun Aug 31 02:43:55 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 30 Aug 2014 17:43:55 -0700 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: Hi Juan, Wait, you are working with a CSV file, right? You should not be trying to parse this by hand if you can avoid it: there's a 'csv' parser library in the Standard Library. https://docs.python.org/3.1/library/csv.html So: #################################### import codecs import urllib.request import csv urlString = "http://www.bankofcanada.ca/en/markets/csv/exchange_eng.csv" rawFile = urllib.request.urlopen(urlString) decodedFile = codecs.getreader("utf-8")(rawFile) rows = csv.reader(decodedFile) for row in rows: print(repr(row)) ####################################### should take better advantage of what the Standard Library provides you: then you just deal with the records. You might have to do a little to filter out the beginning comment lines, but that shouldn't be too bad. From dyoo at hashcollision.org Sun Aug 31 03:37:19 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 30 Aug 2014 18:37:19 -0700 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: As the error message suggests, the problem might be near line 40. Look at lines 40 and 41 in your program. print(rates[row[0]] + " / VALUE : " + str(value)) rates[row[0]] = value Look at it very carefully, and try to explain to yourself what those two lines mean. What do you _want_ to happen when those two statements execute? What does "row[0]" mean? What does "rates[row[0]]" mean? Do you notice something strange? From crushed26 at gmail.com Sun Aug 31 04:18:11 2014 From: crushed26 at gmail.com (Crush) Date: Sat, 30 Aug 2014 22:18:11 -0400 Subject: [Tutor] Interacting with stderr In-Reply-To: References: <20140829233719.GA47475@cskk.homeip.net> Message-ID: <4AD20ED4-E864-4851-BF7C-A68D0ADF465C@gmail.com> Ok, i understand the dangers of using root. I will bring this to the attention of the CTO of the company, which he should know already, but none the less. You must know though, I do not have the power to change the way things are done. If he says "ahhh, dont worry about it," then what am I to do? Personally, I use Ubuntu, which I really like, and I dont have to worry about the "su/root" issue....the companies encoders and decoders, now thats a whole other issue. Now, enough scolding me :) Bo On Aug 30, 2014, at 8:09 PM, Danny Yoo wrote: >>>> One other thing: if you can avoid running commands as root, I'd >>>> strongly suggest doing so. Your second screenshot shows that you're >>>> running as root superuser, and the imaginary security demon that sits >>>> on my left shoulder is laughing uproariously as we speak. >>> >>> Haha Yes I am aware of people like you who are just itching to exploit >>> vulnerabilities like that; however, the programs my company uses to >>> broadcast will only run as root. >> >> >> That's a really bad design decision, and rarely necessary. It is often >> _easy_, but it leaves your systems at much greater risk. > > > I agree with Cameron. On a scale from 1 to 10, where 10 is "oh my god > this is bad", what you're doing by running such a program as root is > about an 8 or 9. But, then, I've always been an optimist. > > The fact that you're doing this in the context of a company, where > things actually _matter_, turns the situation from what I thought was > merely "dubious" into one that's closer to "criminal". Please, please > get an education from your local friendly Unix system administrator > about running as root superuser. From crushed26 at gmail.com Sun Aug 31 04:32:07 2014 From: crushed26 at gmail.com (Crush) Date: Sat, 30 Aug 2014 22:32:07 -0400 Subject: [Tutor] Tutor Digest, Vol 126, Issue 86 In-Reply-To: References: Message-ID: Thank you Allan for your criticism. Please see the below changes. As far as the embedded loops, I know no other way to achieve the same out come. def kill_proc(process1, process2): i = psutil.Popen(["ps", "cax"], stdout=PIPE) out, err = i.communicate() for proc in psutil.process_iter(): if proc.name == process1 and process2: proc.kill() while True: while count < 15: count += 1 kill_proc("bmdplay", "avconv") print "Starting the script", count time.sleep(2) p = subprocess.Popen("/Downloads/bmdtools/test_loop.sh", shell=True, stderr=PIPE) for line in p.stderr: print line if "Segmentation" in line: kill_proc("bmdplay", "avconv") while restart < 3: restart += 1 time.sleep(2) q = subprocess.Popen("/Downloads/bmdtools/test_loop.sh", shell=True, stderr=PIPE) for line in q.stderr: print line if restart == 3: # send email saying so sys.exit() if "storing 0x" in line: kill_proc("bmdplay", "avconv") while restart < 3: restart += 1 sleep.time(2) r = subprocess.Popen("/Downloads/bmdtools/test_loop.sh", shell=True, stderr=PIPE) for line in r.stderr: print line if restart == 3: # send email saying so sys.exit() if count == 10: print "Going to sleep, will try again in..." #send email saying so time.sleep(2) if count == 15: # send email saying so print "Gave up" break From dyoo at hashcollision.org Sun Aug 31 04:58:45 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 30 Aug 2014 19:58:45 -0700 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: On Sat, Aug 30, 2014 at 7:49 PM, Juan Christian wrote: > Let's see, the print is just "debug", it's not necessary in the program. > > 'row[0]' is the first element of the current row. Ex.: row = ['a', 'b', 'c', > 'd'] - row[0] would be 'a' > > 'rates' is a dictionary, 'rates[row[0]]' would update the key row[0] in the > dict with the 'value' > > I think that's it, right? Close enough. Let's look again now. print(rates[row[0]] + " / VALUE : " + str(value)) rates[row[0]] = value The print statement here is trying to print the value for a record that hasn't been entered in yet. So one way to naively fix this is to just switch the statements around: rates[row[0]] = value print(rates[row[0]] + " / VALUE : " + str(value)) But that probably doesn't mean what you want. Otherwise, you'd be printing the value _twice_ in your debugging output. Try it out and you'll see what I mean. You probably meant to write: print(row[0] + " / VALUE : " + str(value)) rates[row[0]] = value This is why human understanding is necessary here: it's all too easy to make a program run, but not make much sense. Here, there are at least two ways to "fix" the erroneous situation, but only you can tell us the right thing to do is. That's why I asked very emphatically: what do you mean? :P (And frankly, you probably don't want the print statement there in the first place: it's debugging output. Right?) From dyoo at hashcollision.org Sun Aug 31 05:27:19 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 30 Aug 2014 20:27:19 -0700 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: > > Everything seems to be working, but, when I try to really use the program > and convert something change the spinBox value I get: > > > ### > Traceback (most recent call last): > File "C:/.../currency.py", line 20, in update_ui > amount = (rates[from_] / rates[to]) * fromSpinBox.value() > TypeError: list indices must be integers, not str > ### > > What I have here is a DICT, not a LIST, why Python is reading it as a list? > I do need to pass a str (the currency names) to get the values from the > dict. I'm reading the doc trying to figure this out. What statements affect the value of rates? Do a text search if you have to. Search for anything that looks like "rates = "... Believe the error message unless something very unusual is happening. Usually, Python is telling you the truth. You _know_ you were dealing with a dictionary earlier. And yet, you also know, from the error message, that something has changed "rates" from a dictionary to a list. What statements in the program could have provoked this? I see at least one in your program that probably will do it. I have no idea what that particular statement is trying to do. From cs at zip.com.au Sun Aug 31 07:22:14 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 31 Aug 2014 15:22:14 +1000 Subject: [Tutor] Interacting with stderr In-Reply-To: References: Message-ID: <20140831052214.GA81693@cskk.homeip.net> On 30Aug2014 22:32, Crush wrote: >Thank you Allan for your criticism. Please see the below changes. As far as the embedded loops, I know no other way to achieve the same out come. Regrettably I've lost Alan's email on that (I had it:-). It looks like you've taken he concern over nested use of p.stderr too literally. It loops like you avoid using the same stderr by restarting "test_loop.sh" in the inner loops and reparsing their error outputs. I'm fairly sure that is not what Alan intended and also not what you want to be doing. Please explain your thinking here. Regarding nested loops on the same iterable: It is ok to nested use of an iterator, with some caution. The typical use case is some sort of nesting parse of the output. For example, if you were looking for the word "Segmentation", and then intending to act specially on all following lines until some marker. Another gleaming example that springs to mind would be gathering up python stack traces (multiline outputs) in some error log. You'd fairly naturally end up with code a bit like this: for line in p.stderr: if "Segemntation" in line: # ok, found the start line for inner_line in p.stderr: if "end segemntation marker" in inner_line: break ... do something with inner_line That essentially has the effect that all the lines from "Segmentation" to "end segemntation marker" are processed specially by the inner loop, and after you see the end marker you return to the outer loop, looking for the next occurence of "Segmentation". There is really only one pitfall with this, and that is the possibility that the end marker line is itself important. Imagine you had two inner loops, one for the "Segmentation" section and another to handle some other section, like this: for line in p.stderr: if "Segemntation" in line: # ok, found the start line ... do the "Segmentation" section ... elif "other-section" in line: # ok, found the start line ... do the "other-section" section ... else: # boring line, report it or discard it etc Simple and straight forward, yes? It will nicely handly input like this: blah blah begin Segmentation >> stuff >> more stuff end segmentation marker blah blah begin other-section >> other stuff >> even more other stuff end the other section blah However, consider the case where the end marker for the "Segmentation" section is not some special line generated by the "Segmentation" event, but simply some line that is not a match. Like the beginning of an "other-section" section. Eg: blah blah begin Segmentation >> stuff >> more stuff begin other-section >> other stuff >> even more other stuff blah With input like that, the "end of section" line is itself an important line that needs to be considered. But the loop as written "consumes" the marker line, and it is not available for recognition on the next outer loop pass (because that fetches the next line). This is where nested loops on the same iterable can have an issue. There are several things you can do about it depending on your code and your preferences. >def kill_proc(process1, process2): > i = psutil.Popen(["ps", "cax"], stdout=PIPE) > out, err = i.communicate() > for proc in psutil.process_iter(): > if proc.name == process1 and process2: > proc.kill() This function won't work as you intend. Specificly, the "if" test is wrong. You want to change: if proc.name == process1 and process2: into: if proc.name == process1 and or proc.name == process2: or perhaps: if proc.name in (process1, process2): and your psutil.Popen call looks... confused. Popen is a subprocess function, not part of psutil (I think). And you don't use either "out" or "err" after you collect them, so why use .communicate? Also, this will kill _every_ instance of mbplay and avconv, not just the ones you started. You would be better off just killing your own. The rest of your code's function is not clear to me. Does it work? Cheers, Cameron Simpson From juan0christian at gmail.com Sun Aug 31 03:26:25 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sat, 30 Aug 2014 22:26:25 -0300 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: I'm changing so much the code that I got lost now. Code so far: http://pastebin.com/u4xwZuyJ I'm getting this error. 'value = float(row[-1])' is getting the values OK, but when I do 'rates[row[0]] = value' it screws things up. =========================== Traceback (most recent call last): File "C:.../currency.py", line 48, in date = get_rates() File "C:.../currency.py", line 40, in get_rates print(rates[row[0]] + " / VALUE : " + str(value)) KeyError: 'U.S. dollar ' Process finished with exit code 1 =========================== 2014-08-30 21:43 GMT-03:00 Danny Yoo : > Hi Juan, > > Wait, you are working with a CSV file, right? You should not be > trying to parse this by hand if you can avoid it: there's a 'csv' > parser library in the Standard Library. > > https://docs.python.org/3.1/library/csv.html > > So: > > #################################### > import codecs > import urllib.request > import csv > > urlString = "http://www.bankofcanada.ca/en/markets/csv/exchange_eng.csv" > rawFile = urllib.request.urlopen(urlString) > decodedFile = codecs.getreader("utf-8")(rawFile) > rows = csv.reader(decodedFile) > > for row in rows: > print(repr(row)) > ####################################### > > > should take better advantage of what the Standard Library provides > you: then you just deal with the records. You might have to do a > little to filter out the beginning comment lines, but that shouldn't > be too bad. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Sun Aug 31 04:49:22 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sat, 30 Aug 2014 23:49:22 -0300 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: Let's see, the print is just "debug", it's not necessary in the program. 'row[0]' is the first element of the current row. Ex.: row = ['a', 'b', 'c', 'd'] - row[0] would be 'a' 'rates' is a dictionary, 'rates[row[0]]' would update the key row[0] in the dict with the 'value' I think that's it, right? 2014-08-30 22:37 GMT-03:00 Danny Yoo : > As the error message suggests, the problem might be near line 40. > > > Look at lines 40 and 41 in your program. > > print(rates[row[0]] + " / VALUE : " + str(value)) > rates[row[0]] = value > > Look at it very carefully, and try to explain to yourself what those > two lines mean. > > What do you _want_ to happen when those two statements execute? > > What does "row[0]" mean? > > What does "rates[row[0]]" mean? > > Do you notice something strange? > -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Sun Aug 31 05:10:08 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 31 Aug 2014 00:10:08 -0300 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: Yes, the print, as I said, is DEBUG only. The way you said works: http://pastebin.com/bqCjNZGH Code: http://pastebin.com/9u2WCVat Everything seems to be working, but, when I try to really use the program and convert something change the spinBox value I get: ### Traceback (most recent call last): File "C:/.../currency.py", line 20, in update_ui amount = (rates[from_] / rates[to]) * fromSpinBox.value() TypeError: list indices must be integers, not str ### What I have here is a DICT, not a LIST, why Python is reading it as a list? I do need to pass a str (the currency names) to get the values from the dict. I'm reading the doc trying to figure this out. 2014-08-30 23:58 GMT-03:00 Danny Yoo : > On Sat, Aug 30, 2014 at 7:49 PM, Juan Christian > wrote: > > Let's see, the print is just "debug", it's not necessary in the program. > > > > 'row[0]' is the first element of the current row. Ex.: row = ['a', 'b', > 'c', > > 'd'] - row[0] would be 'a' > > > > 'rates' is a dictionary, 'rates[row[0]]' would update the key row[0] in > the > > dict with the 'value' > > > > I think that's it, right? > > > Close enough. Let's look again now. > > print(rates[row[0]] + " / VALUE : " + str(value)) > rates[row[0]] = value > > The print statement here is trying to print the value for a record > that hasn't been entered in yet. So one way to naively fix this is to > just switch the statements around: > > rates[row[0]] = value > print(rates[row[0]] + " / VALUE : " + str(value)) > > But that probably doesn't mean what you want. Otherwise, you'd be > printing the value _twice_ in your debugging output. Try it out and > you'll see what I mean. > > You probably meant to write: > > print(row[0] + " / VALUE : " + str(value)) > rates[row[0]] = value > > This is why human understanding is necessary here: it's all too easy > to make a program run, but not make much sense. Here, there are at > least two ways to "fix" the erroneous situation, but only you can tell > us the right thing to do is. > > That's why I asked very emphatically: what do you mean? :P > > > (And frankly, you probably don't want the print statement there in the > first place: it's debugging output. Right?) > -------------- next part -------------- An HTML attachment was scrubbed... URL: From juan0christian at gmail.com Sun Aug 31 15:02:13 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 31 Aug 2014 10:02:13 -0300 Subject: [Tutor] PySide 1.2.2 and Python 3 - "native Qt signal is not callable" In-Reply-To: References: Message-ID: Thank you my friend! It was line 48. The 'sorted()' method transformed my dict in a list. I do need this approach to put the keys in a sorted way, but know I do it directly, like 'fromComboBox.addItems(sorted(rates.keys()))' and 'toComboBox.addItems(sorted(rates.keys()))', so that I don't overwrite my dict. Final code working: http://pastebin.com/9vK1YBfA 3 USD to BRL from Google: 6.71 3 USD to BRL from my App: 6.71 3.50 Euro to YEN from Google: 478.50 3.50 Euro to YEN from my App: 478.67 Close enough, since it's a learning software, I don't need precise conversions, and it's not my fault, it's Bank Of Canada fault =p their CSV is a bit outdated. Thanks for the patience and not posting "take this code, it works", your way is much more helpful. 2014-08-31 0:27 GMT-03:00 Danny Yoo : > > > > Everything seems to be working, but, when I try to really use the program > > and convert something change the spinBox value I get: > > > > > > ### > > Traceback (most recent call last): > > File "C:/.../currency.py", line 20, in update_ui > > amount = (rates[from_] / rates[to]) * fromSpinBox.value() > > TypeError: list indices must be integers, not str > > ### > > > > What I have here is a DICT, not a LIST, why Python is reading it as a > list? > > I do need to pass a str (the currency names) to get the values from the > > dict. I'm reading the doc trying to figure this out. > > > > What statements affect the value of rates? Do a text search if you > have to. Search for anything that looks like "rates = "... > > Believe the error message unless something very unusual is happening. > Usually, Python is telling you the truth. You _know_ you were > dealing with a dictionary earlier. And yet, you also know, from the > error message, that something has changed "rates" from a dictionary to > a list. > > What statements in the program could have provoked this? I see at > least one in your program that probably will do it. I have no idea > what that particular statement is trying to do. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From crushed26 at gmail.com Sun Aug 31 15:25:34 2014 From: crushed26 at gmail.com (Crush) Date: Sun, 31 Aug 2014 09:25:34 -0400 Subject: [Tutor] Interacting with stderr In-Reply-To: <20140831052214.GA81693@cskk.homeip.net> References: <20140831052214.GA81693@cskk.homeip.net> Message-ID: <3E26334E-37FA-4B7E-8CF9-6D28F9EFF64A@gmail.com> Alan said, "... you are reassigning p in the middle of a loop that depends on p. That's usually not a good idea..." If not what I changed my code to, then I reckon I do not understand what he is suggesting I do. I have to reparse stderr, each time test_loop.sh is executed the content of stderr is different i.e. frames, bitrate, time running, etc. Picture, stderr out is being printed to the screen as a running log while the machine is decoding. The frames, time, etc. are counting up. If it has been decoding for 3 days, the the frames, time, etc. will reflect this. As far as killing off every avconv and bmdplay process, that is exactly what I need to do if they exist before I execute test_loop. I need a "clean slate" so-to-speak before each execution. Again, my code works so far in the lab, but I havent tested it with a live broadcast yet. I figured it would not work the same while testing live and I was anticipating changes would need to be made like what you suggested... "This function won't work as you intend. Specificly, the "if" test is wrong. You want to change: if proc.name == process1 and process2: if proc.name in (process1, process2):" Psutil.Popen works just fine. And I will remove "out, err = p.communicate()" as you are are correct, it is not being used. Yes the rest of my code does in fact work fine. Would you be willing to Teamviewer into my machine, so you can see a healthy decoding? This would give you a better understanding of what I am trying to accomplish. Thank you, Bo >> On Aug 31, 2014, at 1:22 AM, Cameron Simpson wrote: >> >> On 30Aug2014 22:32, Crush wrote: >> Thank you Allan for your criticism. Please see the below changes. As far as the embedded loops, I know no other way to achieve the same out come. > > Regrettably I've lost Alan's email on that (I had it:-). > > It looks like you've taken he concern over nested use of p.stderr too literally. It loops like you avoid using the same stderr by restarting "test_loop.sh" in the inner loops and reparsing their error outputs. I'm fairly sure that is not what Alan intended and also not what you want to be doing. Please explain your thinking here. > > Regarding nested loops on the same iterable: > > It is ok to nested use of an iterator, with some caution. The typical use case is some sort of nesting parse of the output. For example, if you were looking for the word "Segmentation", and then intending to act specially on all following lines until some marker. Another gleaming example that springs to mind would be gathering up python stack traces (multiline outputs) in some error log. > > You'd fairly naturally end up with code a bit like this: > > for line in p.stderr: > if "Segemntation" in line: > # ok, found the start line > for inner_line in p.stderr: > if "end segemntation marker" in inner_line: > break > ... do something with inner_line > > That essentially has the effect that all the lines from "Segmentation" to "end segemntation marker" are processed specially by the inner loop, and after you see the end marker you return to the outer loop, looking for the next occurence of "Segmentation". > > There is really only one pitfall with this, and that is the possibility that the end marker line is itself important. > > Imagine you had two inner loops, one for the "Segmentation" section and another to handle some other section, like this: > > for line in p.stderr: > if "Segemntation" in line: > # ok, found the start line > ... do the "Segmentation" section ... > elif "other-section" in line: > # ok, found the start line > ... do the "other-section" section ... > else: > # boring line, report it or discard it etc > > Simple and straight forward, yes? It will nicely handly input like this: > > blah > blah > begin Segmentation >>> stuff >>> more stuff > end segmentation marker > blah > blah > begin other-section >>> other stuff >>> even more other stuff > end the other section > blah > > However, consider the case where the end marker for the "Segmentation" section is not some special line generated by the "Segmentation" event, but simply some line that is not a match. Like the beginning of an "other-section" section. Eg: > > blah > blah > begin Segmentation >>> stuff >>> more stuff > begin other-section >>> other stuff >>> even more other stuff > blah > > With input like that, the "end of section" line is itself an important line that needs to be considered. But the loop as written "consumes" the marker line, and it is not available for recognition on the next outer loop pass (because that fetches the next line). > > This is where nested loops on the same iterable can have an issue. There are several things you can do about it depending on your code and your preferences. >> def kill_proc(process1, process2): >> i = psutil.Popen(["ps", "cax"], stdout=PIPE) >> out, err = i.communicate() >> for proc in psutil.process_iter(): >> if proc.name == process1 and process2: >> proc.kill() > > This function won't work as you intend. Specificly, the "if" test is wrong. You want to change: > > if proc.name == process1 and process2: > > into: > > if proc.name == process1 and or proc.name == process2: > > or perhaps: > > if proc.name in (process1, process2): > > and your psutil.Popen call looks... confused. Popen is a subprocess function, not part of psutil (I think). And you don't use either "out" or "err" after you collect them, so why use .communicate? > > Also, this will kill _every_ instance of mbplay and avconv, not just the ones you started. You would be better off just killing your own. > > The rest of your code's function is not clear to me. Does it work? > > Cheers, > Cameron Simpson From alan.gauld at btinternet.com Sun Aug 31 17:15:28 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 31 Aug 2014 16:15:28 +0100 Subject: [Tutor] Interacting with stderr In-Reply-To: <3E26334E-37FA-4B7E-8CF9-6D28F9EFF64A@gmail.com> References: <20140831052214.GA81693@cskk.homeip.net> <3E26334E-37FA-4B7E-8CF9-6D28F9EFF64A@gmail.com> Message-ID: On 31/08/14 14:25, Crush wrote: > Alan said, > > "... you are reassigning p in the middle of a loop that > depends on p. That's usually not a good idea..." > > If not what I changed my code to, then I reckon I do not > understand what he is suggesting I do. Your original code looked like this: p = subprocess() for line in p.stderr: if some condition: p = subprocess() # now reassigned p to a new subprocess for line in p.stderr: do stuff So the question is: What happens to the outer loop when you finish 'do stuff'? It may be that it is doing what you want, or it may be that you want to break the outer loop when your some condition succeeds. I'm not sure? If you do want to exit the outer loop a more explicit way would be to set a flag and break: p = subprocess() for line in p.stderr: if some condition: some_flag = True break elif other condition: other_flag = True break if some_flag: p = subprocess() for line in p.stderr: do stuff elif other_flag: do other stuff But I haven't read through the code in enough detail to be sure what you are doing, it was just a general observation that resetting the the thing that your loop depends on is usually a bad idea. A bit like cutting off the branch of the tree that you are standing on... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From akleider at sonic.net Sun Aug 31 20:32:19 2014 From: akleider at sonic.net (Alex Kleider) Date: Sun, 31 Aug 2014 11:32:19 -0700 Subject: [Tutor] reading strings and calculating totals In-Reply-To: References: <2D31ED2A-2504-4991-A8E3-0EFF0F2C83EF@comcast.net> Message-ID: <14e23969d604dd8362853b4752d831bb@sonic.net> On 2014-08-30 13:13, Alan Gauld wrote: > BUT, there is a much better way using Pythons for loop: > > total = 0 > for line in infile: > total += float(line) > > That automatically reads all the lines ion the file so > you don't need to check for empty lines, set up the > first line etc. > >> infile.close() > > And if you use Pythons 'with' structure you don't > need the close either, so your whole becomes > > total = 0 > with open('/Users/richarddillon/Desktop/numbers.txt', 'r') as infile: > for line in infile: > total += float(line) > print(total) > > Which is shorter, safer, and more readable. > > HTH ..but isn't there a problem if the file contains empty lines? >>> float("\n") Traceback (most recent call last): File "", line 1, in ValueError: could not convert string to float: >>> float('') Traceback (most recent call last): File "", line 1, in ValueError: could not convert string to float: >>> From dillonrw at comcast.net Sun Aug 31 18:31:25 2014 From: dillonrw at comcast.net (Richard Dillon) Date: Sun, 31 Aug 2014 09:31:25 -0700 Subject: [Tutor] This is driving my crazy! My file hasn't been corrupted Message-ID: <58634834-2327-48FD-BFD1-D4F63F5835FC@comcast.net> My text file has five numbers, 1-5 I don't what the problem is. I've written the file using Word (saved as .txt ) as well as TextEdit Python 3.4.1 on a Mac Here's the code: # Richard Dillon # This program reads data from a .txt file and calculates a total # data in text file: 1,2,3,4 and 5 for a total of 15 # error message: Non-numeric data found in the file def main(): total = 0.0 try: infile = open('/Users/richarddillon/Desktop/numbers.txt', 'r') for line in infile: amount = float(line) total += amount infile.close() print(format(total, ',.2f')) except IOError: print('An error occured trying to read the file.') except ValueError: print('Non-numeric data found in the file.') except: print('An error occured.') main() From lnartist at yahoo.com Sun Aug 31 19:28:32 2014 From: lnartist at yahoo.com (LN A-go-go) Date: Sun, 31 Aug 2014 10:28:32 -0700 Subject: [Tutor] calculate percents of items in a list Message-ID: <1409506112.54330.YahooMailNeo@web161302.mail.bf1.yahoo.com> What would be a better way to calculate percentages of items in a list? please.... CountList = [9221382, 10374466, 5192905, 1710238, 3359] CL = [float(i) for i in CountList] CL sum = CL[0] + CL[1] + CL[2] + CL[3] + CL[4] import math perList = [] n = 0 def percentage(CL,sum): for i in CL: PER = "return 100 * float (CL[0])/float (sum)" perList.append(PER) n = n + 1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwpolska at gmail.com Sun Aug 31 20:44:40 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sun, 31 Aug 2014 20:44:40 +0200 Subject: [Tutor] This is driving my crazy! My file hasn't been corrupted In-Reply-To: <58634834-2327-48FD-BFD1-D4F63F5835FC@comcast.net> References: <58634834-2327-48FD-BFD1-D4F63F5835FC@comcast.net> Message-ID: On Sun, Aug 31, 2014 at 6:31 PM, Richard Dillon wrote: > My text file has five numbers, 1-5 > I don't what the problem is. > I've written the file using Word (saved as .txt ) as well as TextEdit > Python 3.4.1 on a Mac We don?t really know either, without seeing the file. It probably has some unwanted garbage produced by your fancy-schmancy editor. Get a real plain text editor (TextWrangler for example) and don?t use rich-text editors. With a real editor, your code works here. Also, don?t do this: > except: > print('An error occured.') It?s better to let Python show the exceptions. -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From steve at pearwood.info Sun Aug 31 21:19:06 2014 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 1 Sep 2014 05:19:06 +1000 Subject: [Tutor] This is driving my crazy! My file hasn't been corrupted In-Reply-To: <58634834-2327-48FD-BFD1-D4F63F5835FC@comcast.net> References: <58634834-2327-48FD-BFD1-D4F63F5835FC@comcast.net> Message-ID: <20140831191906.GC9293@ando.pearwood.info> On Sun, Aug 31, 2014 at 09:31:25AM -0700, Richard Dillon wrote: > My text file has five numbers, 1-5 > I don't what the problem is. You'll probably find out if you ask Python to show you what is actually causing the problem. > I've written the file using Word (saved as .txt ) as well as TextEdit > Python 3.4.1 on a Mac > > Here's the code: > > # Richard Dillon > > # This program reads data from a .txt file and calculates a total > # data in text file: 1,2,3,4 and 5 for a total of 15 > # error message: Non-numeric data found in the file > > def main(): > total = 0.0 > try: > infile = open('/Users/richarddillon/Desktop/numbers.txt', 'r') > for line in infile: > amount = float(line) > total += amount > infile.close() > print(format(total, ',.2f')) > except IOError: > print('An error occured trying to read the file.') You don't know that it is a read error. Look at the try block: you do SEVEN different things: - open a file - read the file - convert lines of text into floats - add numbers together - close the file - call the format function - print some string. All of them could *in principle* raise IOError, although in practice only three of them are serious candidates. If you have an IOError, how do you know whether it was *opening*, *reading* or *closing* the file that failed? (Yes, closing files can fail.) Lesson 1: never protect too much by a single try...except block. Lesson 2: never catch any error that you don't know how to recover from. If you *don't* catch the IOError, Python will print the full exception, which will show you exactly what failed (say, opening the file), the error code, and the error message. > except ValueError: > print('Non-numeric data found in the file.') Again, there are seven things which could theoretically raise ValueError, although this time only one of them is likely to. Never the less, the same rule applies: don't protect too much with a try block. In this case, this is much more useful: infile = open('/Users/richarddillon/Desktop/numbers.txt', 'r') for line in infile: try: amount = float(line) except ValueError: print(repr(line)) raise total += amount infile.close() print(format(total, ',.2f')) The call to repr will convert any weird invisible characters to backslash escapes so you can see them. But I suspect what you will see is nothing weirder than a blank line: py> line = '\n' # blank line py> float(line) Traceback (most recent call last): File "", line 1, in ValueError: could not convert string to float: > except: > print('An error occured.') Oh, well that explains everything. "An error occurred." With all that diagnostic information, debugging will be so easy! Not. Seriously, don't do that. If an error occurs, Python gives you a heap of information to make it easy to debug. You collect that information, flush it down the toilet, and replace it with an innane and meaningless generic message like "An error occurred". -- Steven From dyoo at hashcollision.org Sun Aug 31 21:42:35 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 31 Aug 2014 12:42:35 -0700 Subject: [Tutor] calculate percents of items in a list In-Reply-To: <1409506112.54330.YahooMailNeo@web161302.mail.bf1.yahoo.com> References: <1409506112.54330.YahooMailNeo@web161302.mail.bf1.yahoo.com> Message-ID: On Aug 31, 2014 11:34 AM, "LN A-go-go" wrote: > > > What would be a better way to calculate percentages of items in a list? > please.... > Without showing us your code, try to explain a few examples of the problem you're trying to solve, and show us expected answer. The problem of just showing code is that it may work perfectly well, and yet do things that you do not want. Concretely, I have no idea what you mean by the term "calculate percentage of items in a list". You need to explain the idea in terms that are independent of your code. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Sun Aug 31 22:17:09 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 31 Aug 2014 13:17:09 -0700 Subject: [Tutor] how import a module upon instantiation of a class? Message-ID: <1409516229.84753.YahooMailNeo@web163803.mail.gq1.yahoo.com> Hi, I want to import a module upon instantiation (not definition) of a class. What is the best way to do this? In my case, I need the "icu" module in only one place/class of the program. If that class won't be used, I don't want to have an ImportError. Also, it might be nice to do the imports only when you actually need that functionality. It's probably not really PEP-compliant to put the imports somewhere else than at the top of the module, but I can live with that. import some_nonbuiltin # I don't want it here! class KlassA(object): import some_nonbuiltin # nope def __init__(self): some_nonbuiltin = __import__("some_nonbuiltin") # idem x = some_nonbuiltin.blah() class KlassB(object): """some_nonbuiltin not needed here! """ def __init__(self): pass Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~