title: setting up the environment when changing to another user
body: <p>I have a bash backup script run as root (cron) that delegates certain tasks to other specific bash scripts owned by different users. (simplified example, principle is, some things have to be done as root, different tasks are delegated to users with the appropriate environment (oracle, amazon, ...)</p>
  
  <pre><code>mkdir -p /tmp/backup$NAME
  su - oracle -c "~/.backups/export-test.sh"
  tar cf /tmp/backup/$NOW.tar /tmp/backup$NAME
  su - amazon upload_to_amazon.sh /tmp/backup/$NOW.tar
  </code></pre>
  
  <p>This script itself does then some tasks as user oracle:</p>
  
  <pre><code>mkdir -p $TMP_LOCATION
  cd ~/.backups
  exp $TMP_LOCATION/$NAME-$NOW
  </code></pre>
  
  <p>When I try to mimic this behaviour in python I came up with the following (started from cron as root)</p>
  
  <pre><code>name = "oracle"
  
  # part run as root
  os.makedirs(tmp_backup + name)
  
  
  os.setegid(pwd.getpwnam(name)[3])
  os.seteuid(pwd.getpwnam(name)[2])
  
  # part run as oracle
  os.makedirs(tmp_location)
  os.chdir(os.path.expanduser("~{user}/.backups".format(user=name)))
  subprocess.check_call(["exp",
                         "os.path.join(tmp_location, name+'-'+now)"
                        ])
  </code></pre>
  
  <p>In bash when using su -, a real new shell is invoked and all environment variables of that user are set.
  How can I improve this for my python script? Is there a standard recipe I can follow? I'm thinking of environment variables, umask, ...</p>
  
  <p>the environment is Solaris if that might matter.</p>