这是我使用的: import os username = getattr(os, "getlogin", None) if not username: for var in ['USER', 'USERNAME','LOGNAME']: if var in os.environ: username = os.environ[var] print("username: %s" % (username))