不同版本 Python 的条件 shebang 行

Conditional shebang line for different versions of Python(不同版本 Python 的条件 shebang 行)
本文介绍了不同版本 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 行中使用什么,以便脚本可以在两台计算机上执行而无需任何更改?我真正想要的是某种可以选择使用哪个版本的 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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)