__main__.py 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. from __future__ import annotations
  2. import errno
  3. import logging
  4. import os
  5. import sys
  6. from timeit import default_timer
  7. from typing import TYPE_CHECKING
  8. if TYPE_CHECKING:
  9. from collections.abc import MutableMapping
  10. from virtualenv.config.cli.parser import VirtualEnvOptions
  11. from virtualenv.run.session import Session
  12. LOGGER = logging.getLogger(__name__)
  13. def run(
  14. args: list[str] | None = None, options: VirtualEnvOptions | None = None, env: MutableMapping[str, str] | None = None
  15. ) -> None:
  16. env = os.environ if env is None else env
  17. start = default_timer()
  18. from virtualenv.run import cli_run # noqa: PLC0415
  19. from virtualenv.util.error import ProcessCallFailedError # noqa: PLC0415
  20. if args is None:
  21. args = sys.argv[1:]
  22. try:
  23. session = cli_run(args, options, env=env)
  24. LOGGER.warning(LogSession(session, start))
  25. except ProcessCallFailedError as exception:
  26. print(f"subprocess call failed for {exception.cmd} with code {exception.code}") # noqa: T201
  27. print(exception.out, file=sys.stdout, end="") # noqa: T201
  28. print(exception.err, file=sys.stderr, end="") # noqa: T201
  29. raise SystemExit(exception.code) # noqa: B904
  30. except OSError as exception:
  31. if exception.errno == errno.EMFILE:
  32. print( # noqa: T201
  33. "OSError: [Errno 24] Too many open files. You may need to increase your OS open files limit.\n"
  34. " On macOS/Linux, try 'ulimit -n 2048'.\n"
  35. " For Windows, this is not a common issue, but you can try to close some applications.",
  36. file=sys.stderr,
  37. )
  38. raise
  39. class LogSession:
  40. def __init__(self, session: Session, start: float) -> None:
  41. self.session = session
  42. self.start = start
  43. def __str__(self) -> str:
  44. spec = self.session.creator.interpreter.spec
  45. elapsed = (default_timer() - self.start) * 1000
  46. lines = [
  47. f"created virtual environment {spec} in {elapsed:.0f}ms",
  48. f" creator {self.session.creator!s}",
  49. ]
  50. if self.session.seeder.enabled:
  51. lines.append(f" seeder {self.session.seeder!s}")
  52. path = self.session.creator.purelib.iterdir()
  53. packages = sorted("==".join(i.stem.split("-")) for i in path if i.suffix == ".dist-info")
  54. lines.append(f" added seed packages: {', '.join(packages)}")
  55. if self.session.activators:
  56. lines.append(f" activators {','.join(i.__class__.__name__ for i in self.session.activators)}")
  57. return "\n".join(lines)
  58. def run_with_catch(args: list[str] | None = None, env: MutableMapping[str, str] | None = None) -> None:
  59. from virtualenv.config.cli.parser import VirtualEnvOptions # noqa: PLC0415
  60. env = os.environ if env is None else env
  61. options = VirtualEnvOptions()
  62. try:
  63. run(args, options, env)
  64. except (KeyboardInterrupt, SystemExit, Exception) as exception: # noqa: BLE001
  65. try:
  66. if getattr(options, "with_traceback", False):
  67. raise
  68. if not (isinstance(exception, SystemExit) and exception.code == 0):
  69. LOGGER.error("%s: %s", type(exception).__name__, exception) # noqa: TRY400
  70. code = exception.code if isinstance(exception, SystemExit) else 1
  71. sys.exit(code)
  72. finally:
  73. for handler in LOGGER.handlers: # force flush of log messages before the trace is printed
  74. handler.flush()
  75. if __name__ == "__main__": # pragma: no cov
  76. run_with_catch() # pragma: no cov