简体   繁体   English

如何检查哪个用户当前使用python登录计算机?

[英]How can i check which user is currently logged in on the computer with python?

So i wonder if there is a way to find out which user is currently logged in on the computer, and store it in a variable so i get print it out or do something else with it later. 因此,我想知道是否有一种方法可以找出哪个用户当前在计算机上登录,并将其存储在变量中,以便稍后将其打印出来或做其他事情。 The reason why i need this is because when i enter a path including the user, it's gonna be diffrent depending on which user is logged in. I tried to look for this on the internet but i could't find what I was looking for. 我之所以需要它,是因为当我输入包括用户在内的路径时,它会根据登录的用户而有所不同。我试图在Internet上寻找它,但找不到我想要的东西。

OS: Windows 8.1 Version: Python 3.4 Let me know if there is anything i need to clearify. 操作系统:Windows 8.1版本:Python 3.4让我知道是否需要清除任何内容。

OT: I'm sorry for any potential mistakes i've done, i'm new to this site. OT:对于我做过的任何潜在错误,我感到抱歉,我是这个网站的新手。

Example: 例:

checkuser = #The user currently logged in

print("The user currently logged in is: " + checkuser)

So for example if ExampleUser would be logged in it would print: 因此,例如,如果ExampleUser将登录,它将打印:

"The user currently logged in is: ExampleUser" “当前登录的用户是:ExampleUser”

Check this site 检查这个网站

the answer with your snippet would be: 您的摘要的答案将是:

import getpass
checkuser = getpass.getuser()

print("The user currently logged in is: " + checkuser)

Also if you need the name just because of the home directory path you can use os.environ['HOMEPATH'] (on Windows) to get the path directly. 另外,如果仅由于主目录路径而需要名称,则可以使用os.environ['HOMEPATH'] (在Windows上)直接获取路径。

Use the getpass module. 使用getpass模块。 It provides you with a getuser function that will return current user. 它为您提供了一个getuser函数,该函数将返回当前用户。

https://docs.python.org/2/library/getpass.html https://docs.python.org/2/library/getpass.html

Example: 例:

from getpass import getuser

print(getuser())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM