Trying to recreate the ls -l command in Python

0

I have been creating a bash simulator in windows using python for some time, at this moment I am programming the command:

ls -l

The problem is that I do not know how to make the following data in the file or folder print:

  • permissions
  • user
  • creation date

Thank you very much for your attention.

    
asked by binario_newbie 30.04.2018 в 05:02
source

1 answer

1

The following shows how to extract the information you are looking for, through os.stat() , and how to format it to look similar to ls -l .

Specifically:

  • I use the module pwd to extract the user's name, starting from its uid .
  • Use the module time to format the date and time of the last change
  • I include a sizeof_fmt() function to format the size in a similar way to how the flag -h of ls (giving more readable size units for people, instead of using bytes).

For a more faithful simulation of ls you would still need to show the group and read-write permissions. That information also gives you os.stat .

This is my code:

import time
import os
import pwd

def sizeof_fmt(num):
    for unit in ['B', 'K', 'M', 'G']:
        if num < 1024:
            return "%3.1f%s" % (num, unit)
        num /= 1024.0
    return "%3.1f%s" % (num, 'T')

def format_file(filename, dirname=''):
    _stat = os.stat(os.path.join(dirname, filename))
    tamano = sizeof_fmt(_stat.st_size)
    propietario = pwd.getpwuid(_stat.st_uid)[0]
    modificado = time.strftime("%Y-%m-%d %H:%M", time.localtime(_stat.st_mtime))
    ret = "%8s %10s %s %s" % (
            propietario, tamano, modificado, filename
            )
    return ret

for filename in sorted(os.listdir(".")):
    print(format_file(filename))

Example of output:

root     188.0K 2015-08-17 07:10 zip
root      84.2K 2015-08-17 07:10 zipcloak
root      47.3K 2018-04-05 14:48 zipdetails
root       2.9K 2015-11-20 15:41 zipgrep
root     158.9K 2015-11-20 15:41 zipinfo
root      79.9K 2015-08-17 07:10 zipnote
root      79.9K 2015-08-17 07:10 zipsplit
root     265.0B 2016-02-07 18:59 zxpdf
    
answered by 30.04.2018 / 13:51
source