Get The Current Username in Different Languages

Sunday, August 26, 2007

How would you get the current user’s name in your programming language of choice? Furthermore, how does this exercise reflect on the design of that language?

C#

string user = Environment.UserName;

Perl

my $user = getpwuid($<);

PHP

$user = $_ENV['user'];

Python

import os
user = os.environ['USER']

Ruby

user = ENV['USER']

Now that I’ve iterated through a few of these I’m wondering if the methods are equivalent. In every language except Perl it seems like I’m just accessing the ‘user’ property of the current environment variables. Is there a better way to get the name of the current user in those other languages? I read a perldoc1 that says getpwuid is the best method in Perl.

  1. getlogin – perldoc.perl.org
tagged: asides, software
written by Brad Fults

Archived at: http://h3h.net/2007/08/get-the-current-username-in-different-languages/

6 responses

  1. John

    Applescript
    set user to system attribute "USER"

  2. D.J. Capelis

    Use inline C and call geteuid(). :)

  3. apotheon

    This is a very late response, but . . .

    In Ruby:

    require 'etc'
    user = Etc.getpwuid.name

    Etc is part of the standard/core library of Ruby. Etc.getpwuid returns a bunch of information about the current user (or you can specify a specific user as an argument). A number of methods pick out specific parts of that information, such as name (as above), dir (for the user’s home directory), and so on.

  4. Tim

    Notice on Python:

    On my System (WinXP, Py2.4.3) I have no “USER” key. Instead I have to use the “USERNAME” key.

    Greetz

  5. Kaven

    The first code used by VS2005 is no longer available, can you update your site?

  6. Brad Fults

    This is not meant to be a resource for the current documentation in different languages. It just asks a question about different methods for getting the current username.

    Feel free to link to updated docs in a comment if you want to point people in the right direction for a specific language or method.

  7. Comment Preview