Ubuntu – Running python script with sudo returns “sudo: script.py: command not found”

executablesudo

I can run script.py without sudo successfully, but I am getting "sudo: script.py: command not found" when running sudo script.py. What I need to do to be able to run sudo script.py?

Best Answer

In order to call an executable by name like that, it needs to be in one of the directories stored in the special variable $PATH. That PATH is different for your regular user and for sudo:

$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

~$ sudo sh -c 'echo $PATH'
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Presumably, since the script is in your current directory, you are in a directory that is included in the PATH of your regular user, but not in the PATH of sudo. So you need to call the script with its full or relative path:

## If it is in _this_ directory, use ./
sudo ./script.py

## Alternatively, use the full path:
sudo /home/terdon/myscripts/script.py

## or a relative path. If you're in /home/terdon/foo, use:
sudo ../myscripts/script.py
Related Question