Skip to content

Commit 05e4dc9

Browse files
committed
redo is_binary in ExportString
1 parent fe3cbb1 commit 05e4dc9

1 file changed

Lines changed: 22 additions & 7 deletions

File tree

mathics/builtin/importexport.py

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2006,6 +2006,7 @@ def apply_elements(self, expr, elems, evaluation, **options):
20062006
evaluation,
20072007
)
20082008

2009+
is_binary = exporter_options["System`BinaryFormat"].is_true()
20092010
if function_channels is None:
20102011
evaluation.message("ExportString", "emptyfch")
20112012
evaluation.predetermined_out = current_predetermined_out
@@ -2025,25 +2026,36 @@ def apply_elements(self, expr, elems, evaluation, **options):
20252026
expr,
20262027
*list(chain(stream_options, custom_options))
20272028
)
2028-
if exporter_function.evaluate(evaluation) != Symbol("Null"):
2029+
exportres = exporter_function.evaluate(evaluation)
2030+
if exportres != Symbol("Null"):
20292031
evaluation.predetermined_out = current_predetermined_out
20302032
return SymbolFailed
20312033
else:
20322034
try:
2033-
tmpstream = open(filename.value, "rb")
2034-
res = tmpstream.read().decode("utf-8")
2035+
if is_binary:
2036+
tmpstream = open(filename.value, "rb")
2037+
else:
2038+
tmpstream = open(filename.value, "r")
2039+
res = tmpstream.read()
20352040
tmpstream.close()
20362041
except Exception as e:
20372042
print("something went wrong")
20382043
print(e)
20392044
evaluation.predetermined_out = current_predetermined_out
20402045
return SymbolFailed
2041-
res = String(str(res))
2046+
if is_binary:
2047+
res = Expression("ByteArray", ByteArrayAtom(res))
2048+
else:
2049+
res = String(str(res))
20422050
elif function_channels == Expression("List", String("Streams")):
2043-
from io import StringIO
2051+
from io import StringIO, BytesIO
20442052
from mathics.builtin.files import STREAMS, NSTREAMS
20452053

2046-
pystream = StringIO()
2054+
if is_binary:
2055+
pystream = BytesIO()
2056+
else:
2057+
pystream = StringIO()
2058+
20472059
n = next(NSTREAMS)
20482060
STREAMS.append(pystream)
20492061
stream = Expression("OutputStream", String("String"), Integer(n))
@@ -2055,7 +2067,10 @@ def apply_elements(self, expr, elems, evaluation, **options):
20552067
)
20562068
res = exporter_function.evaluate(evaluation)
20572069
if res == Symbol("Null"):
2058-
res = String(str(pystream.getvalue()))
2070+
if is_binary:
2071+
res = Expression("ByteArray", ByteArrayAtom(pystream.getvalue()))
2072+
else:
2073+
res = String(str(pystream.getvalue()))
20592074
else:
20602075
res = Symbol("$Failed")
20612076
Expression("Close", stream).evaluate(evaluation)

0 commit comments

Comments
 (0)