Detect if Python running as sudo
On Unix-like systems such as Linux and macOS, Python can detect if a script is being run as sudo / root from the UID, which is by definition zero for root.
On Windows, the ctypes
module can be used to check if the current user is an administrator.
import os
import ctypes
def running_as_root() -> bool:
if os.name == 'nt':
return ctypes.windll.shell32.IsUserAnAdmin()
else:
return os.getuid() == 0