mkdir.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env python
  2. """
  3. Pydir is mkdir for Python modules.
  4. Example:
  5. $ pydir -v myproject/module/etc
  6. Created directory myproject/module/etc
  7. Created file myproject/__init__.py
  8. Created file myproject/module/__init__.py
  9. Created file myproject/module/etc/__init__.py
  10. """
  11. from optparse import OptionParser, make_option
  12. import os
  13. import os.path
  14. import sys
  15. VERSION = (0, 2, 1)
  16. def version_string():
  17. return '.'.join(str(component) for component in VERSION)
  18. def main():
  19. usage = '%prog path [path2] [path3] [pathN]\n\n' + __doc__.strip()
  20. parser = OptionParser(usage=usage, option_list=(
  21. make_option('-v', '--verbose', default=False, action='store_true'),
  22. ))
  23. options, args = parser.parse_args()
  24. if len(args) == 0:
  25. parser.error('No paths given.')
  26. output = sys.stdout if options.verbose else None
  27. for index, path in enumerate(args):
  28. path = path.replace('.', os.path.sep)
  29. if output and index > 0:
  30. output.write('\n')
  31. try:
  32. pydir(path, output=output)
  33. except BaseException as exc:
  34. print ('Couldn\'t create %s: %s' % (path, exc,))
  35. def pydir(path, output=None):
  36. """
  37. Create a directory structure for a Python module, including __init__.py
  38. files. Converts existing directories into modules.
  39. """
  40. def info(line):
  41. if output:
  42. output.write(line)
  43. output.write('\n')
  44. try:
  45. os.makedirs(path)
  46. except (OSError, IOError) as exc:
  47. if not os.path.isdir(path):
  48. info('Path already exists: %s' % path)
  49. else:
  50. raise
  51. else:
  52. info('Created directory %s' % path)
  53. segments = path.split(os.path.sep)
  54. for i in xrange(len(segments)):
  55. init_filename = os.path.sep.join(segments[:i+1] + ['__init__.py'])
  56. if not os.path.isfile(init_filename):
  57. try:
  58. open(init_filename, 'w').close()
  59. except (OSError, IOError) as exc:
  60. raise
  61. else:
  62. info('Created file %s' % (init_filename,))
  63. else:
  64. info('File already exists: %s' % (init_filename,))
  65. if __name__ == '__main__':
  66. main()