blueFast
blueFast

Reputation: 44431

Misleading documentation for os.open?

I have the following:

$ ls -l a.txt 
-rw------- 1 root root 0 Mai 13 09:01 a.txt

And I do the following:

$ python
Python 3.6.9 (default, Apr 18 2020, 01:56:04) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.open('a.txt', os.O_CREAT)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
PermissionError: [Errno 13] Permission denied: 'a.txt'
>>> 

Where is this documented? Not here, afaik. The only thing specified is the suggestion that os.open is a wrapper around the C run-time open system call, which states:

$ man 2 open

RETURN VALUE
       open(), openat(), and creat() return the new file descriptor, or -1 if an error occurred (in which case, errno is set appropriately).

So, where is the full documentation for os.open, including possible exceptions raised and a detailed description of the return value?

Upvotes: 0

Views: 48

Answers (1)

deceze
deceze

Reputation: 522442

You're looking for the ERRORS section of open(2):

ERRORS
     The named file is opened unless:

     [EACCES]           The requested access to the file is not allowed,
                        or search permission is denied for one of the
                        directories in the path prefix of pathname, or the
                        file did not exist yet and write access to the 
                        parent directory is not allowed.

     [..]

In this list, specific to your OS, you'll find all the different things that might go wrong. To translate that to Python exceptions, you can look at the list of builtin exceptions; all exceptions relevant here should inherit from OSError: https://docs.python.org/3/library/exceptions.html#os-exceptions

Each individual exception lists what underlying error code it corresponds to, so you can compare that to the open(2) list of possible errors. E.g.:

exception PermissionError
Raised when trying to run an operation without the adequate access rights - for example filesystem permissions. Corresponds to errno EACCES and EPERM.

In practice most of the time you'll probably want a catch-all except OSError block around your open call; if you do want to catch only very specific exceptions, you may have to experiment a bit yourself.

Upvotes: 3

Related Questions