pyinvoke / invoke

Pythonic task management & command execution.
http://pyinvoke.org
BSD 2-Clause "Simplified" License
4.31k stars 365 forks source link

Add `Context.sudo_scope` context manager #999

Open Cc618 opened 2 weeks ago

Cc618 commented 2 weeks ago

As requested in #778, implemented a context manager that allows running multiple commands while changing user.

Usage

with c.sudo_scope():
    c.run("echo toto")
    c.run("whoami")  # root

# Supports `Context.sudo` options
with c.sudo_scope(user='hello'):
    c.run("whoami")  # hello

Implementation details

As prefix, Context.sudo_scope pushes its arguments to a stack Context.command_sudos. When creating a command, the arguments from the nearest sudo_scope are used to create the command as Context.sudo does.