os.lstat : proper way to do this

Benjamin Kaplan benjamin.kaplan at case.edu
Fri Dec 12 18:40:02 EST 2008


On Fri, Dec 12, 2008 at 6:06 PM, <m1k3b0 at gmail.com> wrote:

> I'm converting from Perl to Python, so I'm learning the basics -
> please be gentle! :)
>
> In Perl, I can lstat($file) whether $file exists or not:
> lstat($file);
> unless (-e _) {
>    print STDERR "$file: No such file or directory\n";
> }
> unless (-l _) {
>    print STDERR "$file: Not a symbolic link\n";
> }
>
> The lstat() returns normally whether the file exists or not, and I
> check for existence with the "-e" conditional. Then I go on and check
> other modes.
>
> In Python,if I os.lstat(file) and file doesn't exist, I get an error
> from within the module:
> OSError: [Errno 2] No such file or directory: '/etc/xxx'
>
> I can check first with os.path.exists(file), but then I'm doing two
> stat() type calls which is inefficient (especially when we're talking
> thousands of files).
>
> I want to be able to do something like this:
> mode = os.lstat(file)[ST_MODE]
> if not mode:
>    print >> sys.stderr, file, ": No such file or directory"
> if not S_ISLNK(mode):
>    print >> sys.stderr, file, ": Not a symbolic link"
>
> Of course, this isn't valid. How can I do this efficiently without
> getting "no such file" error?
>

In Python, people usually follow the "Easier to Ask Forgiveness than
Permission" philosophy. Rather than prevent an error from occurring, just
let it happen and deal with if when it does. Wrap your call to os.lstat in a
try/except block and just print your error message if the lstat call fails.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081212/baedaf41/attachment-0001.html>


More information about the Python-list mailing list