0

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?

fbence
  • 505

1 Answers1

0

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.

UPDATE:
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

Michael D.
  • 2,830