Setting default interpreter for a python script

淺唱寂寞╮ 提交于 2019-12-14 01:47:44

问题


I am using a module that can only be found in python 2.7, so when I run my script I have to specify python2.7 script instead of just script. I know there are bigger issues out there, but still I was wondering - is it possible, when writing a python script, to set the interpreter to 2.7 by default? Maybe by setting #! /usr/bin/env python for example?


回答1:


Most unix environments will have the python2.7 executable, such that you can write:

#!/usr/bin/env python2.7

Obviously this doesn't help much on windows. You can also at least check the python version once you are started, although it won't help you run the later version if it is available:

import sys
print sys.version_info
...really do checks here...



回答2:


Using the shebang is an appropriate way to specify this, yes. Find out where python2.7 is in your PATH using which python2.7. This is e.g. /usr/bin/python2.7. You then set the shebang:

#!/usr/bin/python2.7

Of course, this only works on those systems where Python 2.7 is available at this location :) This will also work on may systems: /usr/bin/env python2.7

Then make the script executable and fire it off using $ ./wonderful_python_script.py.




回答3:


If you are using Windows, install Python 3.3, which features a new launcher that provides shebang support under Windows. This will give you a (finally!) sane and cross-platform way of explicitly specifying interpreter versions.



来源:https://stackoverflow.com/questions/12374307/setting-default-interpreter-for-a-python-script

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