Activate different Python version in Terminal

风流意气都作罢 提交于 2019-12-23 01:28:28

问题


Just reformatted my Mac to Yosemite and installed Python 2 & 3 using Homebrew. I've also setup some aliases in my bash_profile file which allows me to activate which version of Python I want to use. So if I type p3, it'll launch the python3 shell.

I'm wondering if it's possible to activate a specific version of Python without it starting the Python shell? So if I bring any files into the Terminal for instance, it'll use the version which I've activated?

Cheers!

Apologies if this has been answered elsewhere, I had a good search but I couldn't find anything.


回答1:


Rather than writing your own scripts to manage different Python versions, I would suggest using a highly-used manager that has been tested in and out by the community: pyenv. With pyenv you can:

  1. Easily install several different Python versions from the command line with no issues of them fighting (pyenv install 3.4.2)

  2. Create virtual environments from any one of those versions if you want to compartmentalize the packages that are available (pyenv virtualenv 3.4.2 mypy3projectvenv), and

  3. Set specific environments or versions to be active either
    • globally (pyenv global [version-or-venv]),
    • locally in and below folders you configure (pyenv local [ver-or-venv]), usually useful for projects that you have at a specific version/virtualenv, and
    • local to the shell until closed (pyenv shell [ver-or-venv]) (this is perhaps most-similar to your putative p3 command.

After setting the Python you want to use, all Python-related calls are redirected to their appropriate target (e.g. python, pip, easy_install, ipython*, django-admin*). Don't execute the Python scripts with any special command, just call them normally (or prefix a standard #!/usr/bin/env python shebang)

*If installed in that version/virtualenv

If you use the pyenv-installer script:

curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer | bash

Then add the couple lines it tells you to your ~/.bash_profile script (and either source it or restart bash)...you'll be up and running in seconds. The trick is usually installing all the Python build dependencies with brew (sqlite, OpenSSH, zlib...), but after that then you're golden.



来源:https://stackoverflow.com/questions/26442959/activate-different-python-version-in-terminal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!