Search code examples
pythonpython-3.xlinuxpermissionsroot

In Python, check if executed as root


How can I check if my program is running with root permission. Does Pathlib offer the possibility to query the USER-ID under Linux


Solution

  • You can access username with standard library package getpass:

    import getpass
    print(getpass.getuser())
    

    When code is executed with sudo or as root, the user is the string root.