python在合并图片到PDF文件过程中遇到的问题汇总,包括pip/pyinstaller等

刚开始在使用python命令时,命令行执行没报错,总是有个空行,然后仔细看环境变量,里面配置的PYTHON是另一个版本的,无效的,所以命令能找到,但无法正常执行代码。

于是在环境变量PATH里面,删掉了错误的选项,配置了PYTHON. 的路径变量

这个时候执行python --version 能正常出来版本号

F:\test>python --version Python 3.11.1

检测pip安装情况

由于在脚本中用到了图片处理,需要使用Pillow图像处理的支持,因此需要通过pip来安装,但在安装时却发现没有pip这个模块

\python.exe: No module named pip

python -m pip --version

https://pypi.org/project/pip/

python -m ensurepip

通过上述命令,都无法找到相应命令,最终通过访问网站,下载get-pip.py 来解决

下载get-pip.py

第一次使用这个地址,在浏览器里面直接打开了文件,复制出来后,保存文件get-pip.py 会发现这个文件不完整,所以失败了。

https://bootstrap.pypa.io/pip/get-pip.py 没用

接着更换下面这个地址,完全可以下载。 http://mirrors.aliyun.com/pypi/get-pip.py 可用

下载完成后,执行 python get-pip.py

提示是成功了,可是当你执行pip --version 却会报错。

F:\test>pip --version
Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "D:\tools\python\Scripts\pip.exe\__main__.py", line 4, in <module>
ModuleNotFoundError: No module named 'pip'

修改参数

找到文件python{x}._pth, {x}为版本号数字,比如3.11,这里就是311, 打开文件并在第一行插入以下代码

Lib\site-packages

pip报错问题解决

继续安装 Pillow(有报错)

pip install Pillow

F:\test>pip install Pillow
Collecting Pillow
  Downloading pillow-10.4.0-cp311-cp311-win_amd64.whl (2.6 MB)
     |████                            | 307 kB 6.7 kB/s eta 0:05:38ERROR: Exception:
Traceback (most recent call last):
  File "d:\tools\python\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 171, in _merge_into_criterion
    crit = self.state.criteria[name]
           ~~~~~~~~~~~~~~~~~~~^^^^^^
KeyError: 'pillow'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "d:\tools\python\Lib\site-packages\pip\_vendor\urllib3\response.py", line 438, in _error_catcher
    yield
  File "d:\tools\python\Lib\site-packages\pip\_vendor\urllib3\response.py", line 519, in read
    data = self._fp.read(amt) if not fp_closed else b""
           ^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 62, in read
    data = self.__fp.read(amt)
           ^^^^^^^^^^^^^^^^^^^
  File "http\client.py", line 465, in read
  File "socket.py", line 706, in readinto
  File "ssl.py", line 1278, in recv_into
  File "ssl.py", line 1134, in read
