[PYTHON] Useful context manager for fabric

fabric.api.path: Can manipulate $ PATH

You can mess with your PATH using fabric.api.path.

As an example, build Python from source, place it under / usr / local / bin, and run python here.

fabpath.py


import fabric.api as api

with api.path("/usr/local/bin", behavior="prepend"):
    api.run("python -V")

By specifying behavior = "prepend"

PATH=/usr/local/bin:$PATH

It is developed like this.

fabric.api.prefix: Perform preprocessing

You can use fabric.api.prefix to insert the specified process before all run and sudo instructions in the with block.

For example, use it to enable virtualenv.

enablevenv.py


import fabric.api as api

with api.prefix(". /home/www/bin/activate"):
    fabric.api.run("./manage.py syncdb")

fabric.api.shell_env: Add shell environment variables

As an example, run a Django script with a python command.

djscript.py


import fabric.api as api

with api.env_shell("PYTHONPATH=. DJANGO_SETTINGS_MODULE=settings.imagawa"):
    api.run("python dosomething.py")

Recommended Posts

Useful context manager for fabric
Python-dotfiles is useful for managing dotfiles
What makes Python's context manager happy?
How to use Python's Context Manager