platform_methods.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import os
  2. import sys
  3. import json
  4. import uuid
  5. import functools
  6. import subprocess
  7. # NOTE: The multiprocessing module is not compatible with SCons due to conflict on cPickle
  8. JSON_SERIALIZABLE_TYPES = (bool, int, float, str)
  9. def run_in_subprocess(builder_function):
  10. @functools.wraps(builder_function)
  11. def wrapper(target, source, env):
  12. # Convert SCons Node instances to absolute paths
  13. target = [node.srcnode().abspath for node in target]
  14. source = [node.srcnode().abspath for node in source]
  15. # Short circuit on non-Windows platforms, no need to run in subprocess
  16. if sys.platform not in ("win32", "cygwin"):
  17. return builder_function(target, source, env)
  18. # Identify module
  19. module_name = builder_function.__module__
  20. function_name = builder_function.__name__
  21. module_path = sys.modules[module_name].__file__
  22. if module_path.endswith(".pyc") or module_path.endswith(".pyo"):
  23. module_path = module_path[:-1]
  24. # Subprocess environment
  25. subprocess_env = os.environ.copy()
  26. subprocess_env["PYTHONPATH"] = os.pathsep.join([os.getcwd()] + sys.path)
  27. # Keep only JSON serializable environment items
  28. filtered_env = dict((key, value) for key, value in env.items() if isinstance(value, JSON_SERIALIZABLE_TYPES))
  29. # Save parameters
  30. args = (target, source, filtered_env)
  31. data = dict(fn=function_name, args=args)
  32. json_path = os.path.join(os.environ["TMP"], uuid.uuid4().hex + ".json")
  33. with open(json_path, "wt") as json_file:
  34. json.dump(data, json_file, indent=2)
  35. json_file_size = os.stat(json_path).st_size
  36. print(
  37. "Executing builder function in subprocess: "
  38. "module_path=%r, parameter_file=%r, parameter_file_size=%r, target=%r, source=%r"
  39. % (module_path, json_path, json_file_size, target, source)
  40. )
  41. try:
  42. exit_code = subprocess.call([sys.executable, module_path, json_path], env=subprocess_env)
  43. finally:
  44. try:
  45. os.remove(json_path)
  46. except (OSError, IOError) as e:
  47. # Do not fail the entire build if it cannot delete a temporary file
  48. print(
  49. "WARNING: Could not delete temporary file: path=%r; [%s] %s" % (json_path, e.__class__.__name__, e)
  50. )
  51. # Must succeed
  52. if exit_code:
  53. raise RuntimeError(
  54. "Failed to run builder function in subprocess: module_path=%r; data=%r" % (module_path, data)
  55. )
  56. return wrapper
  57. def subprocess_main(namespace):
  58. with open(sys.argv[1]) as json_file:
  59. data = json.load(json_file)
  60. fn = namespace[data["fn"]]
  61. fn(*data["args"])