python - 如何让 Shebang 能够在 python3 和 python3.5 之间选择正确的 Python 解释器

标签 python bash python-3.x shell shebang

我正在用 python3 开发一组脚本,因为我使用这个:

#!/usr/bin/env python3

一切正常,但在一些执行的虚拟机中,解释器的名称是python3.5。我希望能够在两种环境中执行我的脚本,但我无法更改虚拟机的文件系统(因此我放弃了解决方案,例如从 python3.5 到 python3 建立链接)

我查看了 man of env 但我没有找到任何方法来指定搜索模式或类似的东西。

我尝试在我的 session 开始时设置一个 别名 指向正确的 python 解释器,但 env 不使用它。

我独特的解决方案是调用我的脚本说明必须使用哪个解释器但非常烦人:

python3.5 myscript.py

欢迎任何想法!谢谢!

最佳答案

无需引入单独的 shell 和 python 脚本,一个文件即可!

用这个序列替换你的 shebang 行:

#!/bin/sh

# Shell commands follow
# Next line is bilingual: it starts a comment in Python, and is a no-op in shell
""":"

# Find a suitable python interpreter (adapt for your specific needs) 
for cmd in python3.5 python3 /opt/myspecialpython/bin/python3.5.99 ; do
   command -v > /dev/null $cmd && exec $cmd $0 "$@"
done

echo "OMG Python not found, exiting!!!!!11!!eleven" >2

exit 2

":"""
# Previous line is bilingual: it ends a comment in Python, and is a no-op in shell
# Shell commands end here
# Python script follows (example commands shown)

import sys
print ("running Python!")
print (sys.argv)

关于python - 如何让 Shebang 能够在 python3 和 python3.5 之间选择正确的 Python 解释器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47882916/

相关文章:

Python反向迭代分割单词

python - 如果一个家庭不平衡,如何编写一个函数来获取?

python - 添加具有相同键的值

python - 如何使用 NumPy 将单色噪声添加到 PyGame 表面?

python - python中tkinter中的 'width'和 'padx'有什么区别?

ruby - Git post-receive hook不使用rbenv指定的ruby版本

linux - 如何使用 bash 脚本在日期/时间和另一个日期/时间之间提取日志

linux - grep 输出的 Bash 脚本案例菜单

python-3.x - python pdfminer 将 pdf 文件转换为一大块字符串,单词之间没有空格

Python 键盘模块在循环内无法正常工作