Import relative python file

User avatar
bryanfordney
Fusioneer
Posts: 99
Joined: Tue Jan 29, 2019 1:10 pm
Location: Atlanta, GA
Been thanked: 5 times

Import relative python file

#1

Post by bryanfordney » Thu Jul 11, 2019 10:49 am

Is there a way to import other python files into a python script?

My method for this when the relative imports don't work is usually to manually add the current directory of the current file to the PATH:
  1. import sys
  2. this_path = os.path.realpath(os.path.dirname(__file__))
  3. if not this_path in sys.path:
  4.     sys.path.append(this_path)
But, in Fusion ,`__file__` doesn't exist.

User avatar
Movalex
Sir Requestalot
Posts: 154
Joined: Fri Nov 03, 2017 5:36 am
Answers: 2
Been thanked: 44 times
Contact:

Re: Import relative python file

#2

Post by Movalex » Fri Jul 12, 2019 3:23 pm

your module path will not preserve in sys.path, so you have to append it on each script run.
Try this:
  1. import sys
  2. import os
  3.  
  4. sys.path.append(os.path.expanduser("~/Downloads/import_file/pymodules"))
  5.  
  6. try:
  7.     from fu9import import remote_task as rts
  8. except ImportError:
  9.     print('no module imported')
  10.  
  11. test = rts(os.path.expanduser("~/Downloads/import_file/test1.comp"))
  12. if test:
  13.     print("\nLoaded comp: {}".format(test.GetAttrs()["COMPS_FileName"]))
  1. import sys
  2. from pathlib import Path
  3.  
  4.  
  5. def remote_task(comp_path):
  6.     comp_path = Path(comp_path)
  7.     if not comp_path.is_file() or comp_path.suffix != ".comp":
  8.         print("wrong comp path")
  9.         return None
  10.     fu = bmd.scriptapp("Fusion")
  11.     current_comp = fu.GetCurrentComp()
  12.     if not current_comp.ActiveTool:
  13.         tool = current_comp.Blur
  14.         print("created {}".format(tool.Name))
  15.     temp_comp = fu.LoadComp(str(comp_path))
  16.     return temp_comp
You do not have the required permissions to view the files attached to this post.

User avatar
bryanfordney
Fusioneer
Posts: 99
Joined: Tue Jan 29, 2019 1:10 pm
Location: Atlanta, GA
Been thanked: 5 times

Re: Import relative python file

#3

Post by bryanfordney » Wed Jul 17, 2019 1:41 pm

This works for my purposes (had to reorganize all my reusable code into modules):
  1. LIB_PATH = comp.MapPath("UserData:/Scripts/Lib")
  2. if LIB_PATH not in sys.path:
  3.     sys.path.append(LIB_PATH)