Repository: pex-tool/pex

Issue:
pex fails to build sdist when creating lockfile for local project
Using the latest pex with python3.10 on Ubuntu Jammy when I try to generate a lockfile from a local clone of `requests` I get the following error.

``` shell
PEX_SCRIPT=pex3 PEX_VERBOSE=9 python3.10 ./pex-2.1.102 lock create ./requests
pex: Laying out PEX zipfile /home/zmanji/tmp/pexfun/pex-2.1.102: 0.1ms
pex: Executing installed PEX for /home/zmanji/tmp/pexfun/./pex-2.1.102 at /home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a
pex: Installed VendorImporter(root='/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap', importables=(_Importable(module='attr', is_pkg=True, path='pex/vendor/_vendored/attrs', prefix='pex.third_party'), _Importable(module='pyparsing', is_pkg=False, path='pex/vendor/_vendored/packaging', prefix='pex.third_party'), _Importable(module='packaging', is_pkg=True, path='pex/vendor/_vendored/packaging', prefix='pex.third_party'), _Importable(module='setuptools', is_pkg=True, path='pex/vendor/_vendored/setuptools', prefix='pex.third_party'), _Importable(module='pkg_resources', is_pkg=True, path='pex/vendor/_vendored/setuptools', prefix='pex.third_party'), _Importable(module='wheel', is_pkg=True, path='pex/vendor/_vendored/wheel', prefix='pex.third_party')))
pex: pex.third_party.attr imported via _Loader(module_name='pex.third_party.attr', vendor_module_name='pex.vendor._vendored.attrs.attr')
pex: pex.third_party.packaging imported via _Loader(module_name='pex.third_party.packaging', vendor_module_name='pex.vendor._vendored.packaging.packaging')
pex: pex.third_party.packaging.utils imported via _Loader(module_name='pex.third_party.packaging.utils', vendor_module_name='pex.vendor._vendored.packaging.packaging.utils')
pex: pex.third_party.pyparsing imported via _Loader(module_name='pex.third_party.pyparsing', vendor_module_name='pex.vendor._vendored.packaging.pyparsing')
pex: pex.third_party.packaging.markers imported via _Loader(module_name='pex.third_party.packaging.markers', vendor_module_name='pex.vendor._vendored.packaging.packaging.markers')
pex: pex.third_party.packaging.requirements imported via _Loader(module_name='pex.third_party.packaging.requirements', vendor_module_name='pex.vendor._vendored.packaging.packaging.requirements')
pex: pex.third_party.packaging.specifiers imported via _Loader(module_name='pex.third_party.packaging.specifiers', vendor_module_name='pex.vendor._vendored.packaging.packaging.specifiers')
pex: pex.third_party.packaging.tags imported via _Loader(module_name='pex.third_party.packaging.tags', vendor_module_name='pex.vendor._vendored.packaging.packaging.tags')
pex: No pyenv installation was found.
pex: Searching for pyenv root...: 0.1ms
pex: Using $PATH constrained by ['>=2.7,<3.12,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*']
pex: Constraints on interpreters: ['>=2.7,<3.12,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*'], Matching Interpreter: /usr/bin/python3.10
pex: Selecting runtime interpreter :: Testing /usr/bin/python3.10 can resolve PEX at /home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a :: Searching dependency cpex: Selecting runtime interpreter :: Testing /usr/bin/python3.10 can resolve PEX at /home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a :: Searching dependency cpex: Selecting runtime interpreter :: Testing /usr/bin/python3.10 can resolve PEX at /home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a :: Resolving pex==2.1.102pex: Skipping activation of `subprocess32>=3.2.7; extra == "subprocess" and python_version < "3"` due to environment marker de-selection                                                
pex: Selecting runtime interpreter: 3.1ms
pex:   Testing /usr/bin/python3.10 can resolve PEX at /home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a: 2.4ms
pex:     Searching dependency cache: /home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.deps: 1.9ms
pex:       Adding pex 2.1.102: 0.0ms
pex:     Resolving pex==2.1.102: 0.1ms
pex: Using the current interpreter /usr/bin/python3.10 since it matches constraints and PYTHONPATH is not set.
pex: Found site-library: /usr/local/lib/python3.10/dist-packages
pex: Found site-library: /usr/lib/python3/dist-packages
pex: Found site-library: /usr/lib/python3.10/dist-packages
pex: Found .pth file: /usr/lib/python3/dist-packages/matplotlib-3.5.1-nspkg.pth
pex: Error executing line 1 of /usr/lib/python3/dist-packages/matplotlib-3.5.1-nspkg.pth with content:
import sys, types, os;has_mfs = sys.version_info > (3, 5);p = os.path.join(sys._getframe(1).f_locals['sitedir'], *('mpl_toolkits',));importlib = has_mfs and __import__('importlib.util');has_mfs and __import__('importlib.machinery');m = has_mfs and sys.modules.setdefault('mpl_toolkits', importlib.util.module_from_spec(importlib.machinery.PathFinder.find_spec('mpl_toolkits', [os.path.dirname(p)])));m = m or sys.modules.setdefault('mpl_toolkits', types.ModuleType('mpl_toolkits'));mp = (m or []) and m.__dict__.setdefault('__path__',[]);(p not in mp) and mp.append(p)
Error was:
'sitedir'
pex: Not a tainted path element: /home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap
pex: Not a tainted path element: /home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a
pex: Not a tainted path element: /usr/lib/python310.zip
pex: Not a tainted path element: /usr/lib/python3.10
pex: Not a tainted path element: /usr/lib/python3.10/lib-dynload
pex: Not a tainted path element: /home/zmanji/.local/lib/python3.10/site-packages
pex: Tainted path element: /usr/local/lib/python3.10/dist-packages
pex: Tainted path element: /usr/lib/python3/dist-packages
pex: Scrubbing from user site: /home/zmanji/.local/lib/python3.10/site-packages
pex: Scrubbing from site-packages: /usr/local/lib/python3.10/dist-packages
pex: Scrubbing from site-packages: /usr/lib/python3/dist-packages
pex: Dropping mpl_toolkits
pex: Dropping apport_python_hook
pex: New sys.path: ['/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap', '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload']
pex: Activating PEX virtual environment from /home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a: 0.1ms                                     
pex:   Activating pex 2.1.102: 0.1ms
pex:     Adding sitedir: 0.1ms
pex: Not setting process title since setproctitle is not available in /home/zmanji/tmp/pexfun/pex-2.1.102
pex: Found console_script CallableEntryPoint(name='pex3', module='pex.cli.pex', _attrs=('main',)) in Distribution(location='/home/zmanji/.pex/installed_wheels/d70444dc4c636a154fc77836d81e657d7ad8d148f2baee61c6a62095ecf3d504/pex-2.1.102-py2.py3-none-any.whl', metadata=DistMetadata(project_name=ProjectName(raw='pex', normalized='pex'), version=Version(raw='2.1.102', normalized='2.1.102'), requires_dists=(Requirement(name='subprocess32', url=None, extras=frozenset(), specifier=<SpecifierSet('>=3.2.7')>, marker=<Marker('extra == "subprocess" and python_version < "3"')>),), requires_python=<SpecifierSet('!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,<3.12,>=2.7')>)).
pex: Bootstrap complete, performing final sys.path modifications...
pex: un-imported pex.third_party.attr
pex: un-imported pex.vendor._vendored.attrs.attr
pex: un-imported pex.vendor._vendored.attrs.attr._cmp
pex: un-imported pex.vendor._vendored.attrs.attr._compat
pex: un-imported pex.vendor._vendored.attrs.attr._config
pex: un-imported pex.vendor._vendored.attrs.attr._funcs
pex: un-imported pex.vendor._vendored.attrs.attr._make
pex: un-imported pex.vendor._vendored.attrs.attr._next_gen
pex: un-imported pex.vendor._vendored.attrs.attr._version_info
pex: un-imported pex.vendor._vendored.attrs.attr.converters
pex: un-imported pex.vendor._vendored.attrs.attr.exceptions
pex: un-imported pex.vendor._vendored.attrs.attr.filters
pex: un-imported pex.vendor._vendored.attrs.attr.setters
pex: un-imported pex.vendor._vendored.attrs.attr.validators
pex: un-imported pex.third_party.packaging
pex: un-imported pex.third_party.packaging.markers
pex: un-imported pex.third_party.packaging.requirements
pex: un-imported pex.third_party.packaging.specifiers
pex: un-imported pex.third_party.packaging.tags
pex: un-imported pex.third_party.packaging.utils
pex: un-imported pex.vendor._vendored.packaging.packaging
pex: un-imported pex.vendor._vendored.packaging.packaging.__about__
pex: un-imported pex.vendor._vendored.packaging.packaging._compat
pex: un-imported pex.vendor._vendored.packaging.packaging._structures
pex: un-imported pex.vendor._vendored.packaging.packaging._typing
pex: un-imported pex.vendor._vendored.packaging.packaging.markers
pex: un-imported pex.vendor._vendored.packaging.packaging.requirements
pex: un-imported pex.vendor._vendored.packaging.packaging.specifiers
pex: un-imported pex.vendor._vendored.packaging.packaging.tags
pex: un-imported pex.vendor._vendored.packaging.packaging.utils
pex: un-imported pex.vendor._vendored.packaging.packaging.version
pex: un-imported pex.third_party.pyparsing
pex: un-imported pex.vendor._vendored.packaging.pyparsing
pex: Uninstalled VendorImporter(root='/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap', importables=(_Importable(module='attr', is_pkg=True, path='pex/vendor/_vendored/attrs', prefix='pex.third_party'), _Importable(module='pyparsing', is_pkg=False, path='pex/vendor/_vendored/packaging', prefix='pex.third_party'), _Importable(module='packaging', is_pkg=True, path='pex/vendor/_vendored/packaging', prefix='pex.third_party'), _Importable(module='setuptools', is_pkg=True, path='pex/vendor/_vendored/setuptools', prefix='pex.third_party'), _Importable(module='pkg_resources', is_pkg=True, path='pex/vendor/_vendored/setuptools', prefix='pex.third_party'), _Importable(module='wheel', is_pkg=True, path='pex/vendor/_vendored/wheel', prefix='pex.third_party')))
pex: Demoting code from Bootstrap(sys_path_entry='/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap')
pex: un-imported <module 'pex.version' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/version.py'>
pex: un-imported <module 'pex.venv.virtualenv' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/venv/virtualenv.py'>
pex: un-imported <module 'pex.venv.bin_path' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/venv/bin_path.py'>
pex: un-imported <module 'pex.venv' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/venv/__init__.py'>
pex: un-imported <module 'pex.vendor._vendored.packaging' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/vendor/_vendored/packaging/__init__.py'>
pex: un-imported <module 'pex.vendor._vendored.attrs' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/vendor/_vendored/attrs/__init__.py'>
pex: un-imported <module 'pex.vendor._vendored' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/vendor/_vendored/__init__.py'>
pex: un-imported <module 'pex.vendor' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/vendor/__init__.py'>
pex: un-imported <module 'pex.variables' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/variables.py'>
pex: un-imported <module 'pex.util' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/util.py'>
pex: un-imported <module 'pex.typing' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/typing.py'>
pex: un-imported <module 'pex.tracer' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/tracer.py'>
pex: un-imported <module 'pex.third_party' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/third_party/__init__.py'>
pex: un-imported <module 'pex.targets' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/targets.py'>
pex: un-imported <module 'pex.rank' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/rank.py'>
pex: un-imported <module 'pex.pyenv' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/pyenv.py'>
pex: un-imported <module 'pex.platforms' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/platforms.py'>
pex: un-imported <module 'pex.pex_warnings' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/pex_warnings.py'>
pex: un-imported <module 'pex.pex_info' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/pex_info.py'>
pex: un-imported <module 'pex.pex_bootstrapper' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/pex_bootstrapper.py'>
pex: un-imported <module 'pex.pex' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/pex.py'>
pex: un-imported <module 'pex.pep_508' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/pep_508.py'>
pex: un-imported <module 'pex.pep_503' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/pep_503.py'>
pex: un-imported <module 'pex.pep_440' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/pep_440.py'>
pex: un-imported <module 'pex.pep_425' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/pep_425.py'>
pex: un-imported <module 'pex.pep_376' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/pep_376.py'>
pex: un-imported <module 'pex.orderedset' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/orderedset.py'>
pex: un-imported <module 'pex.layout' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/layout.py'>
pex: un-imported <module 'pex.jobs' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/jobs.py'>
pex: un-imported <module 'pex.interpreter_constraints' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/interpreter_constraints.py'>
pex: un-imported <module 'pex.interpreter' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/interpreter.py'>
pex: un-imported <module 'pex.inherit_path' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/inherit_path.py'>
pex: un-imported <module 'pex.hashing' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/hashing.py'>
pex: un-imported <module 'pex.fingerprinted_distribution' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/fingerprinted_distribution.py'>
pex: un-imported <module 'pex.finders' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/finders.py'>
pex: un-imported <module 'pex.executor' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/executor.py'>
pex: un-imported <module 'pex.environment' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/environment.py'>
pex: un-imported <module 'pex.enum' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/enum.py'>
pex: un-imported <module 'pex.dist_metadata' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/dist_metadata.py'>
pex: un-imported <module 'pex.compatibility' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/compatibility.py'>
pex: un-imported <module 'pex.common' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/common.py'>
pex: un-imported <module 'pex.bootstrap' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/bootstrap.py'>
pex: un-imported <module 'pex' from '/home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap/pex/__init__.py'>
pex: Re-imported pex from ['/home/zmanji/.pex/installed_wheels/d70444dc4c636a154fc77836d81e657d7ad8d148f2baee61c6a62095ecf3d504/pex-2.1.102-py2.py3-none-any.whl/pex']
pex: PYTHONPATH contains:
pex:     /home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a
pex:   * /usr/lib/python310.zip
pex:     /usr/lib/python3.10
pex:     /usr/lib/python3.10/lib-dynload
pex:     /home/zmanji/.pex/installed_wheels/d70444dc4c636a154fc77836d81e657d7ad8d148f2baee61c6a62095ecf3d504/pex-2.1.102-py2.py3-none-any.whl
pex:     /home/zmanji/.pex/unzipped_pexes/2aac9312154c299fac910874b778e800dca4c62a/.bootstrap
pex:   * - paths that do not exist or will be imported via zipimport
pex: Installed VendorImporter(root='/home/zmanji/.pex/installed_wheels/d70444dc4c636a154fc77836d81e657d7ad8d148f2baee61c6a62095ecf3d504/pex-2.1.102-py2.py3-none-any.whl', importables=(_Importable(module='attrs', is_pkg=True, path='pex/vendor/_vendored/attrs', prefix='pex.third_party'), _Importable(module='attr', is_pkg=True, path='pex/vendor/_vendored/attrs', prefix='pex.third_party'), _Importable(module='pyparsing', is_pkg=False, path='pex/vendor/_vendored/packaging', prefix='pex.third_party'), _Importable(module='packaging', is_pkg=True, path='pex/vendor/_vendored/packaging', prefix='pex.third_party'), _Importable(module='toml', is_pkg=True, path='pex/vendor/_vendored/toml', prefix='pex.third_party'), _Importable(module='pip', is_pkg=True, path='pex/vendor/_vendored/pip', prefix='pex.third_party'), _Importable(module='easy_install', is_pkg=False, path='pex/vendor/_vendored/setuptools', prefix='pex.third_party'), _Importable(module='setuptools', is_pkg=True, path='pex/vendor/_vendored/setuptools', prefix='pex.third_party'), _Importable(module='pkg_resources', is_pkg=True, path='pex/vendor/_vendored/setuptools', prefix='pex.third_party'), _Importable(module='wheel', is_pkg=True, path='pex/vendor/_vendored/wheel', prefix='pex.third_party')))
pex: pex.third_party.attr imported via _Loader(module_name='pex.third_party.attr', vendor_module_name='pex.vendor._vendored.attrs.attr')
pex: pex.third_party.packaging imported via _Loader(module_name='pex.third_party.packaging', vendor_module_name='pex.vendor._vendored.packaging.packaging')
pex: pex.third_party.packaging.utils imported via _Loader(module_name='pex.third_party.packaging.utils', vendor_module_name='pex.vendor._vendored.packaging.packaging.utils')
pex: pex.third_party.pyparsing imported via _Loader(module_name='pex.third_party.pyparsing', vendor_module_name='pex.vendor._vendored.packaging.pyparsing')
pex: pex.third_party.packaging.markers imported via _Loader(module_name='pex.third_party.packaging.markers', vendor_module_name='pex.vendor._vendored.packaging.packaging.markers')
pex: pex.third_party.packaging.requirements imported via _Loader(module_name='pex.third_party.packaging.requirements', vendor_module_name='pex.vendor._vendored.packaging.packaging.requirements')
pex: pex.third_party.packaging.specifiers imported via _Loader(module_name='pex.third_party.packaging.specifiers', vendor_module_name='pex.vendor._vendored.packaging.packaging.specifiers')
pex: pex.third_party.packaging.tags imported via _Loader(module_name='pex.third_party.packaging.tags', vendor_module_name='pex.vendor._vendored.packaging.packaging.tags')
pex: pex.third_party.packaging.version imported via _Loader(module_name='pex.third_party.packaging.version', vendor_module_name='pex.vendor._vendored.packaging.packaging.version')
pex: pex.third_party.toml imported via _Loader(module_name='pex.third_party.toml', vendor_module_name='pex.vendor._vendored.toml.toml')
pex: pex.third_party.toml.tz imported via _Loader(module_name='pex.third_party.toml.tz', vendor_module_name='pex.vendor._vendored.toml.toml.tz')
pex: pex.third_party.toml.decoder imported via _Loader(module_name='pex.third_party.toml.decoder', vendor_module_name='pex.vendor._vendored.toml.toml.decoder')
pex: pex.third_party.toml imported via _Loader(module_name='pex.third_party.toml', vendor_module_name='pex.vendor._vendored.toml.toml')
pex: No pyenv installation was found.
pex: Searching for pyenv root...: 0.1ms
pex: Resolving for:
pex: Spawning a maximum of 24 parallel jobs to process:
  /usr/bin/python3.10
pex: Hashing pex: 21.9ms
pex: Isolating pex: 0.0ms
pex: Resolving for:
pex: Resolving for:10 :: Fingerprinting local project at /home/zmanji/tmp/pexfun/requests
pex: Vendoring attr from VendorSpec(key='attrs', requirement='git+https://github.com/python-attrs/attrs@947bfb542104209a587280701d8cb389c813459d#egg=attrs', rewrite=True, constrain=False, constraints=None) @ /home/zmanji/.pex/installed_wheels/d70444dc4c636a154fc77836d81e657d7ad8d148f2baee61c6a62095ecf3d504/pex-2.1.102-py2.py3-none-any.whl/pex/vendor/_vendored/attrs
pex: Vendoring packaging from VendorSpec(key='packaging', requirement='packaging==20.9', rewrite=True, constrain=True, constraints=('pyparsing<3',)) @ /home/zmanji/.pex/installed_wheels/d70444dc4c636a154fc77836d81e657d7ad8d148f2baee61c6a62095ecf3d504/pex-2.1.102-py2.py3-none-any.whl/pex/vendor/_vendored/packaging
pex: Vendoring pyparsing from VendorSpec(key='packaging', requirement='packaging==20.9', rewrite=True, constrain=True, constraints=('pyparsing<3',)) @ /home/zmanji/.pex/installed_wheels/d70444dc4c636a154fc77836d81e657d7ad8d148f2baee61c6a62095ecf3d504/pex-2.1.102-py2.py3-none-any.whl/pex/vendor/_vendored/packaging
pex: Vendoring pkg_resources from PreparedGit(key='setuptools', requirement='git+https://github.com/pantsbuild/setuptools@3acb925dd708430aeaf197ea53ac8a752f7c1863#egg=setuptools', rewrite=True, constrain=False, constraints=None) @ /home/zmanji/.pex/installed_wheels/d70444dc4c636a154fc77836d81e657d7ad8d148f2baee61c6a62095ecf3d504/pex-2.1.102-py2.py3-none-any.whl/pex/vendor/_vendored/setuptools
pex: Vendoring setuptools from PreparedGit(key='setuptools', requirement='git+https://github.com/pantsbuild/setuptools@3acb925dd708430aeaf197ea53ac8a752f7c1863#egg=setuptools', rewrite=True, constrain=False, constraints=None) @ /home/zmanji/.pex/installed_wheels/d70444dc4c636a154fc77836d81e657d7ad8d148f2baee61c6a62095ecf3d504/pex-2.1.102-py2.py3-none-any.whl/pex/vendor/_vendored/setuptools
pex: Vendoring wheel from VendorSpec(key='wheel', requirement='wheel==0.37.1', rewrite=False, constrain=True, constraints=None) @ /home/zmanji/.pex/installed_wheels/d70444dc4c636a154fc77836d81e657d7ad8d148f2baee61c6a62095ecf3d504/pex-2.1.102-py2.py3-none-any.whl/pex/vendor/_vendored/wheel
Failed to build sdist for local project /home/zmanji/tmp/pexfun/requests: Command '['/home/zmanji/.pex/venvs/73e6dd7be7b59d3476c8713b9c5620690733ea6e/5985ed09b49a653d6596b0e14d134c5456cf1a9f/bin/python', '-sE', '/home/zmanji/.pex/venvs/73e6dd7be7b59d3476c8713b9c5620690733ea6e/5985ed09b49a653d6596b0e14d134c5456cf1a9f/pex', '-c', 'import setuptools.build_meta\n\n\nsdist_relpath = setuptools.build_meta.__legacy__.build_sdist(\'/tmp/tmpuofyyo7h/dists\')\nwith open(\'/tmp/tmpate3opfw\', "w") as fp:\n    fp.write(sdist_relpath)\n']' returned non-zero exit status 1.
b'Traceback (most recent call last):\n  File "/home/zmanji/.pex/venvs/73e6dd7be7b59d3476c8713b9c5620690733ea6e/5985ed09b49a653d6596b0e14d134c5456cf1a9f/pex", line 158, in <module>\n    os.execv(script_path, [script_path] + sys.argv[1:])\nFileNotFoundError: [Errno 2] No such file or directory\n'
```

