Skip to content

Root mode context manager? #9

harlowja opened this Issue May 13, 2012 · 3 comments

3 participants


It might be useful to say do the following:

ls = local['ls'] (or use SshMachine here...)
with Root(ls) as root_ls:

This way people can run as other users in a pythonic way (root show as an example here). Similarly the same would be neat with ssh/remote shells. Sometimes u just need to run a single command as another user (ie apt-get install) and u don't want the rest of the commands ran as that user... Thoughts?


well, it's possible, but i don't see why not use sudo[ls](), especially for one-liners. you can, of course, extract this into a function or something, e.g.

def as_root(cmd):
    return sudo[cmd]()

it can also be a context manager, but there's nothing contextual about it... e.g., you don't "stop" being the other user, you just run things out of sudo. you can also do it like so

class AsUser(object):
    def __init__(self, username):
        self.username = username
    def __getitem__(self, cmd):
        return sudo["-u", self.username, cmd]

root = AsUser("root")
john = AsUser("john")


anyway, the point is, running something as another user is not contextual... you can have multiple users "living side by side" and run different commands as different users. on the other hand, cwd is contextual, because at any point of time, there's only one workdir.


okay, i feel it should be solved in a more cross-platform manner, so it will be moved into the local object. see #12


I understand why this issue was rejected as applied to running arbitrary commands, but I'll note that I arrived here looking for a way to perform a few local.path operations with sudo, such as delete and symlink. AFAIK the current way to do this is to avoid those functions and instead do

local['sudo'](local['rm', '-r'][local.path('somepath')])
local['sudo'](local['ln', '-s']['existspath', 'newpath'])

I can imagine a more natural feel with something like

with local.path.as_root(): # or local.path.as_user('root'):

or even

local.path('somepath').delete(sudo=True) # or .delete(user='root')
local.path('existspath').symlink('newpath', sudo=True) # or .symlink('newpath', user='root')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.