install.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import subprocess
  16. import sys
  17. import tempfile
  18. from packaging.requirements import Requirement
  19. from . import logging
  20. def install_packages_from_requirements_file(
  21. requirements_file_path, pip_install_opts=None
  22. ):
  23. from .deps import DEP_SPECS
  24. # TODO: Precompute or cache the constraints
  25. with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as f:
  26. for reqs in DEP_SPECS.values():
  27. for req in reqs:
  28. req = Requirement(req)
  29. if req.marker and not req.marker.evaluate():
  30. continue
  31. if req.url:
  32. req = f"{req.name}@{req.url}"
  33. else:
  34. req = f"{req.name}{req.specifier}"
  35. f.write(req + "\n")
  36. constraints_file_path = f.name
  37. args = [
  38. sys.executable,
  39. "-m",
  40. "pip",
  41. "install",
  42. "-c",
  43. constraints_file_path,
  44. *(pip_install_opts or []),
  45. "-r",
  46. requirements_file_path,
  47. ]
  48. logging.debug("Command: %s", args)
  49. try:
  50. return subprocess.check_call(args)
  51. finally:
  52. os.unlink(constraints_file_path)
  53. def install_packages(requirements, pip_install_opts=None):
  54. with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as f:
  55. for req in requirements:
  56. f.write(req + "\n")
  57. reqs_file_path = f.name
  58. try:
  59. return install_packages_from_requirements_file(
  60. reqs_file_path, pip_install_opts=pip_install_opts
  61. )
  62. finally:
  63. os.unlink(reqs_file_path)
  64. def uninstall_packages(packages, pip_uninstall_opts=None):
  65. args = [
  66. sys.executable,
  67. "-m",
  68. "pip",
  69. "uninstall",
  70. "-y",
  71. *(pip_uninstall_opts or []),
  72. *packages,
  73. ]
  74. logging.debug("Command: %s", args)
  75. return subprocess.check_call(args)