os.lstat : proper way to do this

m1k3b0 at gmail.com m1k3b0 at gmail.com
Fri Dec 12 18:06:05 EST 2008


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?

Thanks!
mikebo



More information about the Python-list mailing list