__main__.py 3.1 KB

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