11module matplotlibd.pyplot ;
22
3- import std.stdio : popen, fprintf, fclose;
4- import std.format : format;
5-
63private :
74
85string py_path = " python" ;
@@ -57,15 +54,15 @@ immutable string py_methods = (){
5754 foreach (name; method_names) {
5855 py_methods ~=
5956 " void " ~ name ~ " (T...)(T a)" ~
60- " {string p;if(a.length>0){foreach(i;a){p~=parseArgs(i);}" ~
57+ " {import std.format: format;" ~
58+ " string p;if(a.length>0){foreach(i;a){p~=parseArgs(i);}" ~
6159 " p = p[0..$-1];}send(format(\" plt." ~ name ~ " (%s)\n\" ,p));" ;
6260
6361 if (name == " show" || name == " savefig" )
6462 py_methods ~= " eval();}\n " ;
6563 else
66- py_methods ~= " }\n " ;
64+ py_methods ~= " }\n " ;
6765 }
68-
6966 return py_methods;
7067}();
7168
@@ -74,16 +71,29 @@ template GenPyMethods() {
7471}
7572
7673void eval () {
77- auto p = popen(py_path, " w" );
78- p.fprintf(" %s" , cast (char * )py_script);
79- p.fclose();
74+ import std.process : pipeProcess, wait, Redirect;
75+ auto pipes = pipeProcess(py_path, Redirect.stdin | Redirect.stderr);
76+
77+ pipes.stdin.writeln(py_script);
78+ pipes.stdin.writeln(" exit()" );
79+ pipes.stdin.close();
80+
81+ wait(pipes.pid);
82+
83+ string error;
84+ foreach (line; pipes.stderr.byLine)
85+ error ~= line ~ " \n " ;
86+
87+ if (error)
88+ throw new Exception (" \n\n ERROR occurred in Python:\n " ~ error);
8089}
8190
8291void send (string line) {
8392 py_script ~= line;
8493}
8594
8695string d2py (T)(T v) {
96+ import std.format : format;
8797 static if (is (typeof (v) : PyNone))
8898 return " None" ;
8999
@@ -98,15 +108,13 @@ string d2py(T)(T v) {
98108}
99109
100110string parseArgs (Args)(Args args) {
101-
102111 static if (is (typeof (args.keys ) : string [])) {
103112 string parsed;
104113 foreach (key; args.byKey )
105114 parsed ~= key ~ " =" ~ d2py(args[key]) ~ " ," ;
106115 }
107116 else
108117 string parsed = d2py(args) ~ " ," ;
109-
110118 return parsed;
111119}
112120
0 commit comments