1. import argparse
  2. import os
  3. def parse_file_paths(file_paths):
  4. """
  5. Parses file paths from command line arguments for monitoring.
  6. Args:
  7. file_paths (list): A list of file paths provided as command-line arguments.
  8. Returns:
  9. dict: A dictionary where keys are file paths and values are dictionaries
  10. containing metadata (e.g., absolute path, file size).
  11. Returns an empty dictionary if no file paths are provided.
  12. """
  13. if not file_paths:
  14. return {} # Return empty dict if no file paths are given
  15. parsed_files = {}
  16. for file_path in file_paths:
  17. try:
  18. abs_path = os.path.abspath(file_path) # Get absolute path
  19. file_size = os.path.getsize(abs_path) # Get file size
  20. parsed_files[file_path] = {
  21. "absolute_path": abs_path,
  22. "file_size": file_size
  23. }
  24. except FileNotFoundError:
  25. print(f"Error: File not found: {file_path}") #Handle file not found
  26. parsed_files[file_path] = {
  27. "error": "File not found"
  28. }
  29. except OSError as e:
  30. print(f"Error accessing {file_path}: {e}") #Handle other OS errors
  31. parsed_files[file_path] = {
  32. "error": str(e)
  33. }
  34. return parsed_files
  35. if __name__ == "__main__":
  36. parser = argparse.ArgumentParser(description="Parse file paths for monitoring.")
  37. parser.add_argument("files", nargs="+", help="List of file paths to monitor.")
  38. args = parser.parse_args()
  39. parsed_data = parse_file_paths(args.files)
  40. #Example usage: Print parsed data
  41. for file_path, data in parsed_data.items():
  42. print(f"File: {file_path}")
  43. if "error" in data:
  44. print(f" Error: {data['error']}")
  45. else:
  46. print(f" Absolute Path: {data['absolute_path']}")
  47. print(f" File Size: {data['file_size']} bytes")
  48. print("-" * 20)

Add your comment