2

Suppose I want to edit /etc/profile:

PYTHONPATH = /home/CURRENT_USER/

  1. How do I have a variable that will automatically fill in the current user?
  2. What about hostname?
  3. Aren't these environment variables?
1
  • One thing to be careful with here - if you ever run this script as root by using sudo, then both whoami and $USER will return root, regardless of what user ran the script.
    – B00TK1D
    Jan 10, 2018 at 14:55

4 Answers 4

9

$USER should typically be set to the current user, and $HOSTNAME to the current hostname. If not, you can also get them from the output of whoami and hostname

Also, the user's home directory is not necessarily in /home/[username]. You should use the value of $HOME instead.

2
  • 1
    Why is it that when I type $HOSTNAME in my terminal command, it says: bash: /root: is a directory
    – Alex
    Oct 31, 2009 at 22:21
  • 4
    No, you need to echo $HOSTNAME. If you just give bash a variable as a command, how is it supposed to know what action to take on it?
    – EEAA
    Oct 31, 2009 at 22:31
1

If you wish to see all of your environmental variables available, use the following command:

bash$ set

Remember case sensitivity, for hostname you'll need $HOSTNAME, and $USER

bash$ echo $USER
sparks
bash$ echo $HOSTNAME
servername
0

Another approach is to add a call to sys.addsitedir in sitecustomize.py rather than PYTHONPATH.

However since Python 2.6 you probably don't need to do either, because /home/$USER/.local/lib/python2.6/site-packages is automatically added to sys.path. This is a good choice of standard place to put user-specific modules/packages; you wouldn't really want to add the home directory itself as a module path as it contains all sorts of things that aren't modules, which could confuse imports.

See PEP370 for details.

0

In python, call os.uname() to get the hostname (and other details in an array).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .