A Python source file has the nice property of being able to act both as module or as a standalone program (tool) using the pattern
if __name__ == "__main__":
Is it somehow possible to get the same behaviour for a D module source file?
(Unix only)
You can use a shebang line that sets a version
which enables a main
function:
#!/path/to/rdmd --shebang -version=run
version(run) void main() {}
Make your file executable (chmod +x foo.d
) and run it like a program (./foo.d
).
Be sure to use a unique version identifier (unlike I did here). Maybe include the fully qualified module name in some form, or use a UUID.
It depends on what you're trying to do. A D program requires exactly one main
function across all modules as the entry point, so there's not an implicit way as in Python. The D way is to create the executable as a separate module that contains a main
and imports the other module.
But if you just want to do it for testing purposes, you should put executable code in unittest
blocks (with no main
) and then you can run the file using rdmd -main -unittest scratch.d
, which adds a stub main
for you.
If you really want to make a dual-purpose module (which is not really The D Way), you could put the main
inside a unique version
block:
module scratch; // file scratch.d
import std.stdio;
void foo(){ writeln("FOO"); }
version(scratchExe) {
void main() {
foo();
}
}
Then compile the executable version with dmd scratch.d -version=scratchExe
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With