TypeError:使用Pyinstaller转换.py时,预期的str,字节或os.PathLike对象,而不是WindowsPath

问题描述

在尝试使用Pyinstaller构建.exe时,会引发此错误

    133235 INFO: Loading module hook 'hook-matplotlib.backends.py' from 'c:\\users\\jimit vaghela\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\PyInstaller\\hooks'...
Traceback (most recent call last):
  File "<string>",line 1,in <module>
  File "c:\users\jimit vaghela\appdata\local\programs\python\python37\lib\site-packages\matplotlib\__init__.py",line 901,in <module>
    fail_on_error=True)
  File "c:\users\jimit vaghela\appdata\local\programs\python\python37\lib\site-packages\matplotlib\__init__.py",line 796,in _rc_params_in_file
    with _open_file_or_url(fname) as fd:
  File "c:\users\jimit vaghela\appdata\local\programs\python\python37\lib\contextlib.py",line 112,in __enter__
    return next(self.gen)
  File "c:\users\jimit vaghela\appdata\local\programs\python\python37\lib\site-packages\matplotlib\__init__.py",line 770,in _open_file_or_url
    fname = os.path.expanduser(fname)
  File "c:\users\jimit vaghela\appdata\local\programs\python\python37\lib\ntpath.py",line 291,in expanduser
    path = os.fspath(path)
TypeError: expected str,bytes or os.pathLike object,not WindowsPath
134074 INFO: Loading module hook 'hook-matplotlib.py' from 'c:\\users\\jimit vaghela\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\PyInstaller\\hooks'...
Traceback (most recent call last):
  File "<string>",not WindowsPath

我在Stackoverflow上发现了一个解决方案,该解决方案指出需要在Pyinstaller文件夹的backend.py中插入代码。但这也不起作用。

这是怎么回事?

解决方法

因此,我发现问题是matplotlib。在Pyinstaller的module参数中排除该错误即可解决。

赞:

pyinstaller --exclude-module matplotlib main.py

,

这是当前 matplotlib 的问题。

我通过编辑源文件解决了这个问题。如果不想编辑源文件,据说可以安装低版本的matplotlib3.0.3来解决这个问题。

我的情况是没有用。无论如何,以下是我采取的步骤。

首先打开 Python 解释器并复制您作为输出获得的路径。

>>> import matplotlib
>>> matplotlib.get_data_path() # copy the below path
'C:\\<Python Path>\\lib\\site-packages\\matplotlib\\mpl-data'

接下来,打开文件 C:\<Python Path>\lib\site-packages\PyInstaller\hooks\hook-matplotlib.py。为了安全起见,如果需要,请备份此文件

from PyInstaller.utils.hooks import exec_statement

# old line; delete this
mpl_data_dir = exec_statement(
    "import matplotlib; print(matplotlib.get_data_path())")

# Add this line
mpl_data_dir = 'C:\\<Python Path>\\lib\\site-packages\\matplotlib\\mpl-data'

assert mpl_data_dir,"Failed to determine matplotlib's data directory!"

datas = [
    (mpl_data_dir,"matplotlib/mpl-data"),]

别忘了保存。