Fabric: Difference between revisions
From charlesreid1
(Created page with "=Basics= Edit a file called <code>fabfile.py</code> and put some fab directives in there. ==Hello World== <pre> def hello(): print("Hello world!") </pre> To run this f...") |
No edit summary |
||
| Line 78: | Line 78: | ||
print ourlist | print ourlist | ||
</pre> | </pre> | ||
[[Category:Linux]] | |||
[[Category:Python]] | |||
Revision as of 17:20, 1 August 2015
Basics
Edit a file called fabfile.py and put some fab directives in there.
Hello World
def hello():
print("Hello world!")
To run this fabric directive, just say:
$ fab hello
and you'll see your message print out.
Hello X
Basic example of taking an argument:
def hello(name="world):
print("Hello %s!" % name)
which you can call and pass an argument to like this:
$ fab hello:name=Joe
Running Commands
To run a command on a local machine, you can import the local function from the Fabric API:
from fabric.api import local
Now you can call local functions by saying local('git pull') or local('mkdir zzz').
from fabric.api import local
def list():
local('/bin/ls -1')
and we can call it by saying
$ fab list
Capturing Output
If you want to use the output from a command, you can capture the output like so:
def list():
z = local('/bin/ls -1', capture=True)
In the case of /bin/ls -1, we have a string containing the name of each file, separated by a newline character.
Combined with Python's splitline() function, we can turn a list of files using ls into a list of files in a Python list in just two lines:
from fabric.api import local
def list():
rawoutput = local('/bin/ls -1', capture=True)
ourlist = rawoutput.splitlines()
print ourlist