Commits

Marek Kubica  committed 396af8f

Added error handling and flushing stdout

  • Participants
  • Parent commits b558864

Comments (0)

Files changed (2)

 CHUNK_SIZE = 65535
 
 def run_code(instance, code):
+    """runs the code using low level libgs functions and checks whether that
+    worked"""
+    # set up prerequisites
     exit_code = c_int()
     codeseq = bytes(code, 'utf-8')
     chunk = codeseq
+
+    # initialize running strings
     libgs.gsapi_run_string_begin(instance, 0, pointer(exit_code))
+    # check whether that worked
+    if exit_code:
+        raise libgs.GhostScriptException("Execution failed at 'begin'")
+
+    # feed in chunks
     while codeseq:
         chunk = codeseq[:CHUNK_SIZE]
-        libgs.gsapi_run_string_continue(instance, chunk, len(chunk), 0, pointer(exit_code))
+        libgs.gsapi_run_string_continue(instance, chunk, len(chunk), 0,
+                pointer(exit_code))
+        # check for failures
+        if exit_code:
+            raise libgs.GhostScriptException("Execution failed at 'continue'")
         codeseq = codeseq[CHUNK_SIZE:]
+
+    # end reading string, execute
     libgs.gsapi_run_string_end(instance, 0, pointer(exit_code))
+    # and determine whether that succeeded
+    if exit_code:
+        raise libgs.GhostScriptException("Execution failed at 'end'")
 
 def main():
     code = "1 2 add == flush"
 
     @std_stream_handler
     def _stdout_handler(caller_handle, buf, length):
+        print("I got called")
         print(caller_handle, buf, length)
         return 0
 
 
     def raw(self, code):
         """Runs raw PostScript code on the current instance"""
-        gsu.run_code(self._instance, code)
+        # prepend space to avoid clashing with stuff that might already
+        # be on the stack
+        gsu.run_code(self._instance, " {}".format(code))
+        # always return self to make sure chainability works
         return self
 
     def __getattr__(self, name):
 
 def main():
     gsi = GhostScriptInterpreter()
-    gsi.number(1).number(2)
-    print(gsi)
-    gsi.add().pstack()
+    gsi.raw("1 2 add == flush")
+    gsi.number(1).number(2).add().raw('==').flush()
 
 if __name__ == '__main__':
     main()