1
$\begingroup$

On Unix, I can run Python scripts from the command line like this1:

PYTHONPATH=lib/python path/to/script.py

The setting of PYTHONPATH affects the run-time value of the sys.path variable, which is Python's equivalent of Mathematica's $Path variable.

For example:

% PYTHONPATH=/foo:/bar:/baz python -c 'import sys; print sys.path[1:4]'
['/foo', '/bar', '/baz']

Is there a similar way to modify the value of the $Path variable from the command line when invoking WolframScripts?


1 Of course, I can omit the PYTHONPATH=lib/python "prefix" by first running export PYTHONPATH=/absolute/path/to/lib/python. The form with the "prefix", however, gives me the flexibility to tailor the library path to the script, something I often find useful.

$\endgroup$
3
  • 3
    $\begingroup$ How about mathkernel -run '$Path=...' ? $\endgroup$
    – ilian
    Commented Dec 15, 2016 at 17:23
  • $\begingroup$ There are two environment variables that can be used for this, MATHEMATICA_BASE and MATHEMATICA_USERBASE. With them I think you should be able to achieve what you want, although they are not exactly the same thing as PYTHONPATH. Both are documented here $\endgroup$ Commented Dec 15, 2016 at 19:10
  • $\begingroup$ @AlbertRetey: Thanks for the pointer. After experimenting a bit with MATHEMATICA_BASE and MATHEMATICA_USERBASE, however, I concluded that Mathematica interprets them sufficiently differently from what I have in mind that decided to go with a different solution. (I've posted this solution as an answer, below.) $\endgroup$
    – kjo
    Commented Dec 15, 2016 at 22:10

1 Answer 1

0
$\begingroup$

OK, I cobbled together this hack, inspired by Ilian's comment. Below is the content of a wrapper script, which I called wolframscript, and put in my $PATH:

#!/bin/bash

components='"'"${MATHEMATICAPATH//:/'", "'}"'"'
setpath=$( printf '$Path = DeleteDuplicates @ Join[{%s}, $Path];' "$components" )
interpreter=$( which WolframScript )

exec $interpreter -run "$setpath" -script "$@"

Now, for example, if /tmp/test.m is the following executable script

#!/usr/bin/env wolframscript

Write["stdout", ToString @ Column @ Take[$Path, 3]];

...I can run

% MATHEMATICAPATH='/yabba:/dabba:/doo' /tmp/test.m
/yabba
/dabba
/doo
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.