Guest User

Untitled

a guest
Apr 20th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. """a tutorial example of A CLI module using argparse to find all files in a directory tree
  2. """
  3.  
  4. from argparse import ArgumentParser
  5. from sys import argv, stderr, stdout
  6. from os import _exit, scandir
  7. from os.path import exists
  8.  
  9. __VERSION__ = "1.0.0"
  10.  
  11.  
  12. def find_all_the_files(path):
  13. """a recursive function to take a path on a disk and find all the files in a complicated directory tree
  14.  
  15. :param str path: a directory path that is on disk
  16.  
  17. :rtype generator
  18. """
  19. # call a for to iterate through the output of scandir
  20. # this does a flat ls of the directory contents whether
  21. # each content is a file or a directory or a symbolic link
  22. for n_item in scandir(path):
  23. # have to check if the item in hand is a directory
  24. if n_item.is_dir():
  25. # if it is a directory have to call the function
  26. # with the path of the new item
  27. yield from find_all_the_files(n_item.path)
  28. # check if the item is a regular file
  29. elif n_item.is_file():
  30. # if it is a regular file add this to the generator
  31. yield n_item.path
  32. else:
  33. # if the item is neither a directory nor a file then
  34. # something is wierd about this directory
  35. # and you need to know so that you can deal with it
  36. stderr.write("{} cannot be recognized.\n".format(n_item.path))
  37.  
  38.  
  39. def main():
  40. """a main method for the module. takes parameters passed
  41.  
  42. :rtype int
  43. """
  44. arguments = ArgumentParser(description="A tool to find all regular files in a complex directory tree",
  45. epilog="Copyright verbalhanglider, version " + __VERSION__)
  46. arguments.add_argument("a_directory", action="store",
  47. type=str, help="An absolute directory path")
  48. parsed_args = arguments.parse_args()
  49. try:
  50. if exists(parsed_args.a_directory):
  51. a_generator = find_all_the_files(parsed_args.a_directory)
  52. for a_file in a_generator:
  53. stdout.write("{}\n".format(a_file))
  54. else:
  55. stderr.write("{} does not exist on this machine!")
  56. # if this completes return proper code to terminal to indicate that program
  57. # completed everything it needed to complete
  58. return 0
  59. except KeyboardInterrupt:
  60. # if user hits Ctrl-C return proper code to terminal to interrupt
  61. return 131
  62.  
  63.  
  64. if __name__ == "__main__":
  65. _exit(main())
Add Comment
Please, Sign In to add comment