How to Make Python Get the Username in Windows and Then Implement It in a Script

How to make Python get the username in windows and then implement it in a script

os.getlogin() return the user that is executing the, so it can be:

path = os.path.join('..','Documents and Settings',os.getlogin(),'Desktop')

or, using getpass.getuser()

path = os.path.join('..','Documents and Settings',getpass.getuser(),'Desktop')

If I understand what you asked.

Is there a portable way to get the current username in Python?

Look at getpass module

import getpass

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)."

How to get Windows user's full name in python?

A bit of googling gives me this link

and this code:

import ctypes

def get_display_name():
GetUserNameEx = ctypes.windll.secur32.GetUserNameExW
NameDisplay = 3

size = ctypes.pointer(ctypes.c_ulong(0))
GetUserNameEx(NameDisplay, None, size)

nameBuffer = ctypes.create_unicode_buffer(size.contents.value)
GetUserNameEx(NameDisplay, nameBuffer, size)
return nameBuffer.value

Tested and works on Windows XP

As noted by OP in comment here, pywin32 wraps this same API call into a simpler function:


GetUserName pointing to ctypes.windll.secur32.GetUserNameExW, and 3 being the same 3 as the constant from ctypes

Python 2.7, use username in filepath

As it python 2.7 the above f-string won't work. Use '/home/{}/'.format(username) – Sergey Pugach

Thank you Sergey Pugach, that solved my problem perfectly. Thank the rest of y'all for solving my question within the pass 2 hours. Have a nice day!

Getting name of windows computer running python script?

It turns out there are three options (including the two already answered earlier):

>>> import platform
>>> import socket
>>> import os
>>> platform.node()
>>> socket.gethostname()
>>> os.environ['COMPUTERNAME']

python execute exe file with script, enter username, password, etc

You're almost there!

You can do the following:

import subprocess
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, shell=True)

You may need to use \n instead of \r if there are any problems. \r is a carriage return, and \n is a newline.

Related Topics

Leave a reply