打包工具 -Pex

使用说明原文

usage: pex [-o OUTPUT.PEX] [options] [-- arg1 arg2 ...] pex builds a PEX (Python Executable) file based on the given specifications: sources, requirements, their dependencies and other options. Command-line options can be provided in one or more files by prefixing the filenames with an @ symbol. These files must contain one argument per line. positional arguments: requirements Requirements to add to the pex (default: None) options: -h, --help show this help message and exit -V, --version show program's version number and exit -o, --output-file PEX_NAME The name of the generated .pex file: Omitting this will run PEX immediately and not save it to a file. (default: None) -p, --preamble-file FILE The name of a file to be included as the preamble for the generated .pex file (default: None) -D, --sources-directory DIR Add a directory containing sources and/or resources to be packaged into the generated .pex file. This option can be used multiple times. (default: []) -R, --resources-directory DIR Add resources directory to be packaged into the generated .pex file. This option can be used multiple times. DEPRECATED: Use -D/--sources-directory instead. (default: []) -P, --package PACKAGE_SPEC Add a package and all its sub-packages to the generated .pex file. The package is expected to be found relative to the the current directory. If the package is housed in a subdirectory, indicate that by appending `@<subdirectory>`. For example, to add the top-level package `foo` housed in the current directory, use `-P foo`. If the top-level `foo` package is in the `src` subdirectory use `-P foo@src`. If you wish to just use the `foo.bar` package in the `src` subdirectory, use `-P foo.bar@src`. This option can be used multiple times. (default: []) -M, --module MODULE_SPEC Add an individual module to the generated .pex file. The module is expected to be found relative to the the current directory. If the module is housed in a subdirectory, indicate that by appending `@<subdirectory>`. For example, to add the top-level module `foo` housed in the current directory, use `-M foo`. If the top-level `foo` module is in the `src` subdirectory use `-M foo@src`. If you wish to just use the `foo.bar` module in the `src` subdirectory, use `-M foo.bar@src`. This option can be used multiple times. (default: []) --project DIR Add the local project at the specified path to the generated .pex file along with its transitive dependencies. (default: []) --group, --dependency-group GROUP[@DIR] Pull requirements from the specified PEP-735 dependency group. Dependency groups are specified by referencing the group name in a given project's pyproject.toml in the form `<group name>@<project directory>`; e.g.: `test@local/project/directory`. If either the `@<project directory>` suffix is not present or the suffix is just `@`, the current working directory is assumed to be the project directory to read the dependency group information from. Multiple dependency groups across any number of projects can be specified. Read more about dependency groups at https://peps.python.org/pep-0735/. (default: []) -r, --requirement FILE or URL Add requirements from the given requirements file. This option can be used multiple times. (default: []) --constraints FILE or URL Add constraints from the given constraints file. This option can be used multiple times. (default: []) --exclude EXCLUDED Specifies a requirement to exclude from the built PEX. Any distribution included in the PEX's resolve that matches the requirement is excluded from the built PEX along with all of its transitive dependencies that are not also required by other non-excluded distributions. At runtime, the PEX will boot without checking the excluded dependencies are available (say, via `--inherit-path`). This option can be used multiple times. (default: []) --override OVERRIDDEN Specifies a transitive requirement to override when resolving. Any distribution requirement in the PEX's resolve that matches the override project name is replaced with the given override requirement. This option can be used multiple times. (default: []) --requirements-pex FILE Add requirements from the given .pex file. This option can be used multiple times. (default: []) --seed [{none,args,verbose}] Seed local Pex caches for the generated PEX and print out the command line to run directly from the seed with (args) or else a json object including the 'pex_root' path, the 'python' binary path and the seeded 'pex' path (verbose). (default: none) --no-seed Deprecated: Use --seed=none instead. (default: None) --help-variables Print out help about the various environment variables used to change the behavior of a running PEX file. (default: None) --docs, --help-html Open a browser to view the embedded documentation for this Pex installation. For more flexible interaction with the embedded documentation, you can use this Pex installation's `pex3` script. Try `pex3 docs --help` to get started. (default: None) Resolver options: Tailor how to find, resolve and translate the packages that get put into the PEX environment. --resolver-version {pip-legacy-resolver,pip-2020-resolver} The dependency resolver version to use. For any `--pip-version` older than 23.2 this defaults to pip-legacy-resolver. For `--pip-version` 23.2 and newer this defaults to pip-2020-resolver which is the only valid version. Read more at https://pip.pypa.io/en/stable/user_guide/#resolver-changes-2020 (default: None) --pip-version {latest,latest-compatible,vendored,20.3.4-patched,22.2.2,22.3,22.3.1,23.0,23.0.1,23.1,23.1.1,23.1.2,23.2,23.3.1,23.3.2,24.0,24.1,24.1.1,24.1.2,24.2,24.3,24.3.1,25.0,25.0.1,25.1} The version of Pip to use for resolving dependencies. The `latest` version refers to the latest version in this list (25.1) which is not necessarily the latest Pip version released on PyPI. The `latest-compatible` version refers to the latest version of Pip in this list compatible with the current interpreter. (default: 24.1) --allow-pip-version-fallback, --no-allow-pip-version-fallback Whether to allow --pip-version to be ignored if the requested version is not compatible with all of the selected interpreters. If fallback is allowed, a warning will be emitted when fallback is necessary. If fallback is not allowed, Pex will fail fast indicating the problematic selected interpreters. (default: True) --extra-pip-requirement EXTRA_PIP_REQUIREMENTS Add this extra requirement to the Pip PEX uses by Pex to resolve distributions. Notably, this can be used to install keyring and keyring plugins for Pip to use. There is obviously a bootstrap issue here if your only available index is secured; so you may need to use an additional --find-links repo or --index that is not secured in order to bootstrap keyring. See: https://pip.pypa.io/en/stable/topics/authentication/#keyring-support (default: []) --use-pip-config, --no-use-pip-config Whether to allow Pip to read its local configuration files and PIP_ env vars from the environment. (default: None) --keyring-provider PROVIDER Configure Pip to use the given keyring provider to obtain authentication for package indexes. Please note that keyring support is only available in Pip v23.1 and later versions. There is obviously a bootstrap issue here if your only available index is secured; so you may need to use an additional --find-links repo or --index that is not secured in order to bootstrap a version of Pip which supports keyring. See: https://pip.pypa.io/en/stable/topics/authentication/#keyring-support (default: None) --pypi, --no-pypi, --no-index Whether to use PyPI to resolve dependencies. (default: True) -f, --find-links, --repo PATH/URL Additional repository path (directory or URL) to look for requirements. (default: None) -i, --index, --index-url URL Additional cheeseshop indices to use to satisfy requirements. (default: None) --retries RETRIES Maximum number of retries each connection should attempt. (default: 5) --resume-retries RESUME_RETRIES Maximum attempts to resume or restart an incomplete download. N.B.: This only takes effect when using Pip 25.1 or newer. (default: 3) --timeout SECS Set the socket timeout in seconds. (default: 15) --proxy PROXY Specify a proxy in the form http(s)://[user:passwd@]proxy.server:port. (default: None) --cert PATH Path to alternate CA bundle. (default: None) --client-cert PATH Path to an SSL client certificate which should be a single file containing the private key and the certificate in PEM format. (default: None) --cache-ttl DEPRECATED Deprecated: No longer used. (default: None) -H, --header DEPRECATED Deprecated: No longer used. (default: None) --pex-repository FILE Resolve requirements from the given PEX file instead of from --index servers, --find-links repos or a --lock file. (default: None) --lock FILE Resolve requirements from the given lock file created by Pex instead of from --index servers, --find-links repos or a --pex-repository. If no requirements are specified, will install the entire lock. (default: None) --path-mapping PATH_MAPPINGS A mapping of the form `NAME|PATH|DESCRIPTION` of a logical name to a concrete local absolute path with an optional description. Can be specified multiple times. The mapping must include the pipe (`|`) separated name and absolute path components, but the trailing pipe-separated description is optional. The mapping is used when creating, and later reading, lock files to ensure the lock file created on one machine can be used on another with a potentially different realization of various paths used in the resolve. A typical example is a find-links repo. This might be provided on the file-system via a network mount instead of via an HTTP(S) server and that network mount may be at different absolute paths on different machines. Classically, it may be in a user's home directory; whose path will vary from user to user. (default: []) --pre-resolved-dist, --pre-resolved-dists FILE If a wheel, add it to the PEX. If an sdist, build wheels for the selected targets and add them to the PEX. Otherwise, if a directory, add all the distributions found in the given directory to the PEX, building wheels from any sdists first. This option can be used to add a pre-resolved dependency set to a PEX. By default, Pex will ensure the dependencies added form a closure. (default: []) --pre, --no-pre Whether to include pre-release and development versions of requirements. (default: False) --wheel, --binary, --no-wheel, --no-use-wheel, --no-binary, --no-use-binary Whether to allow binary distributions. (default: True) --only-binary, --only-wheel ONLY_WHEELS Names of projects to only ever accept pre-built wheels for. (default: []) --build, --no-build Whether to allow building of distributions from source. (default: True) --only-build ONLY_BUILDS Names of projects to only ever build from source. (default: []) --prefer-wheel, --prefer-binary, --no-prefer-wheel, --no-prefer-binary Whether to prefer older binary distributions to newer source distributions (prefer not building wheels). (default: False) --force-pep517, --use-pep517, --no-use-pep517 Whether to force use of PEP 517 for building source distributions into wheels (https://peps.python.org/pep-0517) or force direct invocation of`setup.py bdist_wheel` (which requires all source distributions have a `setup.py` based build). Defaults to using PEP-517 only when a `pyproject.toml` file is present with a `build-system` section. If PEP-517 is forced (--use-pep517 is passed) and no `pyproject.toml` file is present or one is but does not have a `build-system` section defined, then the build is executed as if a `pyproject.toml` was present with a `build-system` section comprised of `requires = ["setuptools>=40.8.0", "wheel"]` and `build-backend = "setuptools.build_meta:__legacy__"`. (default: None) --build-isolation, --no-build-isolation Disable `sys.path` isolation when building a modern source distribution. Build dependencies specified by PEP 518 (https://peps.python.org/pep-0518) must already be installed on the `sys.path` if this option is used. (default: True) --transitive, --no-transitive, --intransitive Whether to transitively resolve requirements. (default: True) -j, --jobs JOBS The maximum number of parallel jobs to use when resolving, building and installing distributions. You might want to increase the maximum number of parallel jobs to potentially improve the latency of the pex creation process at the expense of other processes on your system. (default: 10) --pip-log, --preserve-pip-download-log, --no-preserve-pip-download-log [PIP_LOG] With no argument, preserve the `pip download` log and print its location to stderr. With a log path argument, truncate the log if it exists and create it if it does not already exist, and send Pip log output there. (default: None) --pex-path PEX_PATH A ':' separated list of other pex files to merge into the runtime environment. (default: None) PEX output options: Tailor the behavior of the emitted .pex file if -o is specified. --include-tools Whether to include runtime tools in the pex file. If included, these can be run by exporting PEX_TOOLS=1 and following the usage and --help information. (default: False) --zip-safe, --not-zip-safe Deprecated: This option is no longer used since user code is now always unzipped before execution. (default: None) --layout {zipapp,packed,loose} By default, a PEX is created as a single file zipapp when `-o` is specified, but either a packed or loose directory tree based layout can be chosen instead. A packed layout PEX is an executable directory structure designed to have cache-friendly characteristics for syncing incremental updates to PEXed applications over a network. At the top level of the packed directory tree there is an executable `__main__.py`script. The directory can also be executed by passing its path to a Python executable; e.g: `python packed-pex-dir/`. The Pex bootstrap code and all dependency code are packed into individual zip files for efficient caching and syncing. A loose layout PEX is similar to a packed PEX, except that neither the Pex bootstrap code nor the dependency code are packed into zip files, but are instead present as collections of loose files in the directory tree providing different caching and syncing tradeoffs. Both zipapp and packed layouts install themselves in the PEX_ROOT as loose apps by default before executing, but these layouts compose with `--venv` execution mode as well and support `--seed`ing. (default: zipapp) --pre-install-wheels, --no-pre-install-wheels Whether to pre-install third party dependency wheels. Pre-installed wheels will always yield slightly faster PEX cold boot times; so they are used by default, but they also slow down PEX build time. As the size of dependencies grows you may find a tipping point where it makes sense to not pre-install wheels; either because the increased cold boot time is irrelevant to your use case or marginal compared to other costs. Note that you may be able to use --max-install-jobs to decrease cold boot times for some PEX deployment scenarios. (default: True) --max-install-jobs MAX_INSTALL_JOBS The maximum number of parallel jobs to use when installing third party dependencies contained in a PEX during its first boot. By default, this is set to 1 which indicates dependencies should be installed in serial. A value of 2 or more indicates dependencies should be installed in parallel using exactly this maximum number of jobs. A value of 0 indicates the maximum number of parallel jobs should be auto-selected taking the number of cores into account. Finally, a value of -1 indicates the maximum number of parallel jobs should be auto-selected taking both the characteristics of the third party dependencies contained in the PEX and the number of cores into account. The third party dependency heuristics are intended to yield good install performance, but are opaque and may change across PEX releases if better heuristics are discovered. Any other value is illegal. (default: 1) --check {none,warn,error} Check that the built PEX is valid. Currently this only applies to `--layout zipapp` where the PEX zip is tested for importability of its `__main__` module by the Python zipimport module. This check will fail for PEX zips that use ZIP64 extensions since the Python zipimport zipimporter only works with 32 bit zips. The check no-ops for all other layouts. (default: warn) --compress, --compressed, --no-compress, --not-compressed, --no-compression Whether to compress zip entries when creating either a zipapp PEX file or a packed PEX's bootstrap and dependency zip files. Does nothing for loose layout PEXes. (default: True) --unzip, --no-unzip Deprecated: This option is no longer used since unzipping PEX zip files before execution is now the default. (default: None) --venv [{prepend,append}] Convert the pex file to a venv before executing it. If 'prepend' or 'append' is specified, then all scripts and console scripts provided by distributions in the pex file will be added to the PATH in the corresponding position. If the the pex file will be run multiple times under a stable runtime PEX_ROOT, the venv creation will only be done once and subsequent runs will enjoy lower startup latency. (default: False) --venv-copies, --no-venv-copies If --venv is specified, create the venv using copies of base interpreter files instead of symlinks. This allows --venv mode PEXes to work across interpreter upgrades without being forced to remove the PEX_ROOT to allow the venv to re-build using the upgraded interpreter. (default: False) --venv-site-packages-copies, --no-venv-site-packages-copies If --venv is specified, populate the venv site packages using hard links or copies of resolved PEX dependencies instead of symlinks. This can be used to work around problems with tools or libraries that are confused by symlinked source files. (default: False) --venv-system-site-packages, --no-venv-system-site-packages If --venv is specified, give the venv access to the system site-packages dir. (default: False) --non-hermetic-venv-scripts If --venv is specified, don't rewrite Python script shebangs in the venv to pass `-sE` to the interpreter; for example, to enable running the venv PEX itself or its Python scripts with a custom `PYTHONPATH`. (default: True) --scie, --par {lazy,eager} Create one or more native executable scies from your PEX that include a portable CPython interpreter along with your PEX making for a truly hermetic PEX that can run on machines with no Python installed at all. If your PEX has multiple targets, whether `--platform`s, `--complete-platform`s or local interpreters in any combination, then one PEX scie will be made for each platform, selecting the latest compatible portable CPython or PyPy interpreter as appropriate. Note that only Python>=3.8 is supported. If you'd like to explicitly control the target platforms or the exact portable CPython selected, see `--scie-platform`, `--scie-pbs-release` and `--scie-python-version`. Specifying `--scie lazy` will fetch the portable CPython interpreter just in time on first boot of the PEX scie on a given machine if needed. The URL(s) to fetch the portable CPython interpreter from can be customized by exporting the PEX_BOOTSTRAP_URLS environment variable pointing to a json file with the format: `{"ptex": {<file name 1>: <url>, ...}}` where the file names should match those found via `SCIE=inspect <the PEX scie> | jq .ptex` with appropriate replacement URLs. Specifying `--scie eager` will embed the portable CPython interpreter in your PEX scie making for a larger file, but requiring no internet access to boot. If you have customization needs not addressed by the Pex `--scie*` options, consider using `science` to build your scies (which is what Pex uses behind the scenes); see: https://science.scie.app. (default: None) --scie-only, --no-scie-only, --pex-and-scie Only output a scie. By default, both a PEX and a scie are output unless the `-o` / `--output-file` specified has no '.pex' extension or a platform suffix is included (see `--scie-name- platform`). (default: False) --scie-name-style {dynamic,platform-parent-dir,platform-file-suffix} Control how the `-o` / --output-file` translates to a scie name. By default (`--scie-name-style dynamic`), the platform is used as a file suffix only when needed for disambiguation when targeting a local platform. Specifying `--scie-name-style platform-file-suffix` forces the scie target platform name to be added as a suffix of the output filename; e.g.: `-o app` would produce a scie named app-linux-x86_64 assuming the scie targets that platform. Specifying `--scie-name-style platform-parent-dir` places the scie in a sub-directory with the name of the platform it targets; e.g.: `-o app` would produce a scie at `macos-aarch64/app` assuming the scie targets that platform. (default: None) --scie-busybox SCIE_BUSYBOX Make the PEX scie a BusyBox over the specified entry points. The entry points can either be console scripts or entry point specifiers. To select all console scripts in all distributions contained in the PEX, use `@`. To just pick all the console scripts from a particular project name's distributions in the PEX, use `@<project name>`; e.g.: `@ansible-core`. To exclude all the console scripts from a project, prefix with a `!`; e.g.: `@,!@ansible-core` selects all console scripts except those provided by the `ansible-core` project. To select an individual console script, just use its name or prefix the name with `!` to exclude that individual console script. To specify an arbitrary entry point in a module contained within one of the distributions in the PEX, use a string of the form `<name>=<module>(:<function>)`; e.g.: 'run-baz=foo.bar:baz' to execute the `baz` function in the `foo.bar` module as the entry point named `run-baz`. Multiple entry points can be specified at once using a comma-separated list or the option can be specified multiple times. A BusyBox scie has no default entrypoint; instead, when run, it inspects argv0; if that matches one of its embedded entry points, it runs that entry point; if not, it lists all available entrypoints for you to pick from. To run a given entry point, you specify it as the first argument and all other arguments after that are forwarded to that entry point. BusyBox PEX scies allow you to install all their contained entry points into a given directory. For more information, run `SCIE=help <your PEX scie>` and review the `install` command help. (default: []) --scie-busybox-pex-entrypoint-env-passthrough, --no-scie-busybox-pex-entrypoint-env-passthrough When creating a busybox, allow overriding the primary entrypoint at runtime via PEX_INTERPRETER, PEX_SCRIPT and PEX_MODULE. Note that when using --venv this adds modest startup overhead on the order of 10ms. (default: False) --scie-platform {linux-aarch64,linux-armv7l,linux-powerpc64,linux-s390x,linux-x86_64,macos-aarch64,macos-x86_64} The platform to produce the native PEX scie executable for. Can be specified multiple times. You can use a value of 'current' to select the current platform. If left unspecified, the platforms implied by the targets selected to build the PEX with are used. Those targets are influenced by the current interpreter running Pex as well as use of `--python`, `--interpreter-constraint`, `--platform` or `--complete-platform` options. Note that, in general, `--scie-platform` should only be used to select a subset of the platforms implied by the targets selected via other options. (default: []) --scie-pbs-release SCIE_PBS_RELEASE The Python Standalone Builds release to use when a CPython interpreter distribution is needed for the PEX scie. Currently, releases are dates of the form YYYYMMDD, e.g.: '20240713'. See their GitHub releases page athttps://github.com/astral-sh/python-build-standalone/releases to discover available releases. If left unspecified the latest release is used. N.B.: The latest lookup is cached for 5 days. To force a fresh lookup you can remove the cache at <USER CACHE DIR>/science/downloads. (default: None) --scie-pypy-release SCIE_PYPY_RELEASE The PyPy release to use when a PyPy interpreter distribution is needed for the PEX scie. Currently, stable releases are of the form `v<major>.<minor>.<patch>`, e.g.: 'v7.3.16'. See their download page at https://pypy.org/download.html for the latest release and https://downloads.python.org/pypy/ to discover all available releases. If left unspecified, the latest release is used. N.B.: The latest lookup is cached for 5 days. To force a fresh lookup you can remove the cache at <USER CACHE DIR>/science/downloads. (default: None) --scie-python-version SCIE_PYTHON_VERSION The portable CPython version to select. Can be either in `<major>.<minor>` form; e.g.: '3.11', or else fully specified as `<major>.<minor>.<patch>`; e.g.: '3.11.3'. If you don't specify this option, Pex will do its best to guess appropriate portable CPython versions. N.B.: Python Standalone Builds does not provide all patch versions; so you should check their releases at https://github.com/astral-sh/python-build-standalone/releases if you wish to pin down to the patch level. (default: None) --scie-pbs-stripped, --no-scie-pbs-stripped Should the Python Standalone Builds CPython distributions used be stripped of debug symbols or not. For Linux and Windows particularly, the stripped distributions are less than half the size of the distributions that ship with debug symbols. (default: False) --scie-hash-alg SCIE_HASH_ALGORITHMS Output a checksum file for each scie generated that is compatible with the shasum family of tools. For each unique --scie-hash-alg specified, a sibling file to each scie executable will be generated with the same stem as that scie file and hash algorithm name suffix. The file will contain the hex fingerprint of the scie executable using that algorithm to hash it. Supported algorithms include at least md5, sha1, sha256, sha384 and sha512. For the complete list of supported hash algorithms, see the science tool --hash documentation here: https://science.scie.app/cli.html#science-lift-build. (default: []) --scie-science-binary SCIE_SCIENCE_BINARY The file path of a `science` binary or a URL to use to fetch the `science` binary when there is no `science` on the PATH with a version matching ~=0.12.2. Pex uses the official `science` releases at https://github.com/a-scie/lift/releases by default. (default: None) --always-write-cache Deprecated: This option is no longer used; all internally cached distributions in a PEX are always installed into the local Pex dependency cache. (default: None) --ignore-errors Ignore requirement resolution solver errors when building pexes and later invoking them. (default: False) --inherit-path {false,prefer,fallback} Inherit the contents of sys.path (including site-packages, user site-packages and PYTHONPATH) running the pex. Possible values: false (does not inherit sys.path), fallback (inherits sys.path after packaged dependencies), prefer (inherits sys.path before packaged dependencies), No value (alias for prefer, for backwards compatibility). (default: false) --compile, --no-compile Compiling means that the built pex will include .pyc files, which will result in slightly faster startup performance. However, compiling means that the generated pex likely will not be reproducible, meaning that if you were to run `./pex -o` with the same inputs then the new pex would not be byte-for-byte identical to the original. (default: False) --use-system-time, --no-use-system-time Use the current system time to generate timestamps for the new pex. Otherwise, Pex will use midnight on January 1, 1980. By using system time, the generated pex will not be reproducible, meaning that if you were to run `./pex -o` with the same inputs then the new pex would not be byte-for-byte identical to the original. (default: False) --runtime-pex-root RUNTIME_PEX_ROOT Specify the pex root to be used in the generated .pex file (if unspecified, uses a pex subdirectory of default user cache directory for the runtime OS; e.g.: ~/.cache/pex on Linux and ~/Library/Caches/pex on Mac). (default: None) --strip-pex-env, --no-strip-pex-env Strip all `PEX_*` environment variables used to control the pex runtime before handing off control to the pex entrypoint. You might want to set this to `False` if the new pex executes other pexes (or the Pex CLI itself) and you want the executed pex to be controllable via `PEX_*` environment variables. (default: True) PEX target environment options: Specify which target environments the PEX should run on. If more than one interpreter or platform is specified, a multi-platform PEX will be created that can run on all specified targets. N.B.: You may need to adjust the `--python-shebang` so that it works in all the specified target environments. --python PYTHON The Python interpreter to use (default: current interpreter). Either specify an absolute path to an interpreter, or specify a binary accessible on $PATH like `python3.7`. This option can be passed multiple times. (default: []) --python-path PYTHON_PATH A ':' separated list of paths to search for interpreters in when `--interpreter-constraint` and/or `--resolve-local-platforms` are specified (default: $PATH). Each element can be the absolute path of an interpreter binary or a directory containing interpreter binaries. (default: None) --interpreter-constraint INTERPRETER_CONSTRAINT Constrain the selected Python interpreter. Specify with Requirement-style syntax, e.g. "CPython>=2.7,<3" (A CPython interpreter with version >=2.7 AND version <3), ">=2.7,<3" (Any Python interpreter with version >=2.7 AND version <3) or "PyPy" (A PyPy interpreter of any version). This argument may be repeated multiple times to OR the constraints. Try `pex3 interpreter inspect --python /Users/wangyanwei/code/python-test/dns-dialer/.venv/bin/python3 --verbose --indent 4` to find the exact interpreter constraints of /Users/wangyanwei/code/python-test/dns- dialer/.venv/bin/python3 and `pex3 interpreter inspect --all --verbose --indent 4` to find out the interpreter constraints of all Python interpreters on the $PATH. (default: []) --platform, --abbreviated-platform PLATFORMS The (abbreviated) platform to build the PEX for. This option can be passed multiple times to create a multi-platform pex. To use the platform corresponding to the current interpreter you can pass `current`. To target any other platform you pass a string composed of fields: <platform>-<python impl abbr>-<python version>-<abi>. These fields stem from wheel name conventions as outlined in https://peps.python.org/pep-0427#file-name-convention and influenced by https://peps.python.org/pep-0425. To find out more, try `pex3 interpreter inspect --all --verbose --indent 4` to print out the platform for all interpreters on the $PATH or `pex3 interpreter inspect --python /Users/wangyanwei/code/python-test/dns-dialer/.venv/bin/python3 --verbose --indent 4` to inspect the single interpreter /Users/wangyanwei/code/python-test/dns-dialer/.venv/bin/python3. (default: []) --complete-platform COMPLETE_PLATFORMS The complete platform information describing the platform for which to build the PEX. This option can be passed multiple times to create a multi-platform pex. Values should be either JSON object literal strings or paths to files containing them. The JSON object is expected to have two fields with any other fields ignored. The 'marker_environment' field should have an object value with string field values corresponding to PEP-508 marker environment entries (See: https://peps.python.org/pep-0508/#environment-markers). It is OK to only have a subset of valid marker environment fields but it is not valid to present entries not defined in PEP-508. The 'compatible_tags' field should have an array of strings value containing the compatible tags in order from most specific first to least specific last as defined in PEP-425 (See: https://peps.python.org/pep-0425). Pex can create complete platform JSON for you by running it on the target platform like so: `pex3 interpreter inspect --markers --tags`. For more options, particularly to select the desired target interpreter see: `pex3 interpreter inspect --help`. (default: []) --manylinux, --no-manylinux, --no-use-manylinux [ASSUME_MANYLINUX] Whether to allow resolution of manylinux wheels for linux target platforms. (default: manylinux2014) --resolve-local-platforms When --platforms are specified, attempt to resolve a local interpreter that matches each platform specified. If found, use the interpreter to resolve distributions; if not (or if this option is not specified), resolve for each platform only allowing matching binary distributions and failing if only sdists or non-matching binary distributions can be found. (default: False) --python-shebang PYTHON_SHEBANG The exact shebang (#!...) line to add at the top of the PEX file minus the #!. This overrides the default behavior, which picks an environment Python interpreter compatible with the one used to build the PEX file. (default: None) --sh-boot, --no-sh-boot Create a modified ZIPAPP that uses `/bin/sh` to boot. If you know the machines that the PEX will be distributed to have POSIX compliant `/bin/sh` (almost all do, see: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/sh.html); then this is probably the way you want your PEX to boot. Instead of launching via a Python shebang, the PEX will launch via a `#!/bin/sh` shebang that executes a small script embedded in the head of the PEX ZIPAPP that performs initial interpreter selection and re-execution of the underlying PEX in a way that is often more robust than a Python shebang and always faster on 2nd and subsequent runs since the sh script has a constant overhead of O(1ms) whereas the Python overhead to perform the same interpreter selection and re-execution is O(100ms). (default: False) PEX entry point options: Specify what target/module the PEX should invoke if any. -m, -e, --entry-point MODULE[:SYMBOL] Set the entry point to module or module:symbol. If just specifying module, pex behaves like python -m, e.g. python -m SimpleHTTPServer. If specifying module:symbol, pex assume symbol is a n0-arg callable and imports that symbol and invokes it as if via `sys.exit(symbol())`. (default: None) -c, --script, --console-script SCRIPT_NAME Set the entry point as to the script or console_script as defined by a any of the distributions in the pex. For example: "pex -c fab fabric" or "pex -c mturk boto". (default: None) --exe, --executable, --python-script EXECUTABLE Set the entry point to an existing local python script. For example: `pex --exe bin/my-python-script`. If the script contains PEP-723 `dependencies` metadata, add these dependencies as requirements, which will be combined with other requirements specified on the command line as positional arguments or via `-r` / `--requirement` files (if any). If the script contains PEP-723 `requires-python` metadata, treat this as the primary `--interpreter-constraint` and ensure all interpreters selected via explicit `--python`, `--interpreter-constraint`, `--platform` and `--complete-platform` command line arguments comply or else fail. (default: None) --pep723, --enable-script-metadata, --no-pep723, --no-enable-script-metadata Enable parsing PEP-723 script metadata from an `--exe` for requirements and interpreter constraints. See the `--exe` help for more details. This is enabled by default but can be disabled to work around undesired script metadata. (default: True) --validate-entry-point Validate the entry point by importing it in separate process. Warning: this could have side effects. For example, entry point `a.b.c:m` will translate to `from a.b.c import m` during validation. (default: False) --inject-env INJECT_ENV Environment variables to freeze in to the application environment. (default: []) --inject-python-args INJECT_PYTHON_ARGS Command line arguments to the Python interpreter to freeze in. For example, `-u` to disable buffering of `sys.stdout` and `sys.stderr` or `-W <arg>` to control Python warnings. (default: []) --inject-args INJECT_ARGS Command line arguments to the application to freeze in. (default: []) Global options: -v Turn on logging verbosity, may be specified multiple times. (default: 0) --emit-warnings, --no-emit-warnings Emit runtime UserWarnings on stderr. If false, only emit them when PEX_VERBOSE is set. (default: True) --pex-root PEX_ROOT Specify the pex root used in this invocation of pex (if unspecified, uses /Users/wangyanwei/Library/Caches/pex). (default: None) --disable-cache Disable caching in the pex tool entirely. (default: False) --cache-dir CACHE_DIR DEPRECATED: Use --pex-root instead. The local cache directory to use for speeding up requirement lookups. (default: None) --tmpdir TMPDIR Specify the temporary directory Pex and its subprocesses should use. (default: /var/folders/tv/7sy5wrxd249g3f54f31tcxtc0000gn/T) --rcfile RC_FILE An additional path to a pexrc file to read during configuration parsing, in addition to reading `/etc/pexrc` and `~/.pexrc`. If `PEX_IGNORE_RCFILES=true`, then all rc files will be ignored. (default: None)

使用说明翻译

基本用法

用法: pex [-o 输出文件.PEX] [选项] [-- 参数1 参数2 ...] pex 基于给定的规格(源码、依赖项及其他选项)构建 PEX(Python 可执行)文件。 可通过在文件名前添加 @ 符号将命令行选项放入一个或多个文件中。这些文件需每行包含一个参数。

位置参数

位置参数: 需求 添加到 PEX 的依赖项(默认:无)

选项

选项: -h, --help 显示帮助信息并退出 -V, --version 显示程序版本号并退出 -o, --output-file PEX名称 生成的 .pex 文件名:省略此参数将直接运行 PEX 而不保存文件(默认:无) -p, --preamble-file 文件 作为生成 PEX 文件前导语包含的文件名(默认:无) -D, --sources-directory 目录 添加包含源码/资源的目录到生成的 PEX 文件中(可重复使用)(默认:[]) -R, --resources-directory 目录 添加资源目录到 PEX 中(已弃用,请用 -D 代替)(默认:[]) -P, --package 包规范 添加包及其子包到 PEX 中(格式:包名@子目录)(可重复使用)(默认:[]) -M, --module 模块规范 添加单个模块到 PEX 中(格式:模块名@子目录)(可重复使用)(默认:[]) --project 目录 将指定路径的本地项目及其传递依赖添加到 PEX(默认:[]) --group, --dependency-group 组名@目录 从 PEP-735 依赖组中提取需求(可重复使用)(默认:[]) -r, --requirement 文件或URL 从指定需求文件添加依赖(可重复使用)(默认:[]) --constraints 文件或URL 从约束文件添加限制(可重复使用)(默认:[]) --exclude 排除项 指定要从 PEX 中排除的依赖项(可重复使用)(默认:[]) --override 覆盖项 覆盖解析时的传递依赖(可重复使用)(默认:[]) --requirements-pex 文件 从指定 .pex 文件添加需求(可重复使用)(默认:[])

解析器选项

解析器选项: --resolver-version {pip-legacy-resolver,pip-2020-resolver} 依赖解析器版本(默认:自动选择) --pip-version {latest,latest-compatible,...} 指定 Pip 版本(默认:24.1) --allow-pip-version-fallback 允许在 Pip 版本不兼容时回退(默认:True) --extra-pip-requirement 额外需求 向 Pip 添加额外需求(例如安装密钥环插件) --use-pip-config 允许 Pip 读取本地配置文件(默认:无) --keyring-provider 供应商 指定密钥环验证提供方 --pypi/--no-pypi 是否使用 PyPI(默认:True) -f, --find-links 路径/URL 添加本地/远程仓库路径(可重复使用) -i, --index-url URL 添加自定义包索引地址(默认:无) --retries 重试次数 最大连接重试次数(默认:5) --timeout 秒数 超时设置(默认:15) --proxy 代理 设置 HTTP 代理(格式:http(s)://user:pass@host:port)

输出控制选项

PEX 输出选项: --include-tools 在 PEX 中包含运行时工具(默认:False) --layout {zipapp,packed,loose} 输出布局方式(默认:zipapp 单文件) --pre-install-wheels 预安装第三方依赖(默认:True) --compress 压缩 ZIP 条目(默认:True) --venv [prepend/append] 将 PEX 转换为虚拟环境运行(默认:False) --scie {lazy/eager} 生成含独立解释器的原生可执行文件(SCIEs) --scie-platform 平台 指定目标平台(如 linux-x86_64) --scie-python-version 版本 指定便携式 CPython 版本(如 3.11)

环境目标选项

目标环境选项: --python 解释器路径 指定 Python 解释器(可重复使用) --interpreter-constraint 约束 解释器版本约束(如 "CPython>=3.8") --platform 平台 目标平台标识(如 "linux-x86_64-cp-38-cp38") --manylinux {manylinux2014} 允许使用 manylinux 兼容的二进制包(默认启用)

入口点配置

入口点选项: -m, --entry-point 模块[:符号] 设置入口模块(如 `-m http.server`) -c, --console-script 脚本名 使用 console_script 入口点(如 `-c pytest`) --exe 本地脚本路径 使用本地 Python 脚本作为入口点 --inject-env 环境变量 固化环境变量到 PEX

全局配置

全局选项: -v 增加日志详细度(可重复使用) --pex-root 路径 设置 PEX 缓存根目录 --tmpdir 临时目录 指定临时文件目录 --rcfile 配置文件 加载额外配置文件

关键功能说明

  1. 跨平台打包
    通过 --platform​ 和 --complete-platform​ 支持多平台构建
  2. 依赖管理
    使用 -r requirements.txt​ 导入依赖,支持排除特定包 (--exclude​)
  3. 虚拟环境集成
    --venv​ 选项可将 PEX 转换为虚拟环境运行,提升重复执行效率
  4. 独立可执行文件
    --scie​ 参数可生成包含 Python 解释器的原生二进制文件,实现无环境依赖运行

使用示例

# 打包 Flask 项目并指定 Python 3.9 pex flask -o app.pex --python=python3.9 # 生成跨 Linux 和 macOS 的可执行文件 pex . --platform linux-x86_64 --platform macosx_12_0_x86_64 -o multi.pex # 创建含独立解释器的 SCIE 文件 pex requests --scie eager -o web-tool

pex -D dns-dialer/ --exe dns-dialer/main.py --scie eager --scie-python-version 3.13 -o dns-dialer.pex

pex -r dns-dialer/requirement.txt -D dns-dialer/ --exe dns-dialer/main.py --scie eager --scie-platform linux-x86_64 --scie-python-version 3.13 -o dns-dialer.pex

实践案例

初始化一个项目

以一个简单 dns 请求的工具为例,使用 python 3.13 版本

➜ python-test mkdir dns-queryer ➜ python-test cd dns-queryer ➜ dns-queryer uv init --python 3.13 Initialized project `dns-queryer`

添加依赖

➜ dns-queryer git:(main) ✗ uv add dnspython pex pip trio Using CPython 3.13.3 Creating virtual environment at: .venv Resolved 12 packages in 677ms Prepared 1 package in 4.04s Installed 9 packages in 26ms + attrs==25.3.0 + dnspython==2.7.0 + idna==3.10 + outcome==1.3.0.post0 + pex==2.37.0 + pip==25.1.1 + sniffio==1.3.1 + sortedcontainers==2.4.0 + trio==0.30.0

编辑 main.py

import sys import trio import dns.asyncquery import dns.message import dns.edns async def main(): if len(sys.argv) > 1: host = sys.argv[0] else: host = "www.zdns.cn" if len(sys.argv) > 2: server = sys.argv[2] else: server = "223.5.5.5" ecs = dns.edns.ECSOption("114.114.114.115", 24) q = dns.message.make_query(host, "A", use_edns=0, options=[ecs]) r = await dns.asyncquery.tls(q, server) print("####The A Query####") print(r) q = dns.message.make_query(host, "AAAA", use_edns=0, options=[ecs]) q.want_dnssec() r = await dns.asyncquery.tls(q, server) print("\n") print("####The AAAA Query####") print(r) if __name__ == "__main__": trio.run(main)

本地运行验证

➜ dns-queryer git:(main) ✗ uv run main.py ####The A Query#### id 48925 opcode QUERY rcode NOERROR flags QR RD RA edns 0 payload 1232 option ECS 114.114.114.0/24 scope/24 option Generic 12 ;QUESTION www.zdns.cn. IN A ;ANSWER www.zdns.cn. 300 IN CNAME zdns.cn.luo510.faipod.com. zdns.cn.luo510.faipod.com. 10 IN CNAME fap-af1127e2.faipod.com. fap-af1127e2.faipod.com. 5 IN A 106.75.152.155 ;AUTHORITY ;ADDITIONAL ####The AAAA Query#### id 12949 opcode QUERY rcode NOERROR flags QR RD RA edns 0 eflags DO payload 1232 option ECS 114.114.114.0/24 scope/24 option Generic 12 ;QUESTION www.zdns.cn. IN AAAA ;ANSWER www.zdns.cn. 1 IN CNAME zdns.cn.luo510.faipod.com. zdns.cn.luo510.faipod.com. 1 IN CNAME fap-af1127e2.faipod.com. fap-af1127e2.faipod.com. 1 IN AAAA 2401:3480:3000:4::6a4b:989b ;AUTHORITY ;ADDITIONAL

生成项目依赖文件 requirement.txt

激活 venv 环境

➜ dns-queryer git:(main) ✗ source .venv/bin/activate

使用 pip​命令输出 requirement.txt

(dns-queryer) ➜ dns-queryer git:(main) ✗ pip freeze attrs==25.3.0 dnspython==2.7.0 idna==3.10 outcome==1.3.0.post0 pex==2.37.0 sniffio==1.3.1 sortedcontainers==2.4.0 trio==0.30.0 (dns-queryer) ➜ dns-queryer git:(main) ✗ pip freeze >requirement.txt (dns-queryer) ➜ dns-queryer git:(main) ✗ more requirement.txt attrs==25.3.0 dnspython==2.7.0 idna==3.10 outcome==1.3.0.post0 pex==2.37.0 sniffio==1.3.1 sortedcontainers==2.4.0 trio==0.30.0

在 venv 中执行 pex 命令打包

  1. 先 cd 至项目父目录

  2. 执行 pex 命令进行打包,注意 pex 工具在 venv 中,因此需要在 venv 环境下执行

    (dns-queryer) ➜ python-test pex -r dns-queryer/requirement.txt -D dns-queryer/ --exe dns-queryer/main.py --scie eager --scie-platform linux-x86_64 --scie-python-version 3.13 -o dns-queryer.pex

打包参数说明:

  • -r:指定要打包到 pex 文件中的依赖
  • -D:指定要合并打包到 pex 文件中的源代码目录
  • --exe:指定 pex 文件入口点,使用本地 py 脚本文件
  • --scie:指定集成打包 python 解释器
  • --scie-platform:指定输出的目标 pex 可执行文件平台架构
  • --scie-python-version:指定集成打包的 python 解释器版本
  • -o:指定输出的 pex 文件名称
  1. 输出的文件

    (dns-queryer) ➜ python-test ll -th .rwxr-xr-x wangyanwei staff 86 MB Sun May 11 14:30:48 2025  dns-queryer-linux-x86_64

拷贝生成的 pex 文件至目标机器执行验证

➜ python-test ls dns-queryer-linux-x86_64 ➜ python-test chmod a+x dns-queryer-linux-x86_64 ➜ python-test ls dns-queryer-linux-x86_64 ➜ python-test ./dns-queryer-linux-x86_64 ####The A Query#### id 52422 opcode QUERY rcode NOERROR flags QR RD RA edns 0 payload 1232 option ECS 114.114.114.0/24 scope/24 option Generic 12 ;QUESTION www.zdns.cn. IN A ;ANSWER www.zdns.cn. 300 IN CNAME zdns.cn.luo510.faipod.com. zdns.cn.luo510.faipod.com. 10 IN CNAME fap-af1127e2.faipod.com. fap-af1127e2.faipod.com. 5 IN A 106.75.152.155 ;AUTHORITY ;ADDITIONAL ####The AAAA Query#### id 58546 opcode QUERY rcode NOERROR flags QR RD RA edns 0 eflags DO payload 1232 option ECS 114.114.114.0/24 scope/24 option Generic 12 ;QUESTION www.zdns.cn. IN AAAA ;ANSWER www.zdns.cn. 300 IN CNAME zdns.cn.luo510.faipod.com. zdns.cn.luo510.faipod.com. 10 IN CNAME fap-af1127e2.faipod.com. fap-af1127e2.faipod.com. 600 IN AAAA 2401:3480:3000:4::6a4b:989b ;AUTHORITY ;ADDITIONAL

原理

pex 工具本质上是利用了 python 解释器对 zip 的原生支持进行实现,因此考虑解压打包后的 zip 文件对其原理进行学习

可以尝试创建一个 python 脚本文件,并将其打包为一个 zip 文件,此时可直接通过 python xxx.zip 来进行运行

解压打包后的 pex 文件,可以看到 pex 主要是打包了 venv 虚拟环境、项目目录相关文件,以及 pex 相关的一些执行入口的文件

➜ python-test unzip dns-queryer-linux-x86_64 ➜ python-test ls -a . .. .bootstrap .deps dns-queryer-linux-x86_64 .git .gitignore __main__.py main.py __pex__ __pex_executable__.py PEX-INFO pyproject.toml .python-version README.md requirement.txt uv.lock .venv

关键工具参数

  • -r:指定要打包到 pex 文件中的依赖
  • -D:指定要合并打包到 pex 文件中的源代码目录
  • --exe:指定 pex 文件入口点,使用本地 py 脚本文件
  • --scie:指定集成打包 python 解释器
  • --scie-platform:指定输出的目标 pex 可执行文件平台架构
  • --scie-python-version:指定集成打包的 python 解释器版本
  • -o:指定输出的 pex 文件名称
  • Python

    Python 是一种面向对象、直译式电脑编程语言,具有近二十年的发展历史,成熟且稳定。它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务。它的语法简捷和清晰,尽量使用无异义的英语单词,与其它大多数程序设计语言使用大括号不一样,它使用缩进来定义语句块。

    554 引用 • 675 回帖 • 1 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...