python - 使用小版本特性时如何写shebang

标签 python python-3.x posix shebang

例如:

testvar = "test"
print(f"The variable contains \"{testvar}\"")

格式化字符串字面量是在python3.6中引入的

如果我使用 #!/usr/bin/env python3,如果安装了旧版本的 python,它会抛出语法错误。
如果我使用 #!/usr/bin/env python3.6,如果没有安装 python3.6,它将无法工作,但安装了较新的版本。

我如何确保我的程序在特定版本及更高版本上运行?如果使用 python3,我无法检查版本,因为它甚至无法在较低版本上启动。

编辑:

我不是说如何运行它,当然你可以明确地说“用 python3.6 及更高版本运行它”,但确保程序只在特定版本上运行的正确方法是什么 <使用 ./scriptname.py 时,strong>或更新

最佳答案

您需要将脚本拆分为 2 个模块以避免语法错误:第一个是检查 Python 版本并在 python 版本不工作时导入应用程序模块的入口点。

# main.py: entry point
import sys

if sys.version_info > (3, 6):
    import app
    app.do_the_job()
else:
    print("You need Python 3.6 or newer. Sorry")
    sys.exit(1)

还有一个:

# app.py
...
def do_the_job():
    ...
    testvar = "test"
    ...
    print(f"The variable contains \"{testvar}\"")

关于python - 使用小版本特性时如何写shebang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48786152/

相关文章:

python - 如何在双连接关系(或 : How to get around Django's restrictions on ManyToMany "through" models? )之后在 Django 中执行查询

python - 如何将操作节点的输出保存在Tensorflow训练的图中?

python - 合并 pandas 数据帧 : keep row redundancy while removing column redundancy

python - 如何基于pandas中的多个键进行映射而不合并

linux - 当进程被 fork 时会发生什么?

python - 无法在 opencv3.2(ubuntu,python3)中读取 mp4

python-3.x - 虽然true循环给我递归错误

python - 如何使用 python http.server 运行 CGI "hello world"

c++ - 如何使用 Boost 获取 POSIX 时区?

ruby - 正则表达式 "punct"字符类根据 Ruby 版本匹配不同的字符