Skip to content

Commit 5014908

Browse files
author
Giacomo De Lazzari
committed
Replace os.system with subprocess.run
Besides being recommended by the Python documentation of `os.system()` itself (https://docs.python.org/3/library/os.html#os.system), the previous implementation with `os.system()` has the issue of not handling paths with spaces, since the arguments like `program_path` and `object_path` were concatenated as strings and then incorrectly parsed by GCC in the presence of whitespace. With `subprocess.run()`, we provide a list of arguments and the paths are handled correctly. A small commented piece of code has been introduced to build up an arguments list correctly.
1 parent 2c93f3a commit 5014908

File tree

1 file changed

+16
-15
lines changed

1 file changed

+16
-15
lines changed

simwave/kernel/backend/compiler.py

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import os
1+
import os, subprocess
22
from hashlib import sha1
33

44

@@ -200,25 +200,26 @@ def compile(self, dimension, density, float_precision, operator):
200200
if os.path.exists(object_path):
201201
print("Shared object already compiled in:", object_path)
202202
else:
203-
cmd = (
204-
self.cc
205-
+ " "
206-
+ program_path
207-
+ " "
208-
+ self.cflags
209-
+ " {}".format(float_precision)
210-
+ language_c
211-
+ " -o "
212-
+ object_path
213-
)
214-
215-
print("Compilation command:", cmd)
203+
# create arguments list for `subprocess.run`: pay attention to not providing
204+
# empty arguments, which the compiler will try to interpret as source filenames
205+
# and consequenty fail; moreover split the compilation flags string to separate
206+
# arguments to ensure proper parsing
207+
args = [self.cc, program_path]
208+
args += self.cflags.split(' ')
209+
if float_precision.strip() != '':
210+
args.append("{}".format(float_precision))
211+
if language_c.strip() != '':
212+
args.append(language_c)
213+
args += ["-o", object_path]
214+
215+
print("Compilation command:", ' '.join(args))
216216

217217
# create a dir to save the compiled shared object
218218
os.makedirs(object_dir, exist_ok=True)
219219

220220
# execute the command
221-
if os.system(cmd) != 0:
221+
result = subprocess.run(args)
222+
if result.returncode != 0:
222223
raise Exception("Compilation failed")
223224

224225
return object_path

0 commit comments

Comments
 (0)