问题
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