6

I have some packages inside a folder (named Packs) that is in the same file level of some executed package.

executedPack.m
Packs/subPack01.m
Packs/subPack02.m
Packs/subPack03.m

Today I use this structure do load the sub packages inside the executedPack.m:

(*Execution without Front-End*) 
Needs["MyPack`",FileNameJoin[{DirectoryName@$InputFileName,"Packs","subPack01.m"}]]

(*Execution with Front-End*)    
Needs["MyPack`",FileNameJoin[{NotebookDirectory[],"Packs","subPack01.m"}]]

The first I use when running the package without front-end, and the last when I evaluate in the front-end.

There is some simpler way to do that, more symmetric? I read some kernel folder structure, but I didn't find more details on that.

Update

Now what I want, but better. This works both in Fron-End and no Front-End execution.

Quiet[Check[SetDirectory@DirectoryName@$InputFileName,SetDirectory@NotebookDirectory[]],SetDirectory::fstr];
Needs["Packs`subPack01`"];
Murta
  • 26,275
  • 6
  • 76
  • 166

2 Answers2

5

You you could use the following code in place of your example above.

Needs["MyPack`", FileNameJoin[{
   If[$InputFileName == "", NotebookDirectory[], $InputFileName]
   , "Packs", "subPack01.m"}]]

Or you could use Module like the following.

Module[{$InputFileName = 
       If[$InputFileName == "", NotebookDirectory[], $InputFileName]},
     Print[$InputFileName];
 ]
William
  • 7,595
  • 2
  • 22
  • 70
0

After some google and forum search, I get this:

Quiet@SetDirectory@NotebookDirectory[];
Needs["Packs`subPack01`"];

To avoid alert msg, subPack01 is declared inside it as:

BeginPackage["Packs`subPack01`"]

this is a nice article, tks @DavidPark for the reference

Murta
  • 26,275
  • 6
  • 76
  • 166