10

Is there a way to get the script directory from inside a Mathematica script?

I want a function analogue to NotebookDirectory[] (which doesn't work for scripts). Is there a way to do this?

a06e
  • 11,327
  • 4
  • 48
  • 108

1 Answers1

8
DirectoryName @ $InputFileName

is the answer, right?

And this will work whether you call it from a package or a notebook interface:

parentPath = $InputFileName /. "" :> NotebookFileName[]
parentDir = DirectoryName @ parentPath

Check:

path = FileNameJoin[{$TemporaryDirectory, "test.m"}];

Export[
 path,
 "Print @ DirectoryName @ $InputFileName",
 "Text"
 ]

Get @ path

(...)\Local\Temp\

Kuba
  • 136,707
  • 13
  • 279
  • 740
  • sorry, but this doesn't work if you call your script (.m) from within the terminal using wolframscript – Santiago Aug 22 '17 at 13:31
  • @Santi could you elaborate, with a script.m file containing only: Print["test parent dir: ", DirectoryName @ $InputFileName] I get: https://i.stack.imgur.com/SrLrA.png – Kuba Aug 22 '17 at 13:41
  • hi @Kuba, ok, you are right, but in the way I was running my scripts it doesn't work. If I do: wolfram -script script.m it works. But if I do wolframscript -file script.m it doesn't work. I am on Mathematica 11.1.1 Kernel for Linux x86 (64-bit). – Santiago Aug 22 '17 at 14:29
  • do you have an idea why this doesn't work with wolframscript ? – Santiago Aug 23 '17 at 08:31
  • @Santi I didn't work with scripts yet so I don't know, I will try to investigate if I find time. You could ask a question on main about that. Just make sure to prepare simple example people can run. – Kuba Aug 23 '17 at 08:33
  • Is $InputFileName supposed to work in .mt test files? It looks like I'll have to hardcode my paths in my tests. – Gustavo Delfino Jun 21 '18 at 20:41