Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an interactive D process from Mathematica?

I'm trying to establish an interactive session with another process using Mathematicas' StartProcess. It is basically the same scenario as in this question, only that I'm calling a D program instead of a Fortran one.

Take for instance a minimal D program that reads from Standard Input and writes to Standard Output interactively (notice the infinite loop):

// D
void main(string[] argv) {
    while(true) {
        auto name = readln().chomp;
        writefln("Hello %s!", name);
    }
}

When I run this program from the command prompt, it behaves as expected. If I would want to run it from Mathematica, this is supposed to work:

(* Mathematica *)
dhello = StartProcess["dhello.exe"];
WriteLine[dhello, "Wulfrick"]; 
ReadLine[dhello]

but it doesn't. The call to ReadLine[] blocks, as if waiting for the Process to finish. I initially thought it may be a problem in Mathematica, but I tried calling a C# program instead and it worked! Take for instance:

// C#
static void Main(string[] args) {
    while (true) {
        var name = Console.ReadLine();
        Console.WriteLine($"Hello {name}!");
    }
}

Now on the Mathematica side, doing:

(* Mathematica *)
cshello = StartProcess["cshello.exe"];
WriteLine[cshello, "Wulfrick"]; 
ReadLine[cshello]

Works as expected, printing the output as soon as I call ReadLine[] and maintaining interactivity. So it looks like the problem is in the D side really. Also that's why I decided to post here and not on mathematica.stackexchange.

I would really like to make this work with the D program. Any input is much appreciated.

System:

  • Windows 10 x64
  • Mathematica 11.2
  • DMD v2.078.2
like image 635
WHermann Avatar asked Nov 15 '25 16:11

WHermann


1 Answers

Standard output may not have been flushed.

Try:

import std.stdio : stdout;
stdout.flush();

At the end of your while loop.

like image 162
Richard Andrew Cattermole Avatar answered Nov 18 '25 20:11

Richard Andrew Cattermole