1

I'm running a Python script on a fresh installation of Ubuntu 20.04.2. The script checks if a directory exists and creates it if not. The code is:

os.makedirs(f'..{os.sep}logs{os.sep}')

I get the following error:

PermissionError: [Errno 13] Permission denied: '../logs/'

In the command prompt, I would just add a sudo but I need my Python script to be able to make these directories so, my question is how can I allow Python to make new directories?

2
  • 2
    run the script as root Commented May 25, 2021 at 16:54
  • 1
    Or give write permission on that path to your self (Or the user who run python script) Commented May 25, 2021 at 17:01

1 Answer 1

2

The simple answer is: you don't. While I am sure it is possible to have your script ask for and get elevated permissions, the normal way of doing this is to assume that whoever runs the script has access to what the script needs to change. After all, if the user doesn't have permission, then the user has no business running the script in the first place.

So just write your script, and leave it to the user to ensure that they have the right to do what they want to do. Instead, you should modify your script to catch the error and give a more informative error message so the user can know what directory they require access to and what kind of access. So instead of ../log, get the full path and instead of "permission denied" check what permissions are required, and test for them before attempting the operation. That way, you can error out gracefully and tell the user what they need.

2
  • Thanks @terdon. I have resolved my issue using your and @YetAnotherUser's advice and given myself the correct permissions following along with this link (askubuntu.com/questions/1013528/…). The relevant code is sudo chown -R username: directory I have not modified the script for the time being since there are really no users to deal with but that certainly does seem like a great way to handle the issue. I think it would be useful for others if you were to edit your answer to outline how you would enact your solution. Commented May 26, 2021 at 17:54
  • @Casivio that would depend on the programming language used, the environment, the exact details of what the script needs to do etc. Commented May 26, 2021 at 17:58

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.