Python shebang and newlines

女生的网名这么多〃 提交于 2019-11-30 18:43:58

问题


To make a Python script executable on Linux and bash, one uses the shebang

#! /usr/bin/env python

as the first line of the script. If this line happens to end with the Windows-style newline \r\n (carriage return - line feed), instead of the Unix-style newline \n, then bash will not be able to run the script through the Python interpreter.

I am doing cross-platform development in Python. When I work in Windows, the natural newline is \r\n. When I work in Linux, the natural newline is \n. Given that I use Mercurial for version control, what would be the best way to enforce the use of the \n newline in the script file containing the shebang?


回答1:


The common approach is not to generate the outer wrapper scripts yourself at all, but specify them in your setup.py and let them be generated during package installation.

If you do something like the following:

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

...then, on installation, a wrapper named script_name will be generated and installed, and configured appropriately to run on your current platform (shebang line and all). This makes the end-of-line characters in use moot.




回答2:


This problem is common to all scripts that are developed on non-native platforms, not just Python. Most SCM have automatic line ending conversion features. Mercurial can do this, but it's not the default. See the EOL Extension.




回答3:


You may want to check EolExtension out.

Using EolExtension, you can enforce a certain line ending for your repository. Files commited with different line endings get automatically converted.



来源:https://stackoverflow.com/questions/12713555/python-shebang-and-newlines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!