Sometimes you need root privileges to access system resources, install packages, modify protected files, or interact with system services. Here are simple and safe ways to run a Python script as root.

For example some packages like: ping3 will result in error:

PermissionError: [Errno 13] Permission denied

unless your are running the script as admin (root)

In the terminal:

sudo python3 my_script.py

If your system uses Python 3 by default:

sudo python my_script.py

You’ll be prompted for your password.

2. Use Enviroment (i.e. anaconda)

If you use different environment than the default one you need to identify it by:

$ which python

result

/home/user/anaconda3/bin/python

Now we can run the script with this Python installation:

Run the script as sudo:

sudo /home/user/anaconda3/bin/python test.py

3. Make the Script Executable with a Shebang

Add this at the top of your script:

#!/usr/bin/env python3

Then make it executable:

chmod +x my_script.py
sudo ./my_script.py

This might work in some cases.

4. Check for Root Inside the Script (Optional)

You can detect if the script is running as root and exit or re-run with sudo:

import os, sys

if os.geteuid() != 0:
    print("Please run as root")
    sys.exit(1)

5. Windows Administrator Mode

On Windows, open the command prompt as Administrator, then run:

python my_script.py

6. Caution:

Running scripts as root gives full system access — always review code and avoid unnecessary elevated privileges.

7. Resources