greduan
greduan

Reputation: 4938

Go into sudo user, run couple of commands, go back to normal user in Python script

The problem I've run into is that I want to temporarily get into the sudo user, run a couple of commands, and then go back to a normal user and run the commands in that mode.

You can find the script I'm gonna use it in here: https://github.com/Greduan/dotfiles/blob/master/scripts/symlinks.py

Basically, when I'm installing the scripts under the /bin folder of my dotfiles I need sudo access in order to make a symlink to that folder. You can find this part of the script under the last for statement in the code.

However, since I do depend on some commands that use the current user as a guideline to do stuff, I can't just run the entire script as sudo. Last time I tried I got a lot of errors about a folder not existing.

Thanks for all the help you can provide.

Upvotes: 0

Views: 280

Answers (2)

greduan
greduan

Reputation: 4938

In the end I tried @Blender's solution, but it didn't work or I wasn't able to figure it out.

So Instead I did the following:

subprocess.Popen('sudo rm ' + final_dest, shell=True)

and:

subprocess.Popen('sudo ln -s ' + final_src + ' ' + final_dest, shell=True)

This works correctly as I expected it and it has no extra dependencies. Thanks for your answer @Blender but it didn't work for me. ;|

Upvotes: 0

Blender
Blender

Reputation: 298532

If you don't mind installing an external dependency, the sh module makes this pretty simple:

import sh

sh.cp('foo.txt', 'bar.txt')

with sh.sudo:
    sh.cp('foo2.txt', 'bar2.txt')

Upvotes: 4

Related Questions