TimeoutError: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "d:\tools\python\Lib\site-packages\pip\_internal\cli\base_command.py", line 223, in _main
    status = self.run(options, args)
             ^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\cli\req_command.py", line 180, in wrapper
    return func(self, options, args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\commands\install.py", line 320, in run
    requirement_set = resolver.resolve(
                      ^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 121, in resolve
    self._result = resolver.resolve(
                   ^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 453, in resolve
    state = resolution.resolve(requirements, max_rounds=max_rounds)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 318, in resolve
    name, crit = self._merge_into_criterion(r, parent=None)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 173, in _merge_into_criterion
    crit = Criterion.from_requirement(self._p, requirement, parent)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 82, in from_requirement
    if not cands:
  File "d:\tools\python\Lib\site-packages\pip\_vendor\resolvelib\structs.py", line 124, in __bool__
    return bool(self._sequence)
           ^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 99, in __bool__
    return any(self)
           ^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\resolution\resolvelib\factory.py", line 239, in iter_index_candidates
    candidate = self._make_candidate_from_link(
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\resolution\resolvelib\factory.py", line 167, in _make_candidate_from_link
    self._link_candidate_cache[link] = LinkCandidate(
                                       ^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\resolution\resolvelib\candidates.py", line 296, in __init__
    super(LinkCandidate, self).__init__(
  File "d:\tools\python\Lib\site-packages\pip\_internal\resolution\resolvelib\candidates.py", line 144, in __init__
    self.dist = self._prepare()
                ^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\resolution\resolvelib\candidates.py", line 222, in _prepare
    dist = self._prepare_distribution()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\resolution\resolvelib\candidates.py", line 307, in _prepare_distribution
    return self._factory.preparer.prepare_linked_requirement(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\operations\prepare.py", line 480, in prepare_linked_requirement
    return self._prepare_linked_requirement(req, parallel_builds)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\operations\prepare.py", line 503, in _prepare_linked_requirement
    local_file = unpack_url(
                 ^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\operations\prepare.py", line 253, in unpack_url
    file = get_http_url(
           ^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\operations\prepare.py", line 130, in get_http_url
    from_path, content_type = download(link, temp_dir.path)
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\network\download.py", line 163, in __call__
    for chunk in chunks:
  File "d:\tools\python\Lib\site-packages\pip\_internal\cli\progress_bars.py", line 168, in iter
    for x in it:
  File "d:\tools\python\Lib\site-packages\pip\_internal\network\utils.py", line 64, in response_chunks
    for chunk in response.raw.stream(
  File "d:\tools\python\Lib\site-packages\pip\_vendor\urllib3\response.py", line 576, in stream
    data = self.read(amt=amt, decode_content=decode_content)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_vendor\urllib3\response.py", line 512, in read
    with self._error_catcher():
  File "contextlib.py", line 155, in __exit__
  File "d:\tools\python\Lib\site-packages\pip\_vendor\urllib3\response.py", line 443, in _error_catcher
    raise ReadTimeoutError(self._pool, None, "Read timed out.")
pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out.
WARNING: You are using pip version 20.3.4; however, version 24.2 is available.
You should consider upgrading via the 'd:\tools\python\python.exe -m pip install --upgrade pip' command.

再次安装 Pillow(有报错)

尝试升级pip

python -m pip install --upgrade pip

升级成功过后,再重试安装,还是报错

ERROR: Exception:
Traceback (most recent call last):
  File "d:\tools\python\Lib\site-packages\pip\_vendor\urllib3\response.py", line 438, in _error_catcher
    yield
  File "d:\tools\python\Lib\site-packages\pip\_vendor\urllib3\response.py", line 561, in read
    data = self._fp_read(amt) if not fp_closed else b""
           ^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_vendor\urllib3\response.py", line 527, in _fp_read
    return self._fp.read(amt) if amt is not None else self._fp.read()
           ^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 98, in read
    data: bytes = self.__fp.read(amt)
                  ^^^^^^^^^^^^^^^^^^^
  File "http\client.py", line 465, in read
  File "socket.py", line 706, in readinto
  File "ssl.py", line 1278, in recv_into
  File "ssl.py", line 1134, in read
TimeoutError: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "d:\tools\python\Lib\site-packages\pip\_internal\cli\base_command.py", line 105, in _run_wrapper
    status = _inner_run()
             ^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\cli\base_command.py", line 96, in _inner_run
    return self.run(options, args)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\cli\req_command.py", line 67, in wrapper
    return func(self, options, args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\commands\install.py", line 379, in run
    requirement_set = resolver.resolve(
                      ^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 179, in resolve
    self.factory.preparer.prepare_linked_requirements_more(reqs)
  File "d:\tools\python\Lib\site-packages\pip\_internal\operations\prepare.py", line 554, in prepare_linked_requirements_more
    self._complete_partial_requirements(
  File "d:\tools\python\Lib\site-packages\pip\_internal\operations\prepare.py", line 469, in _complete_partial_requirements
    for link, (filepath, _) in batch_download:
  File "d:\tools\python\Lib\site-packages\pip\_internal\network\download.py", line 184, in __call__
    for chunk in chunks:
  File "d:\tools\python\Lib\site-packages\pip\_internal\cli\progress_bars.py", line 55, in _rich_progress_bar
    for chunk in iterable:
  File "d:\tools\python\Lib\site-packages\pip\_internal\network\utils.py", line 65, in response_chunks
    for chunk in response.raw.stream(
  File "d:\tools\python\Lib\site-packages\pip\_vendor\urllib3\response.py", line 622, in stream
    data = self.read(amt=amt, decode_content=decode_content)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\tools\python\Lib\site-packages\pip\_vendor\urllib3\response.py", line 560, in read
    with self._error_catcher():
  File "contextlib.py", line 155, in __exit__
  File "d:\tools\python\Lib\site-packages\pip\_vendor\urllib3\response.py", line 443, in _error_catcher
    raise ReadTimeoutError(self._pool, None, "Read timed out.")
pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out.

安装成功

找了些资料,最终确定是由于下载源网络的原因,有些依赖可能无法下载,因此更换了下载源,改为 https://pypi.tuna.tsinghua.edu.cn/simple

pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
python -m pip install --upgrade pip

重新执行pip install Pillow 成功

再去执行脚本,就完全没问题了。

合并图片到PDF

我这里的需求是

根据图片文件夹里面的图片,按顺序合并到一个PDF文件里面

代码如下:

from PIL import Image
import os
def images_to_pdf(input_dir,output_path):
	print(input_dir)
	print(output_path) 
	image_files = [f for f in os.listdir(input_dir) if 
		f.endswith('.png') or f.endswith('.jpg')] 
	print(image_files) 
	images = [] 
	for image_path in image_files: 
		image_path = os.path.join(input_dir, image_path) 
		image = Image.open(image_path) 
		images.append(image.convert("RGB")) 
	images[0].save(output_path, save_all=True, append_images=images[1:])
input_dir = input("请输入图片所在路径:")
output_path = input("请输入生成文件名:")
images_to_pdf(input_dir, output_path)

打包EXE

python打包exe,需要先安装pyinstaller

pip install pyinstaller

打包操作 pyinstaller --onefile tool.py

生成的exe文件默认位置是当前目录下的dist文件夹下。