简体   繁体   中英

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.

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')

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. ;|

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM