Start a command line tool in Python

Asked

Viewed 591 times

3

How can I create a command line tool in Python that works like ls linux or dir windows?

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

  • Hello! You want to start a command line tool writing python by another python executable?

  • not at this point in time my idea is to make a tool to check if certain files exist in a desired directory for example: checar_se_existe -file lista.txt

  • recommend editing the question to make it clearer, the way it is, it seems that the question is how to use the ls from within python and not how to implement your own `ls``

2 answers

4


By comment what you are looking for are functions to simulate the behavior of ls or of dir correct? Therefore, I recommend you look at the command the listdir. to list the files of a directory, the module the path. to verify among the items of listdir what is a file (os.path.isfile) or where is a directory (os.path.isdir) and the function the.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 about argparse, a very simple 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']
  • If that’s what he really wants to do, os.listdir() resolve! + 1

  • 1

    was what I understood in the conversation within the comments of the question, including suggested editing the question to make it clearer

  • It was cool the code with argparse.

  • vlw @zekk argparse is pretty cool, although there are some libs to make it easier I think it’s simple enough.

3

To execute an external command use the module subprocess:

import subprocess

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

Or using the method os.system():

import os

os.system("ls -l")

Editing: Use sys.platform: to verify 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()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.