从命令行设置 python 版本

Setting python version from command line

我正在尝试使用 Rscript 从命令行 运行 R 脚本。 R 脚本调用一些 python 代码并在 运行 交互时工作正常。但是,当我从 Rscript 调用它时,gdal 出现了一些错误。我相信这些错误与 python 3 vs 2 有关。例如,运行在交互式 R 会话中使用以下命令:

system("python --version)

产量

Python 2.7.9

同时 运行 从 shell 执行 "same" 命令:

$ python --version

产量

Python 3.5.1 :: Continuum Analytics, Inc.

如何将我的 $ Rscript "foo.R" 调用指向 python 2.7.9?

当您从 shell 命令行调用 $ python --version$ Rscript -e 'system("python --version")' 时,您是在 Python 虚拟环境中操作,可能是由 virtualenv.具体来说,您正在执行 /home/foo/miniconda3/bin/python

当您从 RStudio 运行 system("python --version") 时,您将获得系统默认版本。具体来说,您正在执行 /usr/bin/python.

How can I point my $ Rscript "foo.R" calls to python 2.7.9?

这取决于您进入虚拟 Python 环境的方式。如果它是由 virtualenv 创建的,只需停用它:

$ deactivate
$ Rscript -e 'system("python --version")'
2.7.9

编辑:您似乎正在使用 miniconda 创建的虚拟环境。如果是这种情况,您可以通过编辑 PATH 环境变量来使用系统默认值 Python。如何编辑 PATH 取决于您希望更改生效多长时间。

  • 如果您只用一个命令就丢失了,试试这个:

    $ PATH="$(echo "$PATH" | sed -e s,:/usr/local/sbin,,)" Rscript -e 'system("python --version")' 
    
  • 要使更改持续单个 shell 会话的持续时间,请尝试以下操作:

    $ PATH="$(echo "$PATH" | sed -e s,:/usr/local/sbin,,)"
    $ python --version
    $ Rscript -e 'system("python --version")' 
    
  • 要永久更改您的 PATH,请适当编辑文件 $HOME/.bashrc。您需要启动一个新的终端会话才能生效。

解决方案是在我的 R 脚本中插入对 methods 库的调用,并使用以下命令 create/load python 2 环境:

$ conda create --name python2 python=2
$ source activate python2

参见:
Rscript does not load methods package, R does -- why, and what are the consequences?

http://conda.pydata.org/docs/py2or3.html