I am trying to run a script as another user, with the user's .bashrc properly loaded (it is a python script and it relies on $PYTHONPATH being properly set).

I tried everything I found for example here, but the best I could coax out of the system was an empty $PYTHONPATH (which is better than my original, where it actually used my $PYTHONPATH).

The usecase is that I'm teaching students about shebangs and paths and whatnot, and I wanted an automated way of checking whether their script are ok or not. I can check them by dropping into their envs with sudo su <username>, but that is very tedious.

How can I execute a script as another user, with their environment loaded the same as if I used sudo su <username> and then ran it myself?


I think that's what python virtual environments are good for.
Creating isolated and portable environments for each single python project.
No PYTHONPATH needed. You could put all projects to a share for all users and switch between projects envs.
If using version control just clone a project to your own environment and go from there. You can find many howtos in the web.

Otherwise sudo su <username> -c python /somepath/somescript.py should at least run somescript in a oneliner.

add the -l switch. Check the env with

sudo su -l foo -c printenv

Add Pythonpath like this to /home/foo/.bashrc
export PYTHONPATH=/banana

the oneliner starting the script is
sudo su -l <username> -c python /somepath/somescript.py

  • Unfortunately, your oneliner will not load environment variables :(
    – fbence
    Nov 4 '20 at 11:40
  • updated my answer
    – Michael D.
    Nov 4 '20 at 18:14
  • Unfortunately, that does not work either. Actually, if I -c "echo $PYTHONPATH" I see my own PYTHONPATH not <username>'s.
    – fbence
    Nov 6 '20 at 9:36
  • is the env var exported? check sudo su -l <username> -c printenv
    – Michael D.
    Nov 6 '20 at 13:27
  • Sorry about the slow response. Yes it does, HOME and USER are e.g. set, but no export in .bashrc is showing up.
    – fbence
    Nov 9 '20 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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