Search code examples
pythonpython-os

Permission denied for mkdir


I installed my own package via sudo python setup.py install locally. In its source code there's the code which causes OSError: (13, 'Permission denied', '....'):

curr_dir = os.path.dirname(os.path.realpath(__file__))
    if not os.path.exists(os.path.dirname(os.path.join(curr_dir, "dir1/log1.out"))):
        os.makedirs(os.path.dirname(os.path.join(curr_dir, "dir1/log1.out")))

curr_dir is:

/usr/local/lib/python2.7/site-packages/my_app-1.2.3-py2.7.egg/my_app

And:

$ ls -al '/usr/local/lib/python2.7/site-packages/my_app-1.2.3-py2.7.egg/my_app'
total 696
drwxr-xr-x  35 root  admin   1190 Mar 29 12:00 .
drwxr-xr-x   4 root  admin    136 Mar 29 12:00 ..
-rw-r--r--   1 root  admin    108 Mar 29 12:00 __init__.py
-rw-r--r--   1 root  admin    202 Mar 29 12:00 __init__.pyc
-rw-r--r--   1 root  admin  11964 Mar 29 12:00 file1.py
-rw-r--r--   1 root  admin  12953 Mar 29 12:00 file1.pyc
-rw-r--r--   1 root  admin  13424 Mar 29 12:00 file2.py
-rw-r--r--   1 root  admin  15621 Mar 29 12:00 file2.pyc
.....

How can I fix it?

P.S. Even I create a file curr_dir, "dir1/log1.out manually by mkdir and touch, the python code also throws the same exception while being executed.


Solution

  • I installed my own package via sudo python setup.py install locally.

    Once you used sudo (which you should not do), all files that your package includes are owned by root because its the root user that is running setup.py install.

    Now, when you try to run any module that is included in the package as your normal user, and that module tries to open/modify/read/create any directory or file that is part of the package itself, it will run into permission problems. All files for your package are owned by root, and you are trying to run it with your normal user, and that user cannot create directories in the package's source path (which is referred to here os.path.dirname(os.path.realpath(__file__)).

    The solution to your problem is to first, uninstall the module (you can simply delete the entire tree as root).

    Next, as your normal user, create a virtual environment and install your package. This will make sure that:

    1. Your package isn't installed in the global Python package repository.
    2. Files for your package are owned by your normal user account.
    3. Any file-level operations can be performed properly without using elevated permissions (like sudo).

    Now, if you need to create these directories as part of your package's setup procedure, then you need to modify your setup.py.