Search code examples
d

How to pass data to console app and handle it's output?


I have got console app that get parameters to start and then output result of calculation.

Example (from docs):

gdaltransform -s_srs EPSG:28992 -t_srs EPSG:31370

177502 311865

In step-by step mode it's work like:

  1. gdaltransform -s_srs EPSG:28992 -t_srs EPSG:31370 [press enter]
  2. I input from keyboard: 177502 311865 [press enter]
  3. it's print on screen new coordinates: 244296.723070577 165937.350438393 1.60975147597492

I need to call it's from D, pass input parametrs, and handle it's output.

It's seems that I need use pipeShell for it, but I can't understand how to use it.

Here is my code:

import std.stdio;
import std.process;
import std.file;

void main()
{
    auto pipes = pipeProcess(["gdaltransform", " -s_srs epsg:4326 -t_srs EPSG:3857"], Redirect.stdout);
    scope(exit) wait(pipes.pid);
}

But how to read of gdaltransform output to variable and then terminate app?


Solution

  • import std.stdio;
    import std.process;
    
    void main() {
        // spawn child process by pipeProcess
        auto pipes = pipeProcess(["gdaltransform", "-s_srs", "EPSG:28992", "-t_srs", "EPSG:31370"], Redirect.all);
    
        // or by pipeShell
        //auto pipes = pipeShell("gdaltransform -s_srs EPSG:28992 -t_srs EPSG:31370", Redirect.all);
    
        scope(exit) {
            // send terminate signal to the child process
            kill(pipes.pid);
            // waiting for terminate
            wait(pipes.pid);
        }
    
        // write data to child's stdin
        pipes.stdin.writeln("177502, 311865");
    
        // close child's stdin
        pipes.stdin.close();
    
        // read data from child's stdout
        string line = pipes.stdout.readln();
    
        write("result: ", line);
    }