{"id":3712,"date":"2016-02-14T18:45:03","date_gmt":"2016-02-14T23:45:03","guid":{"rendered":"http:\/\/kodegeek.com\/blog\/?p=3712"},"modified":"2016-02-21T15:08:02","modified_gmt":"2016-02-21T20:08:02","slug":"escribiendo-ls-en-python3","status":"publish","type":"post","link":"http:\/\/kodegeek.com\/blog\/2016\/02\/14\/escribiendo-ls-en-python3\/","title":{"rendered":"Escribiendo &#8216;ls&#8217; en Python3"},"content":{"rendered":"<p>El programa a continuaci\u00f3n es un ejemplo de las cosas que se pueden hacer con Python 3. Para m\u00ed fue una excusa para aprender lo siguiente:<\/p>\n<ul>\n<li>Uso de &#8216;.format&#8217; para mostrar contenido con formato (mucho mejor que interpolaci\u00f3n de cadena de caracteres con &#8216;%&#8217;)<\/li>\n<li>La librer\u00eda &#8216;OptionParser&#8217; (Mejor que Getoptions)<\/li>\n<li>Trucos con &#8216;list comprehensions&#8217; , ordenaciones<\/li>\n<li>Referencias a funciones<\/li>\n<\/ul>\n<p>(Les debo el manejo de recursividad, me dio algo de flojera escribirlo :-))<br \/>\n&nbsp;<\/p>\n<pre lang=\"python\">#!\/usr\/bin\/env python3\r\nfrom optparse import OptionParser, OptionValueError\r\nfrom collections import namedtuple\r\nimport locale, os, time\r\nfrom _locale import LC_ALL\r\nlocale.setlocale(LC_ALL, \"en_US.UTF-8\") # locale -a\r\nusage = '''\r\n%prog [options] [path1 [path2] [... pathN]]]\r\nThe paths are optional; if not given '.' is used\r\n@author: Jose Vicente Nunez (josevnz@kodegeek.com)\r\n'''\r\nEntry = namedtuple('Entry', 'name size modified')\r\n\r\ndef orderCheck(option, opt_str, value, parser):\r\n    if value in ['n', 'name']:\r\n        parser.values.order = \"name\"\r\n    elif value in ['m', 'modified']:\r\n        parser.values.order = \"modified\"\r\n    elif value in ['s', 'size']:\r\n        parser.values.order = \"size\"\r\n    else:\r\n        raise OptionValueError(\"Invalid value for --order received: {0}\".format(value))\r\n\r\ndef getKeyByName(entry):\r\n    return entry.name\r\n\r\ndef getKeyBySize(entry):\r\n    return int(entry.size)\r\n\r\ndef getKeyByModif(entry):\r\n    return int(entry.modified())\r\n\r\ndef createTuple(path):\r\n    bits = os.stat(path)\r\n    return Entry(path, bits.st_size, bits.st_mtime) \r\n\r\ndef doLs(path, hidden, getKey):\r\n    if (not os.path.isdir(path)):\r\n        return path\r\n    if hidden: # On Unix, hidden files start with '.'\r\n        return sorted([ createTuple(os.path.join(path, entry)) for entry in os.listdir(path) ], key=getKey, reverse=False)\r\n    return sorted([ createTuple(os.path.join(path, entry)) for entry in os.listdir(path) if entry[0] != \".\" ], key=getKey, reverse=False)\r\n\r\ndef doLsR(path, hidden, getKey):\r\n    # TODO\r\n    pass\r\n\r\ndef formatEntries(entries, modified, sizes):\r\n    if entries == None:\r\n        return\r\n    dirs = 1\r\n    files = 0\r\n    for entry in entries:\r\n        mod = time.ctime(entry.modified) if modified else \"\"\r\n        size = entry.size if sizes else \"\"\r\n        if os.path.isfile(entry.name):\r\n            files += 1\r\n        else:\r\n            dirs += 1\r\n        print(\"{modif}{theSize:>10,} bytes{name:>35}\".format(modif=mod, theSize=size, name=entry.name))\r\n    print(\"files={0}, directories={1}\".format(files, dirs))\r\n        \r\nparser = OptionParser(usage=usage)\r\nparser.add_option(\"-H\", \"--hidden\", action=\"store_true\", dest=\"hidden\", default=False, help='Show hidden files [default: off]')\r\nparser.add_option(\"-m\", \"--modified\", action=\"store_true\", dest=\"modified\", default=False, help='Show last modified date\/time [default: off]')\r\nparser.add_option(\"-r\", \"--recursive\", action=\"store_true\", dest=\"recursive\", default=False, help='Recurse into sub-directories [default: off]')\r\nparser.add_option(\"-s\", \"--sizes\", action=\"store_true\", dest=\"sizes\", default=False, help='Show sizes [default: off]')\r\nparser.add_option(\"-o\", \"--order\", action=\"callback\", type=\"string\",  callback=orderCheck, default=\"name\", help='''Order by ('name', 'n', 'modified', 'm', 'size', 's') [default: name]''')\r\n(options, args) = parser.parse_args()\r\nhidden = options.hidden\r\nmodified = options.modified\r\nrecursive = options.recursive\r\nsizes = options.sizes\r\norder = options.order\r\ngetKey = getKeyByName\r\nif order == 'size':\r\n    getKey = getKeyBySize\r\nelif order == 'modified':\r\n    getKey = getKeyByModif\r\npaths = args if len(args) > 0  else [\".\"]\r\nlsCallback = doLs if not recursive else doLsR\r\n\r\nfor path in paths:\r\n    formatEntries(lsCallback(path, hidden, getKey), modified, sizes)\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>El programa a continuaci\u00f3n es un ejemplo de las cosas que se pueden hacer con Python 3. Para m\u00ed fue una excusa para aprender lo siguiente: Uso de &#8216;.format&#8217; para mostrar contenido con formato (mucho mejor que interpolaci\u00f3n de cadena de caracteres con &#8216;%&#8217;) La librer\u00eda &#8216;OptionParser&#8217; (Mejor que Getoptions) Trucos con &#8216;list comprehensions&#8217; , <a class=\"read-more\" href=\"http:\/\/kodegeek.com\/blog\/2016\/02\/14\/escribiendo-ls-en-python3\/\">[&hellip;]<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[239],"tags":[781,780,765,778,775],"_links":{"self":[{"href":"http:\/\/kodegeek.com\/blog\/wp-json\/wp\/v2\/posts\/3712"}],"collection":[{"href":"http:\/\/kodegeek.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/kodegeek.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/kodegeek.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/kodegeek.com\/blog\/wp-json\/wp\/v2\/comments?post=3712"}],"version-history":[{"count":7,"href":"http:\/\/kodegeek.com\/blog\/wp-json\/wp\/v2\/posts\/3712\/revisions"}],"predecessor-version":[{"id":3721,"href":"http:\/\/kodegeek.com\/blog\/wp-json\/wp\/v2\/posts\/3712\/revisions\/3721"}],"wp:attachment":[{"href":"http:\/\/kodegeek.com\/blog\/wp-json\/wp\/v2\/media?parent=3712"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/kodegeek.com\/blog\/wp-json\/wp\/v2\/categories?post=3712"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/kodegeek.com\/blog\/wp-json\/wp\/v2\/tags?post=3712"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}