See also std.process.
Simple example
(1) simple example
|
import std.stdio;
import std.process;
void main()
{
// v1
// auto ret = execute(["gcc", "--version"]);
// v2
auto ret = executeShell("gcc --version");
writeln("Exit code: ", ret.status);
writeln("Output and Error:");
writeln(ret.output);
}
|
Output:
Exit code: 0
Output and Error:
gcc (GCC) 15.1.1 20250425
Copyright (C) 2025 Free Software Foundation, Inc.
...
Notes:
execute()
waits for the process to complete before returning.
executeShell()
is similar to the previous. It runs the given command through the current user's command interpreter (shell).
- It captures what the child process prints to both its standard output and standard error streams, and return this together with its exit code. That is, stdout and stderr are returned together; they are not separated!
Show the output immediately
Say we have a program that produces its output slowly:
from time import sleep
def main():
for i in range(1, 5 + 1):
print(i, flush=True)
sleep(1)
It prints the numbers from 1 to 5 and waits one second after every number.
We want to call this program in an external process and we don't want to buffer its output. We want to see its output in real-time.
(2) os.system()
|
import os
def main():
os.system("./stream.py")
print("END")
|
import std.stdio;
import std.process;
void main()
{
// v1
// auto pid = spawnProcess(["./stream.py"]);
// v2
auto pid = spawnShell("./stream.py");
auto exitCode = wait(pid);
writeln("END");
writeln("Exit code: ", exitCode);
}
|
Output of the D program:
1
2
3
4
5
END
Exit code: 0
Notes:
spawnProcess()
returns immediately, leaving the child process to execute in parallel with its parent. It is recommended to always call wait()
on the returned pid.
spawnShell()
is similar to the previous. It runs the given command through the current user's command interpreter (shell).