It really looks like pex is trying to build the sdist but I am not sure what the "No such file or directory" is referencing.


Discussion:
Ok, this is specific to using the Pex PEX:
```
^jsirois@gill ~/dev/psf $ curl -sSL https://github.com/pantsbuild/pex/releases/download/v2.1.102/pex > pex-2.1.102.pex
^jsirois@gill ~/dev/psf $ PEX_SCRIPT=pex3 python3.10 ./pex-2.1.102.pex lock create ./requests
Failed to build sdist for local project /home/jsirois/dev/psf/requests: Command '['/home/jsirois/.pex/venvs/e0b9868c43b2477b01f2d232389876aaa89e09e7/5985ed09b49a653d6596b0e14d134c5456cf1a9f/bin/python', '-sE', '/home/jsirois/.pex/venvs/e0b9868c43b2477b01f2d232389876aaa89e09e7/5985ed09b49a653d6596b0e14d134c5456cf1a9f/pex', '-c', 'import setuptools.build_meta\n\n\nsdist_relpath = setuptools.build_meta.__legacy__.build_sdist(\'/tmp/tmpnqgxqos7/dists\')\nwith open(\'/tmp/tmph9_pug33\', "w") as fp:\n    fp.write(sdist_relpath)\n']' returned non-zero exit status 1.
b'Re-execing from /home/jsirois/.pex/venvs/e0b9868c43b2477b01f2d232389876aaa89e09e7/5985ed09b49a653d6596b0e14d134c5456cf1a9f/bin/python\nTraceback (most recent call last):\n  File "/home/jsirois/.pex/venvs/e0b9868c43b2477b01f2d232389876aaa89e09e7/5985ed09b49a653d6596b0e14d134c5456cf1a9f/pex", line 158, in <module>\n    os.execv(script_path, [script_path] + sys.argv[1:])\nFileNotFoundError: [Errno 2] No such file or directory\n'
```

