使用不同的Python版本

我正在使用一台我没有管理员访问权限的服务器。安装了几个版本的Python。比如一个在/some/home/directory/Python2.6/,另一个在/some/home/directory/Python2.7/

有没有一种简单的方法可以在终端临时更改Python版本,而不改变默认的Python版本,并且不需要获取root权限(到目前为止,我找到的所有答案都要求满足其中一种条件)?


2使用virtualenv - muru
4个回答

要更改终端会话的Python版本,您可以在.bashrc文件中创建一个别名,然后重新登录。
alias python='/usr/bin/python3.4'

以下文章的链接提供了详细的说明,以便在每个用户会话中更改为其他Python版本

有没有想法这样的文件会在每个用户的哪里?(它会在主目录还是我的工作目录中?)或者,通过终端运行这个命令会改变当前会话中的Python版本吗? - hsnee
1通常你可以在用户账户的主目录中找到 .bashrc 文件,即 /home/username/.bashrc。你可以使用 vi 编辑该文件,只需输入 vi ~/.bashrc - nuwandame

我的建议是使用一个别名来“覆盖”python命令。

An alias can be created with the same name as the core name of a command (i.e., a command without any options or arguments). In such case, it is the alias that is called (i.e., activated) first when the name is used, rather than the command with the same name. For example, an alias named ls could be created for the command ls -al as follows:

alias ls="ls -al" 

ls is a commonly used command that by default lists the names of the files and directories within the current directory (i.e., the directory in which the user is currently working). The -a option instructs ls to also show any hidden files and directories, and the -l option tells it to provide detailed information about each file and subdirectory.

Such an alias can be disabled temporarily and the core command called by preceding it directly (i.e., with no spaces in between) with a backslash, i.e.,

\ls 
linfo.org中获取

在你的程序中,如果你在第一行提到#!/usr/bin/python2.6,那么你的程序将把python 2.6视为其运行环境。同样地,如果你提到python2.7,它将从python2.7开始考虑。
如果你想从终端访问python,你可以在终端输入python2.7,然后你就可以进入它了。

1NB: #!/usr/bin/env python2.7 可能比直接输入 Python 路径更好,也使您的代码更具可移植性。 - user201155

根据评论的说法,虚拟环境管理你所拥有的所有 Python - 只需使用它

# install pip and venv as user
python3 -m pip install --user --upgrade pip
python3 -m pip install --user virtualenv

#create the virtual env files and folders in the current dir
python3 -m venv env

# activate the virtual env by sourcing the bin file
source env/bin/activate

#confirm it
which python