This is how I ensure a Python script is launched as root, and automatically call sudo
to re-launch it as root if not.
I found it useful to check the parameters are valid before re-launching as root, so I don’t have to enter the sudo password if there is a problem with the parameters, or I just want the help message.
Note 1: os.execvp()
replaces the running process, rather than launching a child process, so there's no need to exit afterwards.
Note 2: The extra "sudo
" in the second parameter is required because Python doesn't automatically set $0
to sudo
in the new process.