有没有一种可移植的方法来获取Python中的当前用户名? [英] Is there a portable way to get the current username in Python?

查看:113
本文介绍了有没有一种可移植的方法来获取Python中的当前用户名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在一种可移植的方式来获取Python中当前用户的用户名(即,至少在Linux和Windows上均可使用的用户名).就像os.getuid:

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:

>>> os.getuid()
42
>>> os.getusername()
'slartibartfast'

我在Google周围四处搜寻,很惊讶地没有找到确切的答案(尽管也许我只是在谷歌搜索方面很差). pwd 模块提供了一种相对简单的方法来实现此目的例如在Linux下,但在Windows上不存在.一些搜索结果表明,在某些情况下(例如,作为Windows服务运行),在Windows下获取用户名可能会很复杂,尽管我尚未对此进行验证.

I googled around and was surprised not to find a definitive answer (although perhaps I was just googling poorly). The pwd module provides a relatively easy way to achieve this under, say, Linux, but it is not present on Windows. Some of the search results suggested that getting the username under Windows can be complicated in certain circumstances (e.g., running as a Windows service), although I haven't verified that.

推荐答案

查看 getpass 模块

import getpass
getpass.getuser()
'kostya'

可用性:Unix,Windows

Availability: Unix, Windows

p.s.在""下面的每个注释中,此函数查看各种环境变量的值以确定用户名.因此,不应出于访问控制目的(或可能出于任何其他目的)依赖此函数,因为它允许任何用户模仿任何其他)."

这篇关于有没有一种可移植的方法来获取Python中的当前用户名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