Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use fabric on localhost

Tags:

python

fabric

I'd like to use fabric to do stuff on my local machine in lieu of shell scripts.

For example, I'd like to check if a directory exists, and if it doesn't create that directory.

I can run stuff locally using local('ls'), but I'd like to use the other functionality in fabric like fabric.contrib.files.exists(path).

I've tried to RTFM but the lack of examples doesn't help.

How can I run, for example, fabric.contrib.files.exists('/path/to/test') on my localhost using fabric?


Here's what works for ls using local():

from fabric.api import local
def test():
    local('ls')

And here's a kind of janky solution that requires that I ssh onto my localhost to accomplish the task:

from fabric.api import env
from fabric.contrib import files
env.hosts = ['127.0.0.1']
def test():
    if files.exists('/Users/ryan'):
        print 'path exists!'

So I'd like the ease of local() with the functionality of everything else that comes with fabric.

like image 801
ryantuck Avatar asked Dec 13 '25 09:12

ryantuck


1 Answers

When it comes to fabric short of allowing loopback ssh connections you can't do much with their helper functions. local() (https://github.com/fabric/fabric/blob/1.11.1/fabric/operations.py#L1219) is just short for subprocess.. and a few more lines of code you will normally have to write, im not saying its useless, because i've used it in several occasions, but the os lib can do WAY more than that.

Theres an old expression, find the right tool for the job.

exists() (https://github.com/fabric/fabric/blob/1.11.1/fabric/contrib/files.py#L18) is running tests -e <file path> which will return a 0 is all is well or a 1 if it doesnt exist. -- can you already see this getting so ugly and out of hand that when you come back 3 months from now and look at this you'll be even more confused?!?!

if you really want to use local() do local(test -e <file path>) .. i still say just use os.

-- ps, don't use local(ls) -- like theres no need for that, subprocess is expensive, the os module is SO fast, and nice... os.listdir('.') why won't you just see the light?! :P


Answer to old question question

Local? Use os as in os.path.isfile(<file>) or os.path.isdir(<dir>) there is no point for fabric to support it since the os lib is so well maintained.

like image 89
Javier Buzzi Avatar answered Dec 16 '25 01:12

Javier Buzzi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!