operator_file_import.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import bpy
  2. def read_some_data(context, filepath, use_some_setting):
  3. print("running read_some_data...")
  4. f = open(filepath, 'r', encoding='utf-8')
  5. data = f.read()
  6. f.close()
  7. # would normally load the data here
  8. print(data)
  9. return {'FINISHED'}
  10. # ImportHelper is a helper class, defines filename and
  11. # invoke() function which calls the file selector.
  12. from bpy_extras.io_utils import ImportHelper
  13. from bpy.props import StringProperty, BoolProperty, EnumProperty
  14. from bpy.types import Operator
  15. class ImportSomeData(Operator, ImportHelper):
  16. """This appears in the tooltip of the operator and in the generated docs"""
  17. bl_idname = "import_test.some_data" # important since its how bpy.ops.import_test.some_data is constructed
  18. bl_label = "Import Some Data"
  19. # ImportHelper mixin class uses this
  20. filename_ext = ".txt"
  21. filter_glob: StringProperty(
  22. default="*.txt",
  23. options={'HIDDEN'},
  24. maxlen=255, # Max internal buffer length, longer would be clamped.
  25. )
  26. # List of operator properties, the attributes will be assigned
  27. # to the class instance from the operator settings before calling.
  28. use_setting: BoolProperty(
  29. name="Example Boolean",
  30. description="Example Tooltip",
  31. default=True,
  32. )
  33. type: EnumProperty(
  34. name="Example Enum",
  35. description="Choose between two items",
  36. items=(
  37. ('OPT_A', "First Option", "Description one"),
  38. ('OPT_B', "Second Option", "Description two"),
  39. ),
  40. default='OPT_A',
  41. )
  42. def execute(self, context):
  43. return read_some_data(context, self.filepath, self.use_setting)
  44. # Only needed if you want to add into a dynamic menu
  45. def menu_func_import(self, context):
  46. self.layout.operator(ImportSomeData.bl_idname, text="Text Import Operator")
  47. def register():
  48. bpy.utils.register_class(ImportSomeData)
  49. bpy.types.TOPBAR_MT_file_import.append(menu_func_import)
  50. def unregister():
  51. bpy.utils.unregister_class(ImportSomeData)
  52. bpy.types.TOPBAR_MT_file_import.remove(menu_func_import)
  53. if __name__ == "__main__":
  54. register()
  55. # test call
  56. bpy.ops.import_test.some_data('INVOKE_DEFAULT')