我们应该忽略 .python-version 文件吗?

Should we gitignore the .python-version file?

我有一个 .python-version 文件,当我用 github 创建一个 Python 存储库并指定它应该有一个 .gitignore 时,它添加了 .python-version 文件。在我看来,不应忽略该文件,因为其他人 运行 不同机器上的代码会想知道他们需要什么版本的 Python。

那为什么是 .gitignored?

.python-version 应该被 gitignore 的原因是因为它的版本太具体了。 Python 的微型版本(例如 2.7.1 与 2.7.2)通常彼此兼容,因此您不想锁定特定的微型版本。此外,许多 Python 应用程序或库应该适用于一系列 Python 版本,而不仅仅是特定版本。使用 .python-version 表示您希望其他开发人员使用精确的、特定的 Python 版本,这通常不是一个好主意。

如果您想指明所需的最低 Python 版本,或者版本范围,那么我认为在 README 中记录是更合适的解决方案。

虽然过于具体,但您仍然可以对该文件进行版本控制(意思是:不将其包含在默认 .gitignore 中),如:

  • 它只会被pyenv
  • 使用
  • 它是对README的一个很好的补充,为了说明python针对特定项目推荐的版本,
  • 它可以很容易地被覆盖(如果你正在使用 pyenv),或者简单地被忽略(如果你没有 pyenv)。

正如文章“How to manage multiple Python versions and virtual environments ”所述:

When setting up a new project that is to use Python 3.6.4 then pyenv local 3.6.4 would be ran in its root directory.
This would both set the version, and create a .python-version file, so that other contributors’ machines would pick it up.

但是:

pyenv looks in four places to decide which version of Python to use, in priority order:

  1. The PYENV_VERSION environment variable (if specified).
    You can use the pyenv shell command to set this environment variable in your current shell session.
  2. The application-specific .python-version file in the current directory (if present).
    You can modify the current directory's .python-version file with the pyenv local command.
  3. The first .python-version file found (if any) by searching each parent directory, until reaching the root of your filesystem.
  4. The global version file. You can modify this file using the pyenv global command.
    If the global version file is not present, pyenv assumes you want to use the "system" Python. (In other words, whatever version would run if pyenv weren't in your PATH.)

好的,先生,我认为您问题的答案是 YES。我刚刚打开 GitHub 官方回购并检查了项目 gitignore.

它显示了那里提到的 .python-version 文件。

如果它没有被忽略,您只需检查提及的正确方式即可。

使用 python 虚拟环境时也会出现一些问题,因为人们可能希望使用不同于 3.7.2/envs/myvenv 的虚拟环境名称。

旧 post 但仍然相关。

我的回答是“视情况而定”。

如果借助pyenv 的virtualenv 插件进行管理,虚拟环境的名称也可以在.python-version 中使用。如果项目是在 public Git 存储库上管理的,并且您可以将其排除在外(但如其他答案所述,不这样做是无害的),这会使该文件变得毫无用处。

但是(我正处于这种情况)如果您在私人仓库上管理项目并共享虚拟环境,那么不将其排除在 Git 之外是有意义的。这允许您在项目的实验分支上使用不同的环境(包括 Python 版本)。当然,分叉或克隆原始项目并在副本中试验新的环境会干净得多,但有时只创建一个新分支会更容易。

归根结底,恕我直言,这个问题没有通用的答案,这取决于您的工作流程。