Start a command line tool in Python

3

How can I create a command line tool in Python that works like ls of Linux or dir of Windows?

How would I start a script like the one that will later be compiled as an executable?

    
asked by anonymous 01.08.2016 / 21:55

2 answers

4

By comment what are you looking for are functions to simulate the behavior of ls or dir correct? so I recommend you look at the os.listdir command to list the files in a directory, the os.path to check for items from listdir oq is a file ( os.path.isfile ) or what is a directory ( os.path.isdir ) and os.stat to return the attributes of a file.

>>> import os
>>> files = os.listdir()
>>> files
['foo.txt']
>>> os.path.isfile(files[0])
True
>>> os.stat(files[0])
os.stat_result(st_mode=33188, st_ino=30049365, st_dev=16777218, st_nlink=1, st_uid=501, st_gid=20, st_size=4, st_atime=1470085341, st_mtime=1470085341, st_ctime=1470085341)

On the part of creating a command-line tool, you should search on argparse , one example would be:

import argparse
import os


parser = argparse.ArgumentParser(description='ls clone')
subparsers = parser.add_subparsers()

ls_parser = subparsers.add_parser(
    'ls', help='lista os arquivos e diretórios do diretório atual'
)
ls_parser.set_defaults(command='ls')


if __name__ == '__main__':
    args = parser.parse_args()
    if args.command == 'ls':
        print(os.listdir())

To use this script would be something like

$ python3 foo.py ls
['foo.txt']
    
01.08.2016 / 23:01
3

To run an external command, use the subprocess module:

import subprocess

subprocess.call(["ls", "-l"])

Or using the os.system() method:

import os

os.system("ls -l")

Editing : Use sys.platform: to check the operating system and execute the commands according to the system:

import sys, subprocess

def main():
    if sys.platform == "linux":
        subprocess.call(["ls", "-l"])
    elif sys.platform == "darwin":
        subprocess.call("ls")
    elif sys.platform == "win32":
        subprocess.call("dir")

if __name__ == "__main__":
    main()
    
01.08.2016 / 22:13