Skip to content

Instantly share code, notes, and snippets.

@lenciel
Created October 26, 2012 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lenciel/3958996 to your computer and use it in GitHub Desktop.
Save lenciel/3958996 to your computer and use it in GitHub Desktop.
Line ending on different os.

Running a python script using:

python <file_name>.py

is always ok but trying to run it directly:

./<file_name>.py

You might see error messages. This is because each OS/system uses a different line termination character:

POSIX (any Unix-flavor like Linux, *BSD, Mac OS X, etc.) uses \n (NEWLINE) while DOS/Win uses the combo \r\n (CR/carriage return + NEWLINE) and old Mac OS 8 or 9 uses just CR or \r.

To solve the problem, we can run an utility like unix2dos/dos2unix, or do the convention from your text editor (may not be very apparent however).

The reason why $ python <file_name>.py works is because Python treats all three different line endings the same... the shebang line at the top is ignored because you told Python to load and run that script, and "#" means the first line is a comment and thus ignored.

When running it directly in the OS shell, it needs to parse that line and execute whatever interpreter you requested, but if it can't, it pukes on you like it did.

You can find out what line-termination character is being used on your operating system, just check out the os.linesep (data) attribute. for example, on my Mac (OS X), i get this:


>>> import os
>>> os.linesep
'\n'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment