Python shebang 和换行符

标签 python bash shebang

要使 Python 脚本在 Linux 和 bash 上可执行,可以使用 shebang

#! /usr/bin/env python

作为脚本的第一行。如果这一行恰好以 Windows 风格的换行符\r\n(回车 - 换行)结束,而不是 Unix 风格的换行符\n,那么 bash 将无法通过 Python 解释器运行脚本。

我正在使用 Python 进行跨平台开发。当我在 Windows 中工作时,自然的换行符是\r\n。当我在 Linux 中工作时,自然的换行符是\n。鉴于我使用 Mercurial 进行版本控制,在包含 shebang 的脚本文件中强制使用\n 换行符的最佳方法是什么?

最佳答案

通常的做法是根本不自己生成外包装脚本,而是在你的setup.py中指定它们,让它们在安装包时生成。

如果您执行以下操作:

setup(
    entry_points = {
        "console_scripts": [
            "script_name": "your.module.name:main",
        ],
    }
)

...然后,在安装时,将生成并安装一个名为 script_name 的包装器,并对其进行适当配置以在您当前的平台(shebang line 和所有平台)上运行。这使得使用中的行尾字符没有实际意义。

关于Python shebang 和换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34459754/

相关文章:

Python 类 utcnow 未更新

python - 如何将原始指针传递给 Boost.Python?

bash - Bash 脚本中的 for 循环在处理第一行后退出

linux - 通过 bash 中的第一个字母从一个数组创建新数组

shell - #! 怎么办?谢邦工作?

Python Argparse 重用属性类型错误 : hasattr(): attribute name must be string

python - 无法从 Google App Engine 调用 Google Apps 脚本执行 API

linux - 使用 bash 为文件添加文件扩展名

shell - 如何动态选择 shebang 行中的解释器?

python - 不同版本 Python 的条件 shebang 行