5
$\begingroup$

I am trying to create an import script, I just need to get the filepath as a string to execute the rest of my functions. How can I do that?

Below is the visual example of what I want to get. enter image description here enter image description here

$\endgroup$

2 Answers 2

12
$\begingroup$

This general implementation for file based actions is to use in-built mix-in classes, bpy.types.Operator, bpy_extras.io_utils.ImportHelper. ImportHelper & ExportHelper are wrappers for FileSelector.

import bpy
from bpy_extras.io_utils import ImportHelper, ExportHelper

class NifImportOperator(bpy.types.Operator, ImportHelper):
    """Operator for loading a nif file."""

    #: Name of function for calling the nif export operator.
    bl_idname = "import_scene.nif"

    #: How the nif import operator is labelled in the user interface.
    bl_label = "Import NIF"

    def execute(self, context):
        path = "Importing " + self.properties.filepath
        self.report({'INFO'}, path)
        return{'FINISHED'}

Once your class is registered(see below)), it can be invoked via console.

bpy.ops.<bl_idname>('INVOKE_DEFAULT') 

bpy.ops.import_scene.nif('INVOKE_DEFAULT')

The addition of the ImportHelper/ExportHelper, a new attribute is defined in the self.properties of the operator (filepath).

In the above, because we did not set that attribute, you will get the FileSelector. The filepath attribute will be set to the value of the url bar. Alternative method of invocation via search bar or menu, will produce the same default invocation.

ImportHelper also allows you to pass in an explicit argument "filepath" into the operator.

bpy.ops.<bl_idname>(filepath="") 

bpy.ops.import_scene.nif(filepath="C:\\mypath")

This will skip, the FileSelector. In either scenario, the execute() method defined in your class is then called. The filepath is now accessible via self.properties.filepath

With this now accessible, you can do whatever you want with it, my sample below just reports it to the info bar.

infobar

Full Sample

import bpy
from bpy_extras.io_utils import ImportHelper, ExportHelper

class NifImportOperator(bpy.types.Operator, ImportHelper):
    """Operator for loading a nif file."""

    #: Name of function for calling the nif export operator.
    bl_idname = "import_scene.nif"

    #: How the nif import operator is labelled in the user interface.
    bl_label = "Import NIF"

    def execute(self, context):
        path = "Importing " + self.properties.filepath
        self.report({'INFO'}, path)
        return{'FINISHED'}

def menu_func_import(self, context):
    self.layout.operator(
        NifImportOperator.bl_idname, text="NetImmerse/Gamebryo (.nif)")

def register():
    bpy.utils.register_module(__name__)
    bpy.types.INFO_MT_file_import.append(menu_func_import)

def unregister():
    bpy.utils.unregister_module(__name__)
    bpy.types.INFO_MT_file_import.remove(menu_func_import)

if __name__ == "__main__":
    register()
$\endgroup$
1
  • $\begingroup$ @stacker - Good catch, didn't notice the error as I had the real plugin enabled. The code was copied somewhat ad-verbitim. Our plugins separates out operators from where the guis are init'd __init__, this is normally passed through via self.operators, but it won't exist. Updated with the correct code, verified menu works. $\endgroup$
    – neomonkeus
    Commented Aug 1, 2014 at 9:28
2
$\begingroup$

This opens a file browser and prints the filepath to console.

Without the ImportHelper

import bpy

class OpenBrowser(bpy.types.Operator):
    bl_idname = "open.browser"
    bl_label = "Minimum code to open browser & get filepath"

    def execute(self, context):
        print("filepath=", self.filepath)
        return {'FINISHED'}

    def invoke(self, context, event): # See comments at end  [1]        
        context.window_manager.fileselect_add(self)  
        #Open browser, take reference to 'self' read the path to selected 
        #file, put path in predetermined data structure self.filepath
        return {'RUNNING_MODAL'}  
        # Tells Blender to hang on for the slow user input

In the register function at the end of your file

def register():
    # Tell Blender this exists and should be registered
    bpy.utils.register_class(OpenBrowser) 

It also needs to be unregistered

def unregister():
    bpy.utils.unregister_class(OpenBrowser) 

In this Operator the invoke function is called as soon as you trigger bpy.ops.open.browser. Usually from a UI layout, like:

# inside your draw function of a menu, or panel.
row.operator('open.browser', text='', icon='FILE')

The execute function is where you can process the self.filepath further.

$\endgroup$
1
  • 1
    $\begingroup$ import helper is needed if not self.filepath gives an attribute error $\endgroup$ Commented Jul 28, 2020 at 0:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .