#!/usr/bin/env bash
# Invoke current python as sudo
sudo_python() {
local python_path
python_path=$(which python)
if [ -z "$python_path" ]; then
echo "Python not found in PATH"
return 1
fi
sudo "$python_path" "$@"
}
Suppose you are in a virtual envirment and you want to run a script which requires sudo.
(env) $ python script.py # this will fail because sudo is not granted via python script.
(env) $ sudo python script.py # this will fail because the python be runned is not the python of your `env`, usually a system installed python
Many solutions to this problem are dangerous.
Now, add this function definition to your ~/.bashrc
or other shell configs and source it by manully source
or re-login. You just need to run:
(env) $ sudo_python script.py # this requires you input sudo password like other shell commands
You can test by running following commands and comparing the outputs yourself. These commands simply print current PYTHONPATH, you may run them in any python envs:
$ python -c "import sys; print(sys.path)"
$ sudo python3 -c "import sys; print(sys.path)" # system python usually cannot be found by default, use python3 here
$ sudo_python -c "import sys; print(sys.path)"