Skip to content

Instantly share code, notes, and snippets.

@Choumingzhao
Last active March 1, 2024 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Choumingzhao/dbb1d8930f2229452523ad3c6e15bd82 to your computer and use it in GitHub Desktop.
Save Choumingzhao/dbb1d8930f2229452523ad3c6e15bd82 to your computer and use it in GitHub Desktop.
Run current python with sudo

A shell function for easier running python script with sudo

#!/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)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment