4

I'm running the Mathematica kernel math from inside a makefile to generate C++ code, like so:

a.out:
        g++ -o a.out main.cpp

main.cpp:
        math -run "<< \"generate_main.m\"" # generates main.cpp

However, sometimes there is no Mathematica license available on the machine where make is called (license has expired, connection to license server has been lost, ...). In such a case, the Mathematica kernel does not quit, but instead waits for the user to input a license password. So, make will never finish. In such a case, I'd like math to quit with a non-zero exit code. How can this be achieved?

Most convenient would be a command line option for the Mathematica kernel, like -quit-if-no-license. math -quit-if-no-license could then for example also be used in a configure script to check if the Mathematica kernel can be run.

  • Why just not simply call math with simple test calculation like: echo "2+2" | math -run | grep "4" ? – Acus Oct 13 '17 at 07:35
  • Your can always give it some limited time to complete. See for example https://unix.stackexchange.com/questions/23145/run-a-command-for-a-specified-time-and-then-abort-if-time-exceeds I think you cannot test if license is valid unless you run math (or of course unless you know how to check if generated license file is valid, which is equivalent to know how to crack math :-)) – Acus Oct 13 '17 at 07:46
  • 2
    what happens when you start math with the -script option and there is no license? (I seem to recall that in my experience it simply quits) You can then reset $BatchInput to move out of batch mode. – TimRias Oct 13 '17 at 07:50
  • Sorry, I have to correct myself: The proposal of @user18792 works very well, because stdin is closed after echo "2+2" has finished. If stdin is closed and the correct license password has not been entered, Mathematica returns with the exit code 1. This non-zero exit code can be checked for. – Alexander Voigt Oct 16 '17 at 17:55

1 Answers1

2

As far as I know there is no option -quit-if-no-valid-license-found, though probably one should exist. However, the Python module Pexcpect seems to just work (after a bit of tweaking delaybeforesend ). So install it by sudo yum install pexpect.noarch or 'sudo yum install pexpect.noarch' and then e.g. copy this to m.py :

import pexpect
child=pexpect.spawn('math')
child.delaybeforesend = .2
child.sendline('<<"myCode.m";')
child.sendline('')
child.sendline('')
child.sendline('')
child.sendline('')
child.sendline('')

and, for testing myCode.m :

Export["date.txt", DateString[] <> "\n", "Text"];

and running python m.py will not hang, even if you have no Mathematica license. Instead of newlines you could probably also use id.send(chr(3)).

Rolf Mertig
  • 17,172
  • 1
  • 45
  • 76