How to make a system call and read the stdout, in

2019-06-18 12:47发布

问题:

I thought to try using D for some system administration scripts which require high performance (for comparing performance with python/perl etc).

I can't find an example in the tutorials I looked through so far (dsource.org etc.) on how to make a system call (i.e. calling another software) and receiving it's output from stdout, though?

If I missed it, could someone point me to the right docs/tutorial, or provide with the answer right away?

回答1:

Well, then I of course found it: http://www.digitalmars.com/d/2.0/phobos/std_process.html#shell (Version using the Tango library here: http://www.dsource.org/projects/tango/wiki/TutExec).

The former version is the one that works with D 2.0 (thereby the current dmd compiler that comes with ubuntu).

I got this tiny example to work now, compiled with dmd:

import std.stdio;
import std.process;

void main() {
  string output = shell("ls -l");
  write(output);
}


回答2:

std.process has been updated since... the new function is spawnShell

import std.stdio;
import std.process;

void main(){
    auto pid = spawnShell("ls -l");
    write(pid);
}