python_virtualenv_script.jinja2 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. {#
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. -#}
  17. from __future__ import annotations
  18. import {{ pickling_library }}
  19. import sys
  20. {% if expect_airflow %}
  21. {# Check whether Airflow is available in the environment.
  22. # If it is, we'll want to ensure that we integrate any macros that are being provided
  23. # by plugins prior to unpickling the task context. #}
  24. if sys.version_info >= (3,6):
  25. try:
  26. from airflow.plugins_manager import integrate_macros_plugins
  27. integrate_macros_plugins()
  28. except ImportError:
  29. {# Airflow is not available in this environment, therefore we won't
  30. # be able to integrate any plugin macros. #}
  31. pass
  32. {% endif %}
  33. # Script
  34. {{ python_callable_source }}
  35. # monkey patching for the cases when python_callable is part of the dag module.
  36. {% if modified_dag_module_name is defined %}
  37. import types
  38. {{ modified_dag_module_name }} = types.ModuleType("{{ modified_dag_module_name }}")
  39. {{ modified_dag_module_name }}.{{ python_callable }} = {{ python_callable }}
  40. sys.modules["{{modified_dag_module_name}}"] = {{modified_dag_module_name}}
  41. {% endif%}
  42. {% if op_args or op_kwargs %}
  43. with open(sys.argv[1], "rb") as file:
  44. arg_dict = {{ pickling_library }}.load(file)
  45. {% else %}
  46. arg_dict = {"args": [], "kwargs": {}}
  47. {% endif %}
  48. {% if string_args_global | default(true) -%}
  49. # Read string args
  50. with open(sys.argv[3], "r") as file:
  51. virtualenv_string_args = list(map(lambda x: x.strip(), list(file)))
  52. {% endif %}
  53. try:
  54. res = {{ python_callable }}(*arg_dict["args"], **arg_dict["kwargs"])
  55. except Exception as e:
  56. with open(sys.argv[4], "w") as file:
  57. file.write(str(e))
  58. raise
  59. # Write output
  60. with open(sys.argv[2], "wb") as file:
  61. if res is not None:
  62. {{ pickling_library }}.dump(res, file)