I want to execute a python file in /var/www/html:
sudo python myFile.pyWhich works fine.
Now, I want to write the output to log.txt.
So, I type:
sudo python myFile.py >> log.txtHowever, I get the following error:
-bash: log.txt: Permission denied
Though I changed the permissions of log.txt:
sudo chmod u+x log.txtAnd ls -l log.txt returns:
-rwxr--r-- 1 www-data www-data 0 Feb 3 16:04 log.txt
How can I fix this?
42 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
Two options I can think of:
sudo bash -c "python myFile.py >> log.txt", orsudo chmod u+x myFile.py, thensudo ./myFile.py >> log.txt