某些时候我们需要获得系统当前的用户名,那么在Pyton中有没有一个可跨平台的方式或者类库支持这一操作呢?
最常用的就是getpass模块:
| 1 2 3 | >>>``import``getpass >>> getpass.getuser() 'kostya' |
| --- | --- |
这个模块无论在linux还是在windows上都可以使用。还有一种方法,使用os.getenviron,这一做法有点不安全,是因为它跟环境变量设置有关。
| 1 2 | >>> os.environ[``'USERNAME'``] 'Administrator' |
| --- | --- |
如果你使用的是linux系统,获取方式还有:
| 1 2 3 4 5 | import os import pwd def get_username(): return``pwd.getpwuid( os.getuid() )[``0``] |
| --- | --- |
0 Comments latest
No comments.