Is there a portable way to get the current username in Python?

前端 未结 12 811
别那么骄傲
别那么骄傲 2020-11-22 03:11

Is there a portable way to get the current user\'s username in Python (i.e., one that works under both Linux and Windows, at least). It would work like os.getuid

12条回答
  •  逝去的感伤
    2020-11-22 03:42

    Using only standard python libs:

    from os import environ,getcwd
    getUser = lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"]
    user = getUser()
    

    Works on Windows, Mac or Linux

    Alternatively, you could remove one line with an immediate invocation:

    from os import environ,getcwd
    user = (lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"])()
    

提交回复
热议问题