Python Permission Denied Writing Output to File

Python Permission Denied Writing Output to File

I want to execute a python file in /var/www/html:

sudo python myFile.py

Which works fine.

Now, I want to write the output to log.txt.

So, I type:

sudo python myFile.py >> log.txt

However, I get the following error:

-bash: log.txt: Permission denied

Though I changed the permissions of log.txt:

sudo chmod u+x log.txt

And ls -l log.txt returns:

-rwxr--r-- 1 www-data www-data 0 Feb 3 16:04 log.txt

How can I fix this?

4

2 Answers

The problem here sudo python myFile.py >> log.txt is that you run sudo python myFile.py as root, but your shell is still running as your regular user, which means >> redirection won't work if you don't have permission to write to the log.txt

As George properly noted, you should do sudo bash -c "python myFile.py >> log.txt". Alternatively, if your myFile.py doesn't require root privileges, you can do python myFile.py | sudo tee log.txt

2

Two options I can think of:

  1. sudo bash -c "python myFile.py >> log.txt", or

  2. sudo chmod u+x myFile.py, then sudo ./myFile.py >> log.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.