Versus:
```
^jsirois@gill ~/dev/psf $ python3.10 -mvenv pex.venv
^jsirois@gill ~/dev/psf $ ./pex.venv/bin/pip -q install -U pip
^jsirois@gill ~/dev/psf $ ./pex.venv/bin/pip -q install pex==2.1.102
^jsirois@gill ~/dev/psf $ ./pex.venv/bin/pex -V
2.1.102
^jsirois@gill ~/dev/psf $ ./pex.venv/bin/pex3 lock create ./requests
{"allow_builds": true, "allow_prereleases": false, "allow_wheels": true, "build_isolation": true, "constraints": [], "locked_resolves": [{"locked_requirements": [{"artifacts": [{"algorithm": "sha256", "hash": "fe86415d55e84719d75f8b69414f6438ac3547d2078ab91b67e779ef69378412", "url": "https://files.pythonhosted.org/packages/e9/06/d3d367b7af6305b16f0d28ae2aaeb86154fa91f144f036c2d5002a5a202b/certifi-2022.6.15-py3-none-any.whl"}], "project_name": "certifi", "requires_dists": [], "requires_python": ">=3.6", "version": "2022.6.15"}, {"artifacts": [{"algorithm": "sha256", "hash": "5189b6f22b01957427f35b6a08d9a0bc45b46d3788ef5a92e978433c7a35f8a5", "url": "https://files.pythonhosted.org/packages/94/69/64b11e8c2fb21f08634468caef885112e682b0ebe2908e74d3616eb1c113/charset_normalizer-2.1.0-py3-none-any.whl"}], "project_name": "charset-normalizer", "requires_dists": ["unicodedata2; extra == \"unicode_backport\""], "requires_python": ">=3.6.0", "version": "2.1"}, {"artifacts": [{"algorithm": "sha256", "hash": "84d9dd047ffa80596e0f246e2eab0b391788b0503584e8945f2368256d2735ff", "url": "https://files.pythonhosted.org/packages/04/a2/d918dcd22354d8958fe113e1a3630137e0fc8b44859ade3063982eacd2a4/idna-3.3-py3-none-any.whl"}], "project_name": "idna", "requires_dists": [], "requires_python": ">=3.5", "version": "3.3"}, {"artifacts": [{"algorithm": "sha256", "hash": "dd93f67556977d08c936b26a30ba8a790e4ecf99b7d6ce63fd3eaee90955e65f", "url": "file:///home/jsirois/dev/psf/requests"}], "project_name": "requests", "requires_dists": ["PySocks!=1.5.7,>=1.5.6; extra == \"socks\"", "certifi>=2017.4.17", "chardet<6,>=3.0.2; extra == \"use_chardet_on_py3\"", "charset-normalizer<3,>=2", "idna<4,>=2.5", "urllib3<1.27,>=1.21.1"], "requires_python": "<4,>=3.7", "version": "2.28.1"}, {"artifacts": [{"algorithm": "sha256", "hash": "c33ccba33c819596124764c23a97d25f32b28433ba0dedeb77d873a38722c9bc", "url": "https://files.pythonhosted.org/packages/d1/cb/4783c8f1a90f89e260dbf72ebbcf25931f3a28f8f80e2e90f8a589941b19/urllib3-1.26.11-py2.py3-none-any.whl"}], "project_name": "urllib3", "requires_dists": ["PySocks!=1.5.7,<2.0,>=1.5.6; extra == \"socks\"", "brotli>=1.0.9; ((os_name != \"nt\" or python_version >= \"3\") and platform_python_implementation == \"CPython\") and extra == \"brotli\"", "brotlicffi>=0.8.0; ((os_name != \"nt\" or python_version >= \"3\") and platform_python_implementation != \"CPython\") and extra == \"brotli\"", "brotlipy>=0.6.0; (os_name == \"nt\" and python_version < \"3\") and extra == \"brotli\"", "certifi; extra == \"secure\"", "cryptography>=1.3.4; extra == \"secure\"", "idna>=2.0.0; extra == \"secure\"", "ipaddress; python_version == \"2.7\" and extra == \"secure\"", "pyOpenSSL>=0.14; extra == \"secure\""], "requires_python": "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,<4,>=2.7", "version": "1.26.11"}], "platform_tag": ["cp310", "cp310", "manylinux_2_36_x86_64"]}], "path_mappings": {}, "pex_version": "2.1.102", "prefer_older_binary": false, "requirements": ["requests==2.28.1"], "requires_python": [], "resolver_version": "pip-legacy-resolver", "style": "strict", "target_systems": [], "transitive": true, "use_pep517": null}
```
Ok, yeah - this has nothing to do with locks, it's all about using PEX_SCRIPT and this:
```
$ pex-tools pex-2.1.102.pex info | jq .strip_pex_env
false
```

