Skip to content

Commit b2842ba

Browse files
committed
avoid using file system in mpy_cross_compile()
Don't create a temporary directory for the input and output files. Instead, we can use "-" as the file name to pipe directly to stdin and stdout. This avoids issues with file system encoding and other odd filesystem-related problems.
1 parent b2d5144 commit b2842ba

File tree

1 file changed

+17
-30
lines changed

1 file changed

+17
-30
lines changed

src/mpy_cross_v6_3/__init__.py

Lines changed: 17 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from enum import Enum
22
import subprocess
33
import sys
4-
import tempfile
54
import pathlib
65
import platform
76
from typing import List, Optional, Tuple
@@ -75,44 +74,32 @@ def mpy_cross_compile(
7574
...
7675
7776
"""
78-
with tempfile.TemporaryDirectory() as tmp_dir_name:
79-
tmp_dir = pathlib.Path(tmp_dir_name)
77+
args: list[str] = [MPY_CROSS_PATH, "-", "-s", file_name]
8078

81-
with open(tmp_dir / "tmp.py", "w") as in_file:
82-
in_file.write(file_contents)
79+
if optimization_level is not None:
80+
if optimization_level not in range(4):
81+
raise ValueError("optimization_level must be between 0 and 3")
8382

84-
args: list[str] = [MPY_CROSS_PATH, in_file.name, "-s", file_name]
83+
args.append(f"-O{optimization_level}")
8584

86-
if optimization_level is not None:
87-
if optimization_level not in range(4):
88-
raise ValueError("optimization_level must be between 0 and 3")
85+
if small_number_bits is not None:
86+
args.append(f"-msmall-int-bits={small_number_bits}")
8987

90-
args.append(f"-O{optimization_level}")
88+
if arch is not None:
89+
args.append(f"-march={arch.value}")
9190

92-
if small_number_bits is not None:
93-
args.append(f"-msmall-int-bits={small_number_bits}")
91+
if emit is not None:
92+
args += ["-X", f"emit={emit.value}"]
9493

95-
if arch is not None:
96-
args.append(f"-march={arch.value}")
94+
if heap_size is not None:
95+
args += ["-X", f"heapsize={heap_size}"]
9796

98-
if emit is not None:
99-
args += ["-X", f"emit={emit.value}"]
97+
if extra_args:
98+
args += extra_args
10099

101-
if heap_size is not None:
102-
args += ["-X", f"heapsize={heap_size}"]
100+
process = subprocess.run(args, capture_output=True, input=file_contents.encode())
103101

104-
if extra_args:
105-
args += extra_args
106-
107-
process = subprocess.run(args, capture_output=True)
108-
109-
try:
110-
with open(tmp_dir / "tmp.mpy", "rb") as out_file:
111-
data = out_file.read()
112-
except OSError:
113-
data = None
114-
115-
return process, data
102+
return process, process.stdout if process.returncode == 0 else None
116103

117104

118105
def mpy_cross_version() -> str:

0 commit comments

Comments
 (0)