[Tutor] (no subject)

fleet@teachout.org fleet@teachout.org
Sat, 4 Aug 2001 18:39:05 -0400 (EDT)


>From: Michael P. Reilly <arcege@speakeasy.net>
>Subject: Re: [Tutor] sys.exit() not working
>
>On Sat, Aug 04, 2001 at 04:30:02PM -0400, fleet@teachout.org wrote:
>> The only difference I see is that in the second test I provide an error
>> condition and in the first test I don't.  Which brings me to another
>> question:  The error returned if there are no jpg/JPG files in the
>> directory appears to be a shell error message (RH Linux 7.0) and not a
>> Python error (because of popen, I presume).  If I *need* an error
>> condition after except, what do I put there (first test)?
>
>Did you try the first expression in an interpreter?  I did and I got
>no error (though there was a message written to stderr).  In fact,
>popen won't return an error, even if you gave it an invalid command.
>
>>>> string.split(os.popen('ls -1D /etc/*.[Jj][Pp][Gg]').read(), "\012")
>ls: /etc/*.[Jj][Pp][Gg]: No such file or directory
>['']

Well, yes, I did.  I considered the shell message an error (even if Python
didn't) and just assumed a failure.  Didn't realize an empty list was
returned.

>The result is a list containing an empty string.  No exception is raised
>so the except clause is not executed.  If you wanted an exception,
>then you would have to check the result and raise an exception yourself.

And changing the "try" block to a straight "if" statement works wonders.
if len(files)==1 and files[0]=='':   #in the event there's only one file
   sys.exit()                        #in the list or the first file in
                                     #a list could be ''. ??

Since the shell produces a relatively understandable error message, (and I
don't know how to suppress it), I don't bother to print an error message
of my own. (That changes if I use glob, though.)

>Incidently, you might want to look at the glob module, it will do
>this better for you, I think.  Also, readlines() doesthe same as
>string.split(read(), '\n').

Good point on the readlines().

>>>> os.popen('ls -1D /etc/*.[Jj][Pp][Gg]').readlines()
>ls: /etc/*.[Jj][Pp][Gg]: No such file or directory
>[]
>>>> import glob
>>>> glob.glob('/etc/*.[Jj][Pp][Gg]')
>[]

And glob doesn't include that nasty empty line at the bottom of the list either!  Thanks!

>(I use "/etc/" since I know there are no jpeg files there. ;))

I assumed as much.  I have these occasional rare flashes of insight! :)

Regards,
				- fleet -