Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Fabric: How to retrieve a filelist of a dir

I'm building a remote server admin tool using the python-fabric library and am looking for a good way of retrieving a filelist for a directory on the remote server. Currently I'm using run("ls dir") and am manually splitting the return string, which seems horrendous and very much architecture dependent. fabric.contrib.files doesn't seem to contain anything of use..

Suggestions much appreciated.

Cheers, R

like image 376
Ricw Avatar asked Jul 08 '11 17:07

Ricw


2 Answers

I think the best way is to write a BASH (others shells behave similar) oneliner. To retrieve list of files in a directory.

for i in *; do echo $i; done

So the complete solution that returns absolute paths:

from fabric.api import env, run, cd

env.hosts = ["localhost"]
def list_dir(dir_=None):
    """returns a list of files in a directory (dir_) as absolute paths"""
    dir_ = dir_ or env.cwd
    string_ = run("for i in %s*; do echo $i; done" % dir_)
    files = string_.replace("\r","").split("\n")
    print files
    return files

def your_function():
    """docstring"""
    with cd("/home/"):
        list_dir()
like image 186
brodul Avatar answered Sep 21 '22 08:09

brodul


What's wrong with this?

output = run('ls /path/to/files')
files = output.split()
print files

Check the documentation on run() for more tricks.

like image 20
jathanism Avatar answered Sep 24 '22 08:09

jathanism