Meysam Meysam - 10 months ago 67
Python Question

pytest running with another version of python

I've installed

and have different versions of python installed with it:

$ pyenv versions
* 3.5.2

I use the following command to switch to
python 3.5.2

pyenv shell 3.5.2

And when I check the python version this is what I get:

$ python --version
Python 3.5.2

But when I run
, it still runs under
python 2.7.6

pytest -v

==================================================================== test session starts ====================================================================

platform linux2 -- Python 2.7.6, pytest-3.0.3, py-1.4.31, pluggy-0.4.0 -- /usr/bin/python

Why is
running under the older version?

Answer Source

Bottom line: run

  • python -m pytest, or
  • py.test-<version> if your pytest has it.

As I can see, /usr/bin/pytest (that belongs to the system package manager's python-pytest package) has a shebang !#/usr/bin/python since it corresponds to the system python's installation.

pyenv, as its says, does not replace /usr/bin/python - because it indeed should not be replaced to avoid breaking system packages.

Instead, it adds its directory to PATH and inserts a launcher there which is what gets invoked when you type "python". As you probably guessed, this hack is ignored by a shebang like the above - as it should.

Running python -m pytest will make whichever python that launches itself use the package from its installation.

Alternatively, pytest for your other Python version may include versioned executables on the PATH named py.test-<version> (e.g. py.test-3 or py.test-3.6) depending on the way you installed it.

  • If it's from a system package manager's package for nonstandard python - like python36-pytest - this is virtually guaranteed.
  • I checked that if you install a version with pip, it only creates an unversioned executable (though you can create a versioned one yourself). Moreover, if you install the same package for a different Python version but with the same --prefix, it will overwrite the existing one's executable.

To summarize, pyenv only switches the main python executable, not ones for its various packages. So, it doesn't help you "switch" the pytest command in any way, you're on your own here as far as it's concerned.