简体   繁体   English

如何指定python的版本来运行脚本?

[英]how to specify version of python to run a script?

I'm learning python now using a mac which pre-installed python 2.7.5.我现在正在使用预装了 python 2.7.5 的 mac 学习 python。 But I have also installed the latest 3.4.但是我也安装了最新的3.4。

I know how to choose which interpreter to use in command line mode, ie python vs python 3 will bring up the respective interpreter.我知道如何选择在命令行模式下使用哪个解释器,即 python vs python 3 将调出相应的解释器。

But if I just write a python script with this header in it "#!/usr/bin/python" and make it executable, how can I force it to use 3.4 instead of 2.7.5?但是,如果我只是编写一个带有此标头的 python 脚本“#!/usr/bin/python”并使其可执行,我如何强制它使用 3.4 而不是 2.7.5?

As it stands, print sys.version says:就目前而言,print sys.version 说:

2.7.5 (default, Aug 25 2013, 00:04:04) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] 2.7.5(默认,2013 年 8 月 25 日,00:04:04)[GCC 4.2.1 兼容 Apple LLVM 5.0 (clang-500.0.68)]

Set the shebang (script header) to the path to python3.4 which you can get using which .shebang (脚本头)设置为python3.4的路径,您可以使用which

For example, here's what do I have:例如,这是我有什么:

$ which python
/usr/bin/python
$ which python3.4
/usr/local/bin/python3.4

Then, just set the shebang appropriately:然后,只需适当设置shebang:

#!/usr/local/bin/python3.4

您知道,您可以使用py -specific version启动 python 要在具有特定版本的解释器上运行脚本,您只需使用以下参数启动脚本, py yourscript.py -version

You can add to the Python script a first line of:您可以在 Python 脚本中添加第一行:

#!/usr/bin/env python3

It is better than setting the path or the exact python 3 sub version if not needed.如果不需要,它比设置路径或确切的python 3子版本更好。

在python中,您可以使用:

py yourscript.py -version

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM