I have a package that I have placed in the $BaseDirectory\Applications
directory so that Needs
can find it. I have a logo in the directory that I will return when a function is called. However, when I call NotebookDirectory
in the package I get the directory of the notebook (this seems like expected behavior). I've not been able to find a corresponding PackageDirectory function.
How do I get the directory of a package so I can load a resource (in this case a .jpg logo) to return to the calling notebook?
Update to show package and $InputFileName
returns empty string
Update to show proper use of $InputFileName
in package
The package saved as an .m file in $BaseDirectory
\Applications is:
BeginPackage["MyTest`"];
packageDirectory::usage="Gets the directory of the this package.";
packageLogo::usage="Gets the logo of this package.";
testfoo::usage="does this work"
Begin["`Private`"];
(* $Input only has a value as the package is being loaded so capture that
value with `Set` in order to use it with `SetDelayed` later. *)
thisIsThePackageDirectory=$InputFileName//DirectoryName;
packageDirectory[]:=thisIsThePackageDirectory
packageLogo[]:=Import[FileNameJoin[{thisIsThePackageDirectory,"logo.jpg"}],"JPEG"]
testfoo[]:="some text"
End[];
EndPackage[];
The logo.jpg file is in the same directory as the .m package.
The notebook commands are as follows.
Needs["MyTest`"]
Names["MyTest`*"]
(* {"packageDirectory", "packageLogo", "testfoo"} *)
packageLogo[]
(* Logo image returned *)
packageDirectory[] // InputForm
(* "C:\\ProgramData\\Mathematica\\Applications\\MyTest.m" *)
testfoo[]
(* some text *)
Many thanks to @Szabolcs and @Ymareth.