Accepting a path as a command line argument instead of an input in python

Question:

I am tasked with creating an app using python to sort files in a given directory.

I want the input path to be passed as a command line argument using
cmd_parser.add_argument()
instead of being accepted as normal input after running the code.

The code does what it’s supposed to, but I don’t want the path to be received as an input.

Any help is greatly appreciated

import os
import shutil
from argparse import ArgumentParser


def main():
    cmd_parser = ArgumentParser(description="Application")
    cmd_parser.add_argument(
        '-v', '--version',
        action='version',
        version='Application v0.0.1',
        help='show version of the application'
    )
    cmd_parser.add_argument(
        '-h', '--help',
        action='help',
        help='Please enter a valid directory which contains the files to be sorted'
    )
    cmd_args = cmd_parser.parse_args()
    try:
        globals()[cmd_args.action](cmd_args.file)
    except Exception as ex:
        print('[ERROR]', str(ex))
        sys.exit(1)


while True:
    directory = input("Please input the directory including the files: ")
    if not os.path.isdir(directory):
        print("Please input a valid directory")
    else:
        break

path = directory
os.chdir(path)
new_folder = "Sorted Files"
os.makedirs(new_folder)
path_2 = path+"/"+new_folder
os.chdir(path_2)
new_folder_doc = "Documents"
new_folder_texts = "Texts"
new_folder_images = "Images"
new_folder_other = "Other"
os.makedirs(new_folder_doc)
os.makedirs(new_folder_texts)
os.makedirs(new_folder_images)
os.makedirs(new_folder_other)


for file in os.listdir(path):
    file_path = os.path.join(path, file)
    if os.path.isfile(file_path):
        file_name = os.path.basename(file_path)
    if file_path.endswith('.png') or file_path.endswith('.gif') or file_path.endswith('.bmp') or
            file_path.endswith('.jpg') or file_path.endswith('.jpeg') is True:
        shutil.move(file_path, new_folder_images)
        continue
    if file_path.endswith('.txt') or file_path.endswith('.ini') or file_path.endswith('.log') is True:
        shutil.move(file_path, new_folder_texts)
        continue
    if file_path.endswith('.pdf') or file_path.endswith('.docx') or file_path.endswith('.doc') or
            file_path.endswith('.xls') or file_path.endswith('.xlsx') or file_path.endswith('.csv') is True:
        shutil.move(file_path, new_folder_doc)
        continue
    if file_path.endswith('.docx') or file_path.endswith('.txt') or file_path.endswith('.bmp') or 
            file_path.endswith('.png') is not True:
        shutil.move(file_path, new_folder_other)
        continue

my_folder = path  # your path here
count = 0
for root, dirs, files in os.walk(my_folder):
    count += len([fn for fn in files if fn.endswith(".pdf") or fn.endswith(".docx")
                  or fn.endswith(".doc") or fn.endswith(".xls") or fn.endswith(".xlsx") or fn.endswith(".csv")
                  or fn.endswith(".jpeg") or fn.endswith(".jpg") or fn.endswith(".bmp") or fn.endswith(".gif")
                  or fn.endswith(".png") or fn.endswith(".txt") or fn.endswith(".ini") or fn.endswith(".log")])
print(f"Organized {count} files")

Error resulting from fixed code (It’s also not doing what it’s supposed to anymore)

usage: StackTestSorter.py [-h] [-v] directory
StackTestSorter.py: error: the following arguments are required: directory

Asked By: Juj

||

Answers:

Rather than having:

def main():
    cmd_parser = ArgumentParser(description="Application")
    cmd_parser.add_argument(
        '-v', '--version',
        action='version',
        version='Application v0.0.1',
        help='show version of the application'
    )
    cmd_parser.add_argument(
        '-h', '--help',
        action='help',
        help=''
    )
    cmd_args = cmd_parser.parse_args()
    try:
        globals()[cmd_args.action](cmd_args.file)
    except Exception as ex:
        print('[ERROR]', str(ex))
        sys.exit(1)


while True:
    directory = input("Please input the directory including the files: ")
    if not os.path.isdir(directory):
        print("Please input a valid directory")
    else:
        break

path = directory

have (removing the --help argument as this will be added automatically):

cmd_parser = ArgumentParser(description="Application")
cmd_parser.add_argument(
    '-v', '--version',
    action='version',
    version='Application v0.0.1',
    help='show version of the application'
)
cmd_parser.add_argument(
    "directory",  # this will be a positional argument
    help="a valid directory which contains the files to be sorted",
)

cmd_args = cmd_parser.parse_args()

path = cmd_args.directory
Answered By: Matt Pitkin

if I understood you correctly all you need to do is add one more argument, something like:

cmd_parser.add_argument("-p", "--path", help="", required=True, default=False)

and then after cmd_args you can do:

path = cmd_args.path
Answered By: enzo_ai