install.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 req in DEP_SPECS:
  27. req = Requirement(req)
  28. if req.marker and not req.marker.evaluate():
  29. continue
  30. if req.url:
  31. req = f"{req.name}@{req.url}"
  32. else:
  33. req = f"{req.name}{req.specifier}"
  34. f.write(req + "\n")
  35. constraints_file_path = f.name
  36. args = [
  37. sys.executable,
  38. "-m",
  39. "pip",
  40. "install",
  41. "-c",
  42. constraints_file_path,
  43. *(pip_install_opts or []),
  44. "-r",
  45. requirements_file_path,
  46. ]
  47. logging.debug("Command: %s", args)
  48. try:
  49. return subprocess.check_call(args)
  50. finally:
  51. os.unlink(constraints_file_path)
  52. def install_packages(requirements, pip_install_opts=None):
  53. with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as f:
  54. for req in requirements:
  55. f.write(req + "\n")
  56. reqs_file_path = f.name
  57. try:
  58. return install_packages_from_requirements_file(
  59. reqs_file_path, pip_install_opts=pip_install_opts
  60. )
  61. finally:
  62. os.unlink(reqs_file_path)
  63. def uninstall_packages(packages, pip_uninstall_opts=None):
  64. args = [
  65. sys.executable,
  66. "-m",
  67. "pip",
  68. "uninstall",
  69. "-y",
  70. *(pip_uninstall_opts or []),
  71. *packages,
  72. ]
  73. logging.debug("Command: %s", args)
  74. return subprocess.check_call(args)