Start a command line tool in Python

Posted on

Question :

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?


Answer :

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
>>> os.path.isfile(files[0])
>>> 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'

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

To use this script would be something like

$ python3 ls


To run an external command, use the subprocess module:

import subprocess["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":["ls", "-l"])
    elif sys.platform == "darwin":"ls")
    elif sys.platform == "win32":"dir")

if __name__ == "__main__":


Leave a Reply

Your email address will not be published. Required fields are marked *