不同版本 Python 的条件 shebang 行

2022-01-20 00:00:00 python conditional shebang

问题描述

尝试在两台不同的计算机上运行 python 脚本时遇到问题.在每台计算机上,我想使用 python 版本 2.7.3 运行脚本,但是我遇到的问题是两台计算机以不同的方式命名 python 2.7.3.其中一台计算机运行arch linux,在这台计算机上它被命名为python2.另一台计算机正在运行redhat linux,它使用名称python2.7.3.

I have a problem when trying to run a python script on two different computers. On each computer I would like to run the script using python version 2.7.3 however the problem I am having is that the two computers name python 2.7.3 in different ways. One of the computers runs arch linux and on this computer it is named python2. The other computer is running redhat linux and it uses the name python2.7.3.

我应该在 shebang 行中使用什么,以便脚本可以在两台计算机上执行而无需任何更改?我真正想要的是某种可以选择使用哪个版本的 Python 的有条件的 shebang 行.我是不是运气不好,必须保留两个不同版本的脚本?

What should I use in the shebang line so that the script is executable on both computers without requiring any changes? What I really want is some sort of conditional shebang line that could choose which version of Python to use. Am I just out of luck and I have to keep two different versions of the script?

附:我不能只使用 #!/usr/bin/env python,因为在 arch linux 计算机上它指的是 python 3.2.3,而在 redhat linux 计算机上它是指 python 2.4.

P.S. I can't just use #!/usr/bin/env python as on the arch linux computer this would refer to python 3.2.3 and on the redhat linux computer it would refer to python 2.4.


解决方案

您可以编写一个小包装脚本,查看不同版本的 python 可执行文件并使用它找到的那个.

You can write a small wrapper script that looks through different versions of python executables and uses the one it finds.

例如:

#!/bin/sh -e
pythons=('python2', 'python2.7.3')
for py_exec in ${pythons[@]}; do
    py_exec="/usr/bin/$py_exec"
    if [[ -f $py_exec ]]; then
        exec $py_exec $1
    fi
done

当然,此脚本只是一个开始示例,您当然可以通过多种方式对其进行改进.请务必让您了解我的意思.

Of course this script is just a start sample, you could surely improve it in many ways. Just do give you an idea of what I mean.

相关文章