Search code examples
pythonmacosbashmacportssudo

Macports sudo expands ~ to /var/root in python


I installed the macports version of sudo. All is well, except for one thing. Using python 2.6 to expand ~ to the user's home directory results in a different output than the version of sudo that comes with Snow Leopard.

For example consider the following python code:

#expand_home_dir.py
import os

os.path.expanduser('~')

Below are 3 different calls of the code listed above. The first call using sudo is using the Macports version because my $PATH begins with /opt/local/bin:

robert$ python2.6 expand_home_dir.py 
/Users/robert
robert$ sudo python2.6 expand_home_dir.py 
/var/root
robert$ /usr/bin/sudo python2.6 expand_home_dir.py
/Users/robert

Any idea why this is happening?


Solution

  • The HOME environment variable controls what ~ expands to. It sounds like your MacPorts-installed version of sudo is resetting HOME to the root user's home directory, while the system-installed version doesn't. What happens if you type sudo sh -c 'echo $HOME'?