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?
  • 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. – Kernel Stearns Jan 10 at 14:55
up vote 9 down vote accepted

$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.

  • 1
    Why is it that when I type $HOSTNAME in my terminal command, it says: bash: /root: is a directory – Alex Oct 31 '09 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 '09 at 22:31

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

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.

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

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.