Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hyrbid Modul and Program Behaviour for a D Source File

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?

like image 313
Nordlöw Avatar asked Dec 07 '22 05:12

Nordlöw


2 Answers

(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.

like image 98
user2744502 Avatar answered Dec 08 '22 20:12

user2744502


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.

like image 25
J. Miller Avatar answered Dec 08 '22 18:12

J. Miller