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

Add your thoughts | Trackback URL

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

4 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. Comment Preview

Leave a comment

Comments are posted at the discretion of the site owner. Please try to be respectful, insightful and otherwise useful to society as a whole.

(X)HTML is allowed. You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <blockquote cite=""> <cite> <code> <dfn> <em> <kbd> <q cite=""> <samp> <strike> <strong> <sub> <sup> <var>