Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding, when trying to start uwsgi

Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding, when trying to start uwsgi

我试图在我的虚拟环境中启动我的 uwsgi 服务器,但在我添加 plugin python3 选项后,我每次都会收到此错误:

!!! Python Home is not a directory: /home/env3/educ !!!
Set PythonHome to /home/env3/educ
Python path configuration:
  PYTHONHOME = '/home/env3/educ'
  PYTHONPATH = (not set)
  program name = '/home/env3/educ/bin/python'
  isolated = 0
  environment = 1
  user site = 1
  import site = 1
  sys._base_executable = '/home/env3/educ/bin/python'
  sys.base_prefix = '/home/env3/educ'
  sys.base_exec_prefix = '/home/env3/educ'
  sys.executable = '/home/env3/educ/bin/python'
  sys.prefix = '/home/env3/educ'
  sys.exec_prefix = '/home/env3/educ'
  sys.path = [
    '/home/env3/educ/lib/python38.zip',
    '/home/env3/educ/lib/python3.8',
    '/home/env3/educ/lib/python3.8/lib-dynload',
  ]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007efe89db8780 (most recent call first):
<no Python frame>

我还尝试使用 python3 -m venv env 创建新的虚拟环境并将项目文件移至其中,但仍然出现相同的错误。 这是我的 uwsgi.ini 文件:

[uwsgi]

base = /home/env3/educ
projectname = educ

plugins = python3
master = true
virtualenv = /home/env3/%(projectname)
pythonpath = %(base)
env = DJANGO_SETTINGS_MODULE=%(projectname).settings.pro
module = %(projectname).wsgi:application
socket = /tmp/%(projectname).sock
chmod-socket = 666

我用的是Python3.8.5

我正在尝试使用 Django + uWSGI + nginx + Postgresql。

我看到您的 PYTHONHOME 设置为 PYTHONHOME = '/home/env3/educ'。尝试检查它是否真的存在。

我的解决方案删除PYTHONHOME环境变量。 对您来说,它可以就是这样,或者将该变量设置为另一个值。 这适用于 Windows,并且肯定适用于 Linux。如果有人尝试这样做,请 post 在这里发表评论!

一位 CPython 开发人员确认了解决方案 here. :

This is not a Python bug, this is a symptom of setting PYTHONHOME and/or PYTHONPATH when they’re not needed. In nearly all cases you don’t need to set either of them;

In the case of PYTHONHOME it’s almost always a mistake to set.

我通过取消设置 PYTHONHOME 或 PYTHONPATH 来解决这个问题,因为它们会覆盖虚拟环境变量。

在我的例子中这是由我的管理员的基础环境引起的。我会尝试通过

删除 PYTHONHOME 和 PYTHONPATH 变量
unset PYTHONPATH
unset PYTHONHOME

此消息适用于遇到相同问题的人,他们稍后会找到此页面。 我无法使用我的配置启动 uWSGI,并且我在日志文件中收到了相同的消息。

init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings'

问题是 uWSGI 没有足够的权限访问虚拟环境。当我修复权限后,uWSGI 开始了我的配置。

Denys 在他的消息中发布了 uwsgi.ini 配置。估计是虚拟环境的路径不对

base = /home/env3/educ
projectname = educ
virtualenv = /home/env3/%(projectname)

如果虚拟环境是在项目目录下创建的,那么路径应该是这样的:

virtualenv = /home/env3/%(projectname)/env

我的问题出在virtualenv的设置上。在 linux 系统下,virtualenv 的路径很可能以 /home/(您的登录用户名)/env3/ 开始,而不是 /home/env3/。所以在你尝试其他解决方案之前,你最好确保你的 virtualenv 的路径是正确的。