python怎么读取当前用户名,有没有一种可移植的方法来获取Python中的当前用户名?...

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'

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.

解决方案

Look at getpass module

import getpass

getpass.getuser()

'kostya'

Availability: Unix, Windows

p.s. Per comment below "this function looks at the values of various environment variables to determine the user name. Therefore, this function should not be relied on for access control purposes (or possibly any other purpose, since it allows any user to impersonate any other)."

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值