Package advene :: Package util :: Module files
[hide private]
[frames] | no frames]

Source Code for Module advene.util.files

 1  """ 
 2  I contain utility functions to handle local and distant files. 
 3  """ 
 4   
 5  from os import mkdir, path 
 6  from os.path import dirname, exists, join 
 7  from urllib import pathname2url, url2pathname 
 8  from urllib2 import urlopen 
 9  from urlparse import urlparse 
10   
11 -def recursive_mkdir(dir, sequence):
12 """Make a sequence of embeded dirs in `dir`, and return the path. 13 14 E.g. ``recursive_mkdir('/tmp', ['a', 'b', 'c'])`` will create ``/tmp/a``, 15 ``/tmp/a/b`` and ``/tmp/a/b/c``, and return the latter. 16 17 Note that it is not an error for some of the directories to already exist. 18 It is not an error either for sequence to be empty, in which case dir will 19 simply be returned. 20 """ 21 if len(sequence) > 0: 22 newdir = path.join(dir, sequence[0]) 23 if not exists(newdir): 24 mkdir(newdir) 25 return recursive_mkdir(newdir, sequence[1:]) 26 else: 27 return dir
28
29 -def smart_urlopen(url):
30 """ 31 Opens a URL, using builtin `open` for local files 32 (so that they are writable). 33 34 Also, uses the URL proxy. 35 """ 36 url = __url_proxy.get(url, url) 37 p = urlparse(url) 38 if p.scheme == "file": 39 return open(url2pathname(p.path)) 40 else: 41 return urlopen(url)
42 43 __url_proxy = { 44 "http://liris.cnrs.fr/advene/cam/bootstrap": 45 "file:" + pathname2url(join(dirname(__file__), "bootstrap.bzp")), 46 } 47
48 -def add_url_proxy(url, proxy_url):
49 """ 50 Associate a proxy_url to the given url. 51 """ 52 __url_proxy[url] = proxy_url
53
54 -def remove_url_proxy(url):
55 """ 56 Dissociate any proxy_url from the given url. 57 """ 58 del __url_proxy[url]
59
60 -def get_path(f):
61 """Extract the path of file-like object `f`. 62 63 This works for objects returned either by `open` or `urlopen`. 64 """ 65 url = getattr(f, "url", None) 66 if url is not None: 67 path = urlparse(url).path 68 else: 69 path = getattr(f, "name", "") 70 return path
71
72 -def is_local(f):
73 """Return True if file-like object `f` is a local file. 74 75 This works for objects returned either by `open` or `urlopen`. 76 """ 77 url = getattr(f, "url", None) 78 if url is not None: 79 return urlparse(url).scheme == "file" 80 else: 81 return isinstance(f, file)
82