create_python_init_file.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/env python
  2. """
  3. Script for creating an __init__.py file for a package.
  4. Adds all modules (*.py files) in a directory into an __init__.py file.
  5. Overwrites existing __init__.py file in a directory.
  6. (C) 2011-2013 by the GRASS Development Team
  7. This program is free software under the GNU General Public License
  8. (>=v2). Read the file COPYING that comes with GRASS for details.
  9. @author Martin Landa <landa.martin gmail.com>
  10. @author Vaclav Petras <wenzeslaus gmail.com>
  11. """
  12. import os
  13. import sys
  14. import glob
  15. def main(path):
  16. if not os.path.exists(path) or not os.path.isdir(path):
  17. print >> sys.stderr, "'%s' is not a directory" % path
  18. return 1
  19. modules = []
  20. pattern = os.path.join(path, '*.py')
  21. for f in glob.glob(pattern):
  22. if f[-5:-3] == '__':
  23. continue
  24. modules.append(os.path.splitext(os.path.basename(f))[0])
  25. fd = open(os.path.join(path, '__init__.py'), 'w')
  26. try:
  27. fd.write('all = [%s' % os.linesep)
  28. for m in modules:
  29. fd.write(" '%s',%s" % (m, os.linesep))
  30. fd.write(' ]%s' % os.linesep)
  31. finally:
  32. fd.close()
  33. return 0
  34. if __name__ == "__main__":
  35. if len(sys.argv) < 2:
  36. sys.exit("usage: %s path/to/package/directory" % sys.argv[0])
  37. sys.exit(main(sys.argv[1]))