In other words, when the Pex PEX boots, it does not strip `PEX_*` env vars before handing off to user code (in this case the user code is Pex code); as such, when the Pex user code spawns Pex dogfood subprocesses, as it does when running Pip and when building sdists, the `PEX_SCRIPT=pex3` env var is still in-play and these dogfood PEXes (Pip and setuptools respectively) definitely don't have that script.

I'll review why the Pex PEX has that setting, but the short answer, is you can't use the Pex PEX for anything but running `pex ... ` (i.e.: building a PEX file) safely today.
It turns out that the Pip dogfood PEX guarded against this from day 1 and its only the PEP-518 build system dogfood PEXes that do not guard against this; as such, the practical upshot is exactly and only `PEX_SCRIPT=pex3 pex lock create` where there is a local project - which Pex must create an sdist for to get a consistent project hash - will lead to this error.

Resolving patch:
diff --git a/pex/build_system/pep_518.py b/pex/build_system/pep_518.py
--- a/pex/build_system/pep_518.py
+++ b/pex/build_system/pep_518.py
@@ -13,6 +13,7 @@
 from pex.result import Error
 from pex.tracer import TRACER
 from pex.typing import TYPE_CHECKING
+from pex.variables import ENV
 from pex.venv.bin_path import BinPath
 
 if TYPE_CHECKING:
@@ -76,13 +77,15 @@ def create(
         pex_builder.freeze(bytecode_compile=False)
         venv_pex = ensure_venv(PEX(pex_builder.path()))
 
-        env = os.environ.copy()
-        if extra_env:
-            env.update(extra_env)
-
-        return cls(
-            venv_pex=venv_pex, build_backend=build_backend, requires=tuple(requires), env=env
-        )
+        # Ensure all PEX* env vars are stripped except for PEX_ROOT and PEX_VERBOSE. We want folks
+        # to be able to steer the location of the cache and the logging verbosity, but nothing else.
+        # We control the entry-point, etc. of the PEP-518 build backend venv for internal use.
+        with ENV.strip().patch(PEX_ROOT=ENV.PEX_ROOT, PEX_VERBOSE=str(ENV.PEX_VERBOSE)) as env:
+            if extra_env:
+                env.update(extra_env)
+            return cls(
+                venv_pex=venv_pex, build_backend=build_backend, requires=tuple(requires), env=env
+            )
 
     venv_pex = attr.ib()  # type: VenvPex
     build_backend = attr.ib()  # type: str
diff --git a/scripts/package.py b/scripts/package.py
--- a/scripts/package.py
+++ b/scripts/package.py
@@ -11,13 +11,16 @@
 from pathlib import Path, PurePath
 from typing import Tuple
 
-import toml
-
 PROJECT_METADATA = Path("pyproject.toml")
 DIST_DIR = Path("dist")
 
 
 def python_requires() -> str:
+    # N.B.: We run this script directly from integration tests where toml is not needed; so we lazy
+    # import to allow for this direct running of the script without dependency installation by tox
+    # in ITs.
+    import toml
+
     project_metadata = toml.loads(PROJECT_METADATA.read_text())
     return project_metadata["tool"]["flit"]["metadata"]["requires-python"].strip()
 
@@ -93,9 +96,12 @@ def build_pex_dists(dist_fmt: Format, *additional_dist_fmts: Format, verbose: bo
 
 
 def main(
-    *additional_dist_formats: Format, verbosity: int = 0, local: bool = False, serve: bool = False
+    *additional_dist_formats: Format,
+    verbosity: int = 0,
+    pex_output_file: Path = DIST_DIR / "pex",
+    local: bool = False,
+    serve: bool = False
 ) -> None:
-    pex_output_file = DIST_DIR / "pex"
     print(f"Building Pex PEX to `{pex_output_file}` ...")
     build_pex_pex(pex_output_file, local, verbosity)
 
@@ -149,6 +155,12 @@ def main(
         action="append",
         help="Package Pex in additional formats.",
     )
+    parser.add_argument(
+        "--pex-output-file",
+        default=DIST_DIR / "pex",
+        type=Path,
+        help="Build the Pex PEX at this path.",
+    )
     parser.add_argument(
         "--local",
         default=False,
@@ -166,6 +178,7 @@ def main(
     main(
         *(args.additional_formats or ()),
         verbosity=args.verbosity,
+        pex_output_file=args.pex_output_file,
         local=args.local,
         serve=args.serve
     )


Test patch:
diff --git a/tests/build_system/test_pep_518.py b/tests/build_system/test_pep_518.py
--- a/tests/build_system/test_pep_518.py
+++ b/tests/build_system/test_pep_518.py
@@ -13,6 +13,7 @@
 from pex.resolve.configured_resolver import ConfiguredResolver
 from pex.result import Error
 from pex.typing import TYPE_CHECKING
+from pex.variables import ENV
 
 if TYPE_CHECKING:
     from typing import Any, Optional, Union
@@ -71,3 +72,18 @@ def test_load_build_system_pyproject(
     subprocess.check_call(
         args=[build_system.venv_pex.pex, "-c", "import {}".format(build_system.build_backend)]
     )
+
+
+def test_load_build_system_env_strip_issue_1872(
+    tmpdir,  # type: Any
+    pex_project_dir,  # type: str
+):
+    # type: (...) -> None
+
+    pex_root = os.path.join(str(tmpdir), "pex_root")
+    with ENV.patch(PEX_ROOT=pex_root, PEX_VERBOSE="2", PEX_SCRIPT="pex3"):
+        build_system = load_build_system(pex_project_dir)
+        assert isinstance(build_system, BuildSystem)
+        assert pex_root == build_system.env["PEX_ROOT"]
+        assert "2" == build_system.env["PEX_VERBOSE"]
+        assert "PEX_SCRIPT" not in build_system.env
diff --git a/tests/integration/build_system/test_pep_517.py b/tests/integration/build_system/test_pep_517.py
--- a/tests/integration/build_system/test_pep_517.py
+++ b/tests/integration/build_system/test_pep_517.py
@@ -1,7 +1,6 @@
 # Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
 # Licensed under the Apache License, Version 2.0 (see LICENSE).
-import os.path
-import subprocess
+
 from typing import Callable
 
 import pytest
diff --git a/tests/integration/test_issue_1872.py b/tests/integration/test_issue_1872.py
new file mode 100644
--- /dev/null
+++ b/tests/integration/test_issue_1872.py
@@ -0,0 +1,63 @@
+# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
+# Licensed under the Apache License, Version 2.0 (see LICENSE).
+
+import os
+import subprocess
+import sys
+
+from pex.compatibility import PY3
+from pex.pep_440 import Version
+from pex.pep_503 import ProjectName
+from pex.resolve.locked_resolve import LocalProjectArtifact
+from pex.resolve.lockfile import json_codec
+from pex.resolve.resolved_requirement import Pin
+from pex.testing import PY37, ensure_python_interpreter, make_env
+from pex.typing import TYPE_CHECKING
+from pex.version import __version__
+
+if TYPE_CHECKING:
+    from typing import Any
+
+
+def test_pep_518_venv_pex_env_scrubbing(
+    tmpdir,  # type: Any
+    pex_project_dir,  # type: str
+):
+    # type: (...) -> None
+
+    # N.B.: The package script requires Python 3.
+    python = sys.executable if PY3 else ensure_python_interpreter(PY37)
+
+    package_script = os.path.join(pex_project_dir, "scripts", "package.py")
+    pex_pex = os.path.join(str(tmpdir), "pex")
+    subprocess.check_call(args=[python, package_script, "--local", "--pex-output-file", pex_pex])
+
+    lock = os.path.join(str(tmpdir), "lock.json")
+    subprocess.check_call(
+        args=[
+            # Although the package script requires Python 3 to create the Pex PEX, we should be
+            # able to execute the Pex PEX with any interpreter.
+            sys.executable,
+            pex_pex,
+            "lock",
+            "create",
+            pex_project_dir,
+            "-o",
+            lock,
+            "--indent",
+            "2",
+        ],
+        env=make_env(PEX_SCRIPT="pex3"),
+    )
+
+    lockfile = json_codec.load(lock)
+    assert 1 == len(lockfile.locked_resolves)
+
+    locked_resolve = lockfile.locked_resolves[0]
+    assert 1 == len(locked_resolve.locked_requirements)
+
+    locked_requirement = locked_resolve.locked_requirements[0]
+    assert Pin(ProjectName("pex"), Version(__version__)) == locked_requirement.pin
+    assert isinstance(locked_requirement.artifact, LocalProjectArtifact)
+    assert pex_project_dir == locked_requirement.artifact.directory
+    assert not locked_requirement.additional_artifacts