-
Notifications
You must be signed in to change notification settings - Fork 432
/
Copy pathmain.py
1192 lines (1047 loc) · 42.3 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# PYTHON_ARGCOMPLETE_OK
"""The command line interface to pipx"""
import argparse
import logging
import logging.config
import os
import re
import shlex
import sys
import textwrap
import time
import urllib.parse
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple
import argcomplete
import platformdirs
from packaging.utils import canonicalize_name
from pipx import commands, constants, paths
from pipx.animate import hide_cursor, show_cursor
from pipx.colors import bold, green
from pipx.commands.environment import ENVIRONMENT_VARIABLES
from pipx.constants import (
EXIT_CODE_OK,
EXIT_CODE_SPECIFIED_PYTHON_EXECUTABLE_NOT_FOUND,
MINIMUM_PYTHON_VERSION,
WINDOWS,
ExitCode,
)
from pipx.emojis import hazard
from pipx.interpreter import (
DEFAULT_PYTHON,
InterpreterResolutionError,
find_python_interpreter,
)
from pipx.util import PipxError, mkdir, pipx_wrap, rmdir
from pipx.venv import VenvContainer
from pipx.version import version as __version__
logger = logging.getLogger(__name__)
VenvCompleter = Callable[[str], List[str]]
def print_version() -> None:
print(__version__)
def prog_name() -> str:
try:
prog = os.path.basename(sys.argv[0])
if prog == "__main__.py":
return f"{sys.executable} -m pipx"
else:
return prog
except Exception:
pass
return "pipx"
SPEC_HELP = textwrap.dedent(
"""\
The package name or specific installation source passed to pip.
Runs `pip install -U SPEC`.
For example `--spec mypackage==2.0.0` or `--spec git+https://github.com/user/repo.git@branch`
"""
)
PIPX_DESCRIPTION = textwrap.dedent(
f"""
Install and execute apps from Python packages.
Binaries can either be installed globally into isolated Virtual Environments
or run directly in a temporary Virtual Environment.
Virtual Environment location is {paths.ctx.venvs!s}.
Symlinks to apps are placed in {paths.ctx.bin_dir!s}.
Symlinks to manual pages are placed in {paths.ctx.man_dir!s}.
"""
)
PIPX_DESCRIPTION += pipx_wrap(
"""
optional environment variables:
PIPX_HOME Overrides default pipx location. Virtual Environments will be installed to $PIPX_HOME/venvs.
PIPX_GLOBAL_HOME Used instead of PIPX_HOME when the `--global` option is given.
PIPX_BIN_DIR Overrides location of app installations. Apps are symlinked or copied here.
PIPX_GLOBAL_BIN_DIR Used instead of PIPX_BIN_DIR when the `--global` option is given.
PIPX_MAN_DIR Overrides location of manual pages installations. Manual pages are symlinked or copied here.
PIPX_GLOBAL_MAN_DIR Used instead of PIPX_MAN_DIR when the `--global` option is given.
PIPX_DEFAULT_PYTHON Overrides default python used for commands.
USE_EMOJI Overrides emoji behavior. Default value varies based on platform.
PIPX_HOME_ALLOW_SPACE Overrides default warning on spaces in the home path
""",
subsequent_indent=" " * 24, # match the indent of argparse options
keep_newlines=True,
)
DOC_DEFAULT_PYTHON = os.getenv("PIPX__DOC_DEFAULT_PYTHON", DEFAULT_PYTHON)
INSTALL_DESCRIPTION = textwrap.dedent(
f"""
The install command is the preferred way to globally install apps
from python packages on your system. It creates an isolated virtual
environment for the package, then ensures the package's apps are
accessible on your $PATH. The package's manual pages installed in
share/man/man[1-9] can be viewed with man on an operating system where
it is available and the path in the environment variable `PIPX_MAN_DIR`
(default: {paths.DEFAULT_PIPX_MAN_DIR}) is in the man search path
($MANPATH).
The result: apps you can run from anywhere, located in packages
you can cleanly upgrade or uninstall. Guaranteed to not have
dependency version conflicts or interfere with your OS's python
packages. 'sudo' is not required to do this.
pipx install PACKAGE_SPEC ...
pipx install --python PYTHON PACKAGE_SPEC
pipx install VCS_URL
pipx install ./LOCAL_PATH
pipx install ZIP_FILE
pipx install TAR_GZ_FILE
The PACKAGE_SPEC argument is passed directly to `pip install`.
Virtual Environments will be installed to `$PIPX_HOME/venvs`.
The default pipx home location is {paths.DEFAULT_PIPX_HOME} and can
be overridden by setting the environment variable `PIPX_HOME`.
If the `--global` option is used, the default pipx home location
instead is {paths.DEFAULT_PIPX_GLOBAL_HOME} and can be overridden
by setting the environment variable `PIPX_GLOBAL_HOME`.
The default app location is {paths.DEFAULT_PIPX_BIN_DIR} and can be
overridden by setting the environment variable `PIPX_BIN_DIR`.
If the `--global` option is used, the default app location instead
is {paths.DEFAULT_PIPX_GLOBAL_BIN_DIR} and can be overridden by
setting the environment variable `PIPX_GLOBAL_BIN_DIR`.
The default manual pages location is {paths.DEFAULT_PIPX_MAN_DIR} and
can be overridden by setting the environment variable `PIPX_MAN_DIR`.
If the `--global` option is used, the default manual pages location
instead is {paths.DEFAULT_PIPX_GLOBAL_MAN_DIR} and can be overridden
by setting the environment variable `PIPX_GLOBAL_MAN_DIR`.
The default python executable used to install a package is
{DOC_DEFAULT_PYTHON} and can be overridden
by setting the environment variable `PIPX_DEFAULT_PYTHON`.
"""
)
class LineWrapRawTextHelpFormatter(argparse.RawDescriptionHelpFormatter):
def _split_lines(self, text: str, width: int) -> List[str]:
text = self._whitespace_matcher.sub(" ", text).strip()
return textwrap.wrap(text, width)
class InstalledVenvsCompleter:
def __init__(self, venv_container: VenvContainer) -> None:
self.packages = [str(p.name) for p in sorted(venv_container.iter_venv_dirs())]
def use(self, prefix: str, **kwargs: Any) -> List[str]:
return [f"{prefix}{x[len(prefix):]}" for x in self.packages if x.startswith(canonicalize_name(prefix))]
def get_pip_args(parsed_args: Dict[str, str]) -> List[str]:
pip_args: List[str] = []
if parsed_args.get("index_url"):
pip_args += ["--index-url", parsed_args["index_url"]]
if parsed_args.get("pip_args"):
# Stripping the single quote that can be parsed from several shells
pip_args_striped = parsed_args["pip_args"].strip("'")
pip_args += shlex.split(pip_args_striped, posix=not WINDOWS)
# make sure --editable is last because it needs to be right before
# package specification
if parsed_args.get("editable"):
pip_args += ["--editable"]
return pip_args
def get_venv_args(parsed_args: Dict[str, str]) -> List[str]:
venv_args: List[str] = []
if parsed_args.get("system_site_packages"):
venv_args += ["--system-site-packages"]
return venv_args
def package_is_url(package: str, raise_error: bool = True) -> bool:
url_parse_package = urllib.parse.urlparse(package)
if url_parse_package.scheme and url_parse_package.netloc:
if not raise_error:
return True
raise PipxError("Package cannot be a URL. A valid package name should be passed instead.")
return False
def package_is_path(package: str):
if os.path.sep in package:
raise PipxError(
pipx_wrap(
f"""
Error: '{package}' looks like a path.
Expected the name of an installed package.
"""
)
)
def run_pipx_command(args: argparse.Namespace, subparsers: Dict[str, argparse.ArgumentParser]) -> ExitCode: # noqa: C901
verbose = args.verbose if "verbose" in args else False
pip_args = get_pip_args(vars(args))
venv_args = get_venv_args(vars(args))
venv_container = VenvContainer(paths.ctx.venvs)
if "package" in args:
package = args.package
package_is_url(package)
package_is_path(package)
if "spec" in args and args.spec is not None:
if package_is_url(args.spec, raise_error=False):
if "#egg=" not in args.spec:
args.spec = args.spec + f"#egg={package}"
venv_dir = venv_container.get_venv_dir(package)
logger.info(f"Virtual Environment location is {venv_dir}")
if "packages" in args:
for package in args.packages:
package_is_url(package)
package_is_path(package)
venv_dirs = {package: venv_container.get_venv_dir(package) for package in args.packages}
venv_dirs_msg = "\n".join(f"- {key} : {value}" for key, value in venv_dirs.items())
logger.info(f"Virtual Environment locations are:\n{venv_dirs_msg}")
if "skip" in args:
skip_list = [canonicalize_name(x) for x in args.skip]
python_flag_passed = False
if "python" in args:
python_flag_passed = bool(args.python)
fetch_missing_python = args.fetch_missing_python
try:
interpreter = find_python_interpreter(
args.python or DEFAULT_PYTHON, fetch_missing_python=fetch_missing_python
)
args.python = interpreter
except InterpreterResolutionError as e:
logger.debug("Failed to resolve interpreter:", exc_info=True)
print(
pipx_wrap(
f"{hazard} {e}",
subsequent_indent=" " * 4,
)
)
return EXIT_CODE_SPECIFIED_PYTHON_EXECUTABLE_NOT_FOUND
if args.command == "run":
commands.run(
args.app_with_args[0],
args.spec,
args.path,
args.app_with_args[1:],
args.python,
pip_args,
venv_args,
args.pypackages,
verbose,
not args.no_cache,
)
# We should never reach here because run() is NoReturn.
return ExitCode(1)
elif args.command == "install":
return commands.install(
None,
None,
args.package_spec,
paths.ctx.bin_dir,
paths.ctx.man_dir,
args.python,
pip_args,
venv_args,
verbose,
force=args.force,
reinstall=False,
include_dependencies=args.include_deps,
preinstall_packages=args.preinstall,
suffix=args.suffix,
python_flag_passed=python_flag_passed,
)
elif args.command == "install-all":
return commands.install_all(
args.spec_metadata_file,
paths.ctx.bin_dir,
paths.ctx.man_dir,
args.python,
pip_args,
venv_args,
verbose,
force=args.force,
)
elif args.command == "inject":
return commands.inject(
venv_dir,
None,
args.dependencies,
args.requirements,
pip_args,
verbose=verbose,
include_apps=args.include_apps,
include_dependencies=args.include_deps,
force=args.force,
suffix=args.with_suffix,
)
elif args.command == "uninject":
return commands.uninject(
venv_dir,
args.dependencies,
local_bin_dir=paths.ctx.bin_dir,
local_man_dir=paths.ctx.man_dir,
leave_deps=args.leave_deps,
verbose=verbose,
)
elif args.command == "upgrade":
return commands.upgrade(
venv_dirs,
args.python,
pip_args,
venv_args,
verbose,
include_injected=args.include_injected,
force=args.force,
install=args.install,
python_flag_passed=python_flag_passed,
)
elif args.command == "upgrade-all":
return commands.upgrade_all(
venv_container,
verbose,
include_injected=args.include_injected,
skip=skip_list,
force=args.force,
pip_args=pip_args,
python_flag_passed=python_flag_passed,
)
elif args.command == "upgrade-shared":
return commands.upgrade_shared(
verbose,
pip_args,
)
elif args.command == "list":
return commands.list_packages(
venv_container,
args.include_injected,
args.json,
args.short,
args.pinned,
)
elif args.command == "interpreter":
if args.interpreter_command == "list":
return commands.list_interpreters(venv_container)
elif args.interpreter_command == "prune":
return commands.prune_interpreters(venv_container)
elif args.interpreter_command == "upgrade":
return commands.upgrade_interpreters(venv_container, verbose)
elif args.interpreter_command is None:
subparsers["interpreter"].print_help()
return EXIT_CODE_OK
else:
raise PipxError(f"Unknown interpreter command {args.interpreter_command}")
elif args.command == "pin":
return commands.pin(venv_dir, verbose, skip_list, args.injected_only)
elif args.command == "unpin":
return commands.unpin(venv_dir, verbose)
elif args.command == "uninstall":
return commands.uninstall(venv_dir, paths.ctx.bin_dir, paths.ctx.man_dir, verbose)
elif args.command == "uninstall-all":
return commands.uninstall_all(
venv_container,
paths.ctx.bin_dir,
paths.ctx.man_dir,
verbose,
)
elif args.command == "reinstall":
return commands.reinstall(
venv_dir=venv_dir,
local_bin_dir=paths.ctx.bin_dir,
local_man_dir=paths.ctx.man_dir,
python=args.python,
verbose=verbose,
python_flag_passed=python_flag_passed,
)
elif args.command == "reinstall-all":
return commands.reinstall_all(
venv_container,
paths.ctx.bin_dir,
paths.ctx.man_dir,
args.python,
verbose,
skip=skip_list,
python_flag_passed=python_flag_passed,
)
elif args.command == "runpip":
if not venv_dir:
raise PipxError("Developer error: venv_dir is not defined.")
return commands.run_pip(package, venv_dir, args.pipargs, args.verbose)
elif args.command == "ensurepath":
try:
return commands.ensure_pipx_paths(prepend=args.prepend, force=args.force)
except Exception as e:
logger.debug("Uncaught Exception:", exc_info=True)
raise PipxError(str(e), wrap_message=False) from None
elif args.command == "completions":
print(constants.completion_instructions)
return ExitCode(0)
elif args.command == "environment":
return commands.environment(value=args.value)
else:
raise PipxError(f"Unknown command {args.command}")
def add_pip_venv_args(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"--system-site-packages",
action="store_true",
help="Give the virtual environment access to the system site-packages dir.",
)
parser.add_argument("--index-url", "-i", help="Base URL of Python Package Index")
parser.add_argument(
"--editable",
"-e",
help="Install a project in editable mode",
action="store_true",
)
parser.add_argument(
"--pip-args",
help="Arbitrary pip arguments to pass directly to pip install/upgrade commands",
)
def add_include_dependencies(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--include-deps", help="Include apps of dependent packages", action="store_true")
def add_python_options(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"--python",
help=(
"Python to install with. Possible values can be the executable name (python3.11), "
"the version of an available system Python or to pass to py launcher (3.11), "
f"or the full path to the executable. Requires Python {MINIMUM_PYTHON_VERSION} or above."
),
)
parser.add_argument(
"--fetch-missing-python",
action="store_true",
help=(
"Whether to fetch a standalone python build from GitHub if the specified python version is not found locally on the system."
),
)
def _add_install(subparsers: argparse._SubParsersAction, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"install",
help="Install a package",
formatter_class=LineWrapRawTextHelpFormatter,
description=INSTALL_DESCRIPTION,
parents=[shared_parser],
)
p.add_argument("package_spec", help="package name(s) or pip installation spec(s)", nargs="+")
add_include_dependencies(p)
p.add_argument(
"--force",
"-f",
action="store_true",
help="Modify existing virtual environment and files in PIPX_BIN_DIR and PIPX_MAN_DIR",
)
p.add_argument(
"--suffix",
default="",
help=(
"Optional suffix for virtual environment and executable names. "
"NOTE: The suffix feature is experimental and subject to change."
),
)
add_python_options(p)
p.add_argument(
"--preinstall",
action="append",
help=(
"Optional package to be installed into the Virtual Environment before "
"installing the main package. Use this flag multiple times if you want to preinstall multiple packages."
),
)
add_pip_venv_args(p)
def _add_install_all(subparsers: argparse._SubParsersAction, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"install-all",
help="Install all packages",
formatter_class=LineWrapRawTextHelpFormatter,
description="Installs all the packages according to spec metadata file.",
parents=[shared_parser],
)
p.add_argument("spec_metadata_file", help="Spec metadata file generated from pipx list --json")
p.add_argument(
"--force",
"-f",
action="store_true",
help="Modify existing virtual environment and files in PIPX_BIN_DIR and PIPX_MAN_DIR",
)
add_python_options(p)
add_pip_venv_args(p)
def _add_inject(subparsers, venv_completer: VenvCompleter, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"inject",
help="Install packages into an existing Virtual Environment",
description="Installs packages to an existing pipx-managed virtual environment.",
parents=[shared_parser],
)
p.add_argument(
"package",
help="Name of the existing pipx-managed Virtual Environment to inject into",
).completer = venv_completer
p.add_argument(
"dependencies",
nargs="*",
help="the packages to inject into the Virtual Environment--either package name or pip package spec",
)
p.add_argument(
"-r",
"--requirement",
dest="requirements",
action="append",
default=[],
metavar="file",
help=(
"file containing the packages to inject into the Virtual Environment--"
"one package name or pip package spec per line. "
"May be specified multiple times."
),
)
p.add_argument(
"--include-apps",
action="store_true",
help="Add apps from the injected packages onto your PATH and expose their manual pages",
)
p.add_argument(
"--include-deps",
help="Include apps of dependent packages. Implies --include-apps",
action="store_true",
)
add_pip_venv_args(p)
p.add_argument(
"--force",
"-f",
action="store_true",
help="Modify existing virtual environment and files in PIPX_BIN_DIR and PIPX_MAN_DIR",
)
p.add_argument(
"--with-suffix",
action="store_true",
help="Add the suffix (if given) of the Virtual Environment to the packages to inject",
)
def _add_uninject(subparsers, venv_completer: VenvCompleter, shared_parser: argparse.ArgumentParser):
p = subparsers.add_parser(
"uninject",
help="Uninstall injected packages from an existing Virtual Environment",
description="Uninstalls injected packages from an existing pipx-managed virtual environment.",
parents=[shared_parser],
)
p.add_argument(
"package",
help="Name of the existing pipx-managed Virtual Environment to inject into",
).completer = venv_completer
p.add_argument(
"dependencies",
nargs="+",
help="the package names to uninject from the Virtual Environment",
)
p.add_argument(
"--leave-deps",
action="store_true",
help="Only uninstall the main injected package but leave its dependencies installed.",
)
def _add_pin(subparsers, venv_completer: VenvCompleter, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"pin",
help="Pin the specified package to prevent it from being upgraded",
description="Pin the specified package to prevent it from being upgraded",
parents=[shared_parser],
)
p.add_argument("package", help="Installed package to pin")
p.add_argument(
"--injected-only",
action="store_true",
help=(
"Pin injected packages in venv only, so that they will not be upgraded during upgrade operations. "
"Note that this should not be passed if you wish to pin both main package and injected packages."
),
)
p.add_argument(
"--skip",
nargs="+",
default=[],
help="Skip these packages. Implies `--injected-only`.",
)
def _add_unpin(subparsers, venv_completer: VenvCompleter, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"unpin",
help="Unpin the specified package",
description="Unpin the specified package and all injected packages in its venv to allow them to be upgraded",
parents=[shared_parser],
)
p.add_argument("package", help="Installed package to unpin")
def _add_upgrade(subparsers, venv_completer: VenvCompleter, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"upgrade",
help="Upgrade a package",
description="Upgrade package(s) in pipx-managed Virtual Environment(s) by running 'pip install --upgrade PACKAGE'",
parents=[shared_parser],
)
p.add_argument("packages", help="package names(s) to upgrade", nargs="+").completer = venv_completer
p.add_argument(
"--include-injected",
action="store_true",
help="Also upgrade packages injected into the main app's environment",
)
p.add_argument(
"--force",
"-f",
action="store_true",
help="Modify existing virtual environment and files in PIPX_BIN_DIR and PIPX_MAN_DIR",
)
add_pip_venv_args(p)
p.add_argument(
"--install",
action="store_true",
help="Install package spec if missing",
)
add_python_options(p)
def _add_upgrade_all(subparsers: argparse._SubParsersAction, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"upgrade-all",
help="Upgrade all packages. Runs `pip install -U <pkgname>` for each package.",
description="Upgrades all packages within their virtual environments by running 'pip install --upgrade PACKAGE'",
parents=[shared_parser],
)
p.add_argument(
"--include-injected",
action="store_true",
help="Also upgrade packages injected into the main app's environment",
)
p.add_argument("--skip", nargs="+", default=[], help="skip these packages")
p.add_argument(
"--force",
"-f",
action="store_true",
help="Modify existing virtual environment and files in PIPX_BIN_DIR and PIPX_MAN_DIR",
)
def _add_upgrade_shared(subparsers: argparse._SubParsersAction, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"upgrade-shared",
help="Upgrade shared libraries.",
description="Upgrade shared libraries.",
parents=[shared_parser],
)
p.add_argument(
"--pip-args",
help="Arbitrary pip arguments to pass directly to pip install/upgrade commands",
)
def _add_uninstall(subparsers, venv_completer: VenvCompleter, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"uninstall",
help="Uninstall a package",
description="Uninstalls a pipx-managed Virtual Environment by deleting it and any files that point to its apps.",
parents=[shared_parser],
)
p.add_argument("package").completer = venv_completer
def _add_uninstall_all(subparsers: argparse._SubParsersAction, shared_parser: argparse.ArgumentParser) -> None:
subparsers.add_parser(
"uninstall-all",
help="Uninstall all packages",
description="Uninstall all pipx-managed packages",
parents=[shared_parser],
)
def _add_reinstall(subparsers, venv_completer: VenvCompleter, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"reinstall",
formatter_class=LineWrapRawTextHelpFormatter,
help="Reinstall a package",
description=textwrap.dedent(
"""
Reinstalls a package.
Package is uninstalled, then installed with pipx install PACKAGE
with the same options used in the original install of PACKAGE.
"""
),
parents=[shared_parser],
)
p.add_argument("package").completer = venv_completer
add_python_options(p)
def _add_reinstall_all(subparsers: argparse._SubParsersAction, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"reinstall-all",
formatter_class=LineWrapRawTextHelpFormatter,
help="Reinstall all packages",
description=textwrap.dedent(
"""
Reinstalls all packages.
Packages are uninstalled, then installed with pipx install PACKAGE
with the same options used in the original install of PACKAGE.
This is useful if you upgraded to a new version of Python and want
all your packages to use the latest as well.
"""
),
parents=[shared_parser],
)
add_python_options(p)
p.add_argument("--skip", nargs="+", default=[], help="skip these packages")
def _add_list(subparsers: argparse._SubParsersAction, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"list",
help="List installed packages",
description="List packages and apps installed with pipx",
parents=[shared_parser],
)
p.add_argument(
"--include-injected",
action="store_true",
help="Show packages injected into the main app's environment",
)
g = p.add_mutually_exclusive_group()
g.add_argument("--json", action="store_true", help="Output rich data in json format.")
g.add_argument("--short", action="store_true", help="List packages only.")
g.add_argument(
"--pinned",
action="store_true",
help="List pinned packages only. Pass --include-injected at the same time to list injected packages that were pinned.",
)
g.add_argument("--skip-maintenance", action="store_true", help="(deprecated) No-op")
def _add_interpreter(
subparsers: argparse._SubParsersAction, shared_parser: argparse.ArgumentParser
) -> argparse.ArgumentParser:
p: argparse.ArgumentParser = subparsers.add_parser(
"interpreter",
help="Interact with interpreters managed by pipx",
description="Interact with interpreters managed by pipx",
parents=[shared_parser],
)
s = p.add_subparsers(
title="subcommands",
description="Get help for commands with pipx interpreter COMMAND --help",
dest="interpreter_command",
)
s.add_parser("list", help="List available interpreters", description="List available interpreters")
s.add_parser("prune", help="Prune unused interpreters", description="Prune unused interpreters")
s.add_parser(
"upgrade",
help="Upgrade installed interpreters to the latest available micro/patch version",
description="Upgrade installed interpreters to the latest available micro/patch version",
)
return p
def _add_run(subparsers: argparse._SubParsersAction, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"run",
formatter_class=LineWrapRawTextHelpFormatter,
help=(
"Download the latest version of a package to a temporary virtual environment, "
"then run an app from it. Also compatible with local `__pypackages__` "
"directory (experimental)."
),
description=textwrap.dedent(
f"""
Download the latest version of a package to a temporary virtual environment,
then run an app from it. The environment will be cached
and re-used for up to {constants.TEMP_VENV_EXPIRATION_THRESHOLD_DAYS} days. This
means subsequent calls to 'run' for the same package will be faster
since they can reuse the cached Virtual Environment.
In support of PEP 582 'run' will use apps found in a local __pypackages__
directory, if present. Please note that this behavior is experimental,
and acts as a companion tool to pythonloc. It may be modified or
removed in the future. See https://github.com/cs01/pythonloc.
"""
),
parents=[shared_parser],
)
p.add_argument(
"--no-cache",
action="store_true",
help="Do not reuse cached virtual environment if it exists",
)
p.add_argument(
"app_with_args",
metavar="app ...",
nargs=argparse.REMAINDER,
help="app/package name and any arguments to be passed to it",
default=[],
)
p.add_argument("--path", action="store_true", help="Interpret app name as a local path")
p.add_argument(
"--pypackages",
action="store_true",
help="Require app to be run from local __pypackages__ directory",
)
p.add_argument("--spec", help=SPEC_HELP)
add_python_options(p)
add_pip_venv_args(p)
p.set_defaults(subparser=p)
# modify usage text to show required app argument
p.usage = re.sub(r"^usage: ", "", p.format_usage())
# add a double-dash to usage text to show requirement before app
p.usage = re.sub(r"\.\.\.", "app ...", p.usage)
def _add_runpip(subparsers, venv_completer: VenvCompleter, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"runpip",
help="Run pip in an existing pipx-managed Virtual Environment",
description="Run pip in an existing pipx-managed Virtual Environment",
parents=[shared_parser],
)
p.add_argument(
"package",
help="Name of the existing pipx-managed Virtual Environment to run pip in",
).completer = venv_completer
p.add_argument(
"pipargs",
nargs=argparse.REMAINDER,
default=[],
help="Arguments to forward to pip command",
)
def _add_ensurepath(subparsers: argparse._SubParsersAction, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"ensurepath",
help=("Ensure directories necessary for pipx operation are in your PATH environment variable."),
description=(
"Ensure directory where pipx stores apps is in your "
"PATH environment variable. Also if pipx was installed via "
"`pip install --user`, ensure pipx itself is in your PATH. "
"Note that running this may modify "
"your shell's configuration file(s) such as '~/.bashrc'."
),
parents=[shared_parser],
)
p.add_argument(
"--prepend",
action="store_true",
help=(
"Prepend directories to your PATH instead of appending. "
"This is useful if you want to prioritize pipx apps over system apps."
),
)
p.add_argument(
"--force",
"-f",
action="store_true",
help=(
"Add text to your shell's config file even if it looks like your "
"PATH already contains paths to pipx and pipx-install apps."
),
)
def _add_environment(subparsers: argparse._SubParsersAction, shared_parser: argparse.ArgumentParser) -> None:
p = subparsers.add_parser(
"environment",
formatter_class=LineWrapRawTextHelpFormatter,
help="Print a list of environment variables and paths used by pipx.",
description=textwrap.dedent(
"""
Prints the names and current values of environment variables used by pipx,
followed by internal pipx variables which are derived from the environment
variables and platform specific default values.
Available variables:
"""
)
+ textwrap.fill(", ".join(ENVIRONMENT_VARIABLES), break_long_words=False),
parents=[shared_parser],
)
p.add_argument("--value", "-V", metavar="VARIABLE", help="Print the value of the variable.")
def get_command_parser() -> Tuple[argparse.ArgumentParser, Dict[str, argparse.ArgumentParser]]:
venv_container = VenvContainer(paths.ctx.venvs)
completer_venvs = InstalledVenvsCompleter(venv_container)
shared_parser = argparse.ArgumentParser(add_help=False)
shared_parser.add_argument(
"--quiet",
"-q",
action="count",
default=0,
help=(
"Give less output. May be used multiple times corresponding to the"
" ERROR and CRITICAL logging levels. The count maxes out at 2."
),
)
shared_parser.add_argument(
"--verbose",
"-v",
action="count",
default=0,
help=(
"Give more output. May be used multiple times corresponding to the"
" INFO, DEBUG and NOTSET logging levels. The count maxes out at 3."
),
)
if not constants.WINDOWS:
shared_parser.add_argument(
"--global",
action="store_true",
dest="is_global",
help="Perform action globally for all users.",
)
parser = argparse.ArgumentParser(
prog=prog_name(),
formatter_class=LineWrapRawTextHelpFormatter,
description=PIPX_DESCRIPTION,
parents=[shared_parser],
)
parser.man_short_description = PIPX_DESCRIPTION.splitlines()[1] # type: ignore[attr-defined]
subparsers = parser.add_subparsers(dest="command", description="Get help for commands with pipx COMMAND --help")
subparsers_with_subcommands = {}
_add_install(subparsers, shared_parser)
_add_install_all(subparsers, shared_parser)
_add_uninject(subparsers, completer_venvs.use, shared_parser)
_add_inject(subparsers, completer_venvs.use, shared_parser)
_add_pin(subparsers, completer_venvs.use, shared_parser)
_add_unpin(subparsers, completer_venvs.use, shared_parser)
_add_upgrade(subparsers, completer_venvs.use, shared_parser)
_add_upgrade_all(subparsers, shared_parser)
_add_upgrade_shared(subparsers, shared_parser)
_add_uninstall(subparsers, completer_venvs.use, shared_parser)
_add_uninstall_all(subparsers, shared_parser)
_add_reinstall(subparsers, completer_venvs.use, shared_parser)
_add_reinstall_all(subparsers, shared_parser)
_add_list(subparsers, shared_parser)
subparsers_with_subcommands["interpreter"] = _add_interpreter(subparsers, shared_parser)
_add_run(subparsers, shared_parser)
_add_runpip(subparsers, completer_venvs.use, shared_parser)
_add_ensurepath(subparsers, shared_parser)
_add_environment(subparsers, shared_parser)
parser.add_argument("--version", action="store_true", help="Print version and exit")
subparsers.add_parser(