适用于不同版本Python的条件shebang行 [英] Conditional shebang line for different versions of Python

查看:86
本文介绍了适用于不同版本Python的条件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行中应该使用什么,以便脚本在两台计算机上都可以执行而无需任何变化?我真正想要的是某种有条件的shebang行,可以选择要使用的Python版本。我是不是很幸运,必须保留两个不同版本的脚本?

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?

P.S。我不能只使用#!/ 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.

这篇关于适用于不同版本Python的条件shebang行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