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.


Applescript
set user to system attribute "USER"Use inline C and call geteuid(). :)
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.
Notice on Python:
On my System (WinXP, Py2.4.3) I have no “USER” key. Instead I have to use the “USERNAME” key.
Greetz
The first code used by VS2005 is no longer available, can you update your site?
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.