Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

  File "C:\Users\sergu\PycharmProjects\pythonProject\StackTestSorter.py", line 13, in <module>
    cmd_parser.add_argument(
  File "C:\Users\sergu\AppData\Local\Programs\Python\Python311\Lib\argparse.py", line 1461, in add_argument
    return self._add_action(action)
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\sergu\AppData\Local\Programs\Python\Python311\Lib\argparse.py", line 1843, in _add_action
    self._optionals._add_action(action)
  File "C:\Users\sergu\AppData\Local\Programs\Python\Python311\Lib\argparse.py", line 1663, in _add_action
    action = super(_ArgumentGroup, self)._add_action(action)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\sergu\AppData\Local\Programs\Python\Python311\Lib\argparse.py", line 1475, in _add_action
    self._check_conflict(action)
  File "C:\Users\sergu\AppData\Local\Programs\Python\Python311\Lib\argparse.py", line 1612, in _check_conflict
    conflict_handler(action, confl_optionals)
  File "C:\Users\sergu\AppData\Local\Programs\Python\Python311\Lib\argparse.py", line 1621, in _handle_conflict_error
    raise ArgumentError(action, message % conflict_string)
argparse.ArgumentError: argument -h/--help: conflicting option strings: -h, --help```

>Solution :

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='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

have:

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_parser.add_argument(
    "directory",  # this will be a positional argument
    help="The path to a directory",
)

cmd_args = cmd_parser.parse_args()

path = cmd_args.directory
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading