imgtool: Add write to file option

Signed-off-by: Dávid Házi <david.hazi@arm.com>
Signed-off-by: Bence Balogh <bence.balogh@arm.com>
Change-Id: I6028955be5cbcd20d49ef2126dce8d4636b824a6
diff --git a/scripts/imgtool/keys/general.py b/scripts/imgtool/keys/general.py
index 033a70f..0393a9a 100644
--- a/scripts/imgtool/keys/general.py
+++ b/scripts/imgtool/keys/general.py
@@ -8,7 +8,18 @@
 
 
 class KeyClass(object):
-    def _emit(self, header, trailer, encoded_bytes, indent, file=sys.stdout, len_format=None):
+    def _emit(self, header, trailer, encoded_bytes, indent, file=sys.stdout,
+              len_format=None):
+        if file and file is not sys.stdout:
+            with open(file, 'w') as file:
+                self._emit_to_output(header, trailer, encoded_bytes, indent,
+                                     file, len_format)
+        else:
+            self._emit_to_output(header, trailer, encoded_bytes, indent,
+                                 sys.stdout, len_format)
+
+    def _emit_to_output(self, header, trailer, encoded_bytes, indent, file,
+                        len_format):
         print(AUTOGEN_MESSAGE, file=file)
         print(header, end='', file=file)
         for count, b in enumerate(encoded_bytes):
@@ -39,7 +50,11 @@
                 file=file)
 
     def emit_public_pem(self, file=sys.stdout):
-        print(str(self.get_public_pem(), 'utf-8'), file=file, end='')
+        if file and file is not sys.stdout:
+            with open(file, 'w') as file:
+                print(str(self.get_public_pem(), 'utf-8'), file=file, end='')
+        else:
+            print(str(self.get_public_pem(), 'utf-8'), file=sys.stdout, end='')
 
     def emit_private(self, minimal, format, file=sys.stdout):
         self._emit(