platform_methods.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. def run_in_subprocess(builder_function):
  9. @functools.wraps(builder_function)
  10. def wrapper(target, source, env):
  11. # Convert SCons Node instances to absolute paths
  12. target = [node.srcnode().abspath for node in target]
  13. source = [node.srcnode().abspath for node in source]
  14. # Short circuit on non-Windows platforms
  15. if os.name != 'nt':
  16. return builder_function(target, source, None)
  17. # Identify module
  18. module_name = builder_function.__module__
  19. function_name = builder_function.__name__
  20. module_path = sys.modules[module_name].__file__
  21. if module_path.endswith('.pyc') or module_path.endswith('.pyo'):
  22. module_path = module_path[:-1]
  23. # Subprocess environment
  24. subprocess_env = os.environ.copy()
  25. subprocess_env['PYTHONPATH'] = os.pathsep.join([os.getcwd()] + sys.path)
  26. # Save parameters
  27. args = (target, source, None)
  28. data = dict(fn=function_name, args=args)
  29. json_path = os.path.join(os.environ['TMP'], uuid.uuid4().hex + '.json')
  30. with open(json_path, 'wt') as json_file:
  31. json.dump(data, json_file, indent=2)
  32. try:
  33. print('Executing builder function in subprocess: module_path=%r; data=%r' % (module_path, data))
  34. exit_code = subprocess.call([sys.executable, module_path, json_path], env=subprocess_env)
  35. finally:
  36. try:
  37. os.remove(json_path)
  38. except (OSError, IOError) as e:
  39. # Do not fail the entire build if it cannot delete a temporary file
  40. print('WARNING: Could not delete temporary file: path=%r; [%s] %s' %
  41. (json_path, e.__class__.__name__, e))
  42. # Must succeed
  43. if exit_code:
  44. raise RuntimeError(
  45. 'Failed to run builder function in subprocess: module_path=%r; data=%r' % (module_path, data))
  46. return wrapper
  47. def subprocess_main(namespace):
  48. with open(sys.argv[1]) as json_file:
  49. data = json.load(json_file)
  50. fn = namespace[data['fn']]
  51. fn(*data['args'])