[英]Run a UNIX script to use different versions of python
I have a UNIX script which is used to initialize the environment and properties of the project.我有一个 UNIX 脚本,用于初始化项目的环境和属性。 It uses python. I had to refer the path.
它使用 python。我不得不参考路径。 This will be used as a common file and used across multiple developers.
这将用作通用文件并在多个开发人员之间使用。 Few of the machines uses Python 1.x and 2.x.
很少有机器使用 Python 1.x 和 2.x。 Few others uses only Python 3.x.
很少有人只使用 Python 3.x。
So /usr/bin/python
works for the machines run Python 1.x but it fails in machines running python 3.x.所以
/usr/bin/python
适用于运行 Python 1.x 的机器,但它在运行 python 3.x 的机器上失败。 I have to explicitly change it to /usr/bin/python3
to make it work.我必须明确地将其更改为
/usr/bin/python3
才能使其正常工作。
How can I handle the situation to make the script run independent of the python version installed.我该如何处理这种情况才能使脚本独立于安装的 python 版本运行。
Python 1 or 2 are dead obviously, but I'll try to answer your question Python 1 或 2 显然已经死了,但我会尽量回答你的问题
In this this case you should have seprate binaries for each python version, similar to:在这种情况下,每个 python 版本都应该有单独的二进制文件,类似于:
In your script define the version you want to use using shebang在您的脚本中使用shebang定义您要使用的版本
For example make a file my_old_script.py
:例如制作一个文件
my_old_script.py
:
#!/usr/bin/python2
import sys
print(sys.version)
Give the script execution permission:给脚本执行权限:
chmod +x my_old_script.py
Then execute it without specifying an interpreter:然后在不指定解释器的情况下执行它:
./my_old_script.py
output: output:
2.7.17 (default)
[GCC 7.5.0]
Python2 is dead (less so that python1, but still dead), so it should be less and less of an issue. Python2 已经死了(不像 python1 那样,但仍然死了),所以它应该越来越不是一个问题。 If you are worried about python2/3 compatibility, there is six and most things have been backported through the
__future__
module, hopefully those two should be enough for your use cases.如果您担心 python2/3 兼容性,有六个,并且大部分内容已通过
__future__
模块向后移植,希望这两个应该足以满足您的用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.