Skip to content


Using sudo to re-launch a Python script as root

06 Feb 2010

To ensure a Python script is launched as root, and automatically call sudo to re-launch it as root if not:

import os
import sys

if os.geteuid() != 0:
    os.execvp("sudo", ["sudo"] + sys.argv)

This will replace the current process, so there's no need to exit afterwards.

The second sudo is required because Python doesn't automatically set $0 to sudo in the new process.

In my script, which adds a new virtual host to Apache, I found it useful to put this after checking the parameters are valid, so I don't have to enter the root password1 just to be told there is a problem!

Disclaimer: I discovered this through trial-and-error - there may be problems with this, or they may be a better solution that I'm not aware of!


  1. I use sudo with the rootpw option enabled, so it's necessary to enter the root password, not the user password.
Current Mood:Cheerful
Listening To:Blue Man Group

Add a Comment

* Required field