What type of line breaks does a Python script norm

2019-07-02 01:00发布

问题:

My boss keeps getting annoyed at me for having Windows line breaks in my Python scripts, but I can't for the life of me work out how they are causing him a problem.

Is '\r\n' the normal line-break for a Python script? Or does that only happen on IDLE for PC?

PS: OK, it seems when I write the script on a Mac that it has '\n's, but is there any way that '\r\n' will cause a problem?

Edit: OK... now I'm totally confused. When I interpret files written in Windows in Python they all spit out when I print lines to the screen as '\n'. Does the Python interpreter for Windows translate line-breaks?

回答1:

This has nothing to do with Python but with the underlying OS. If you save a text file on Windows, you get CRLF linebreaks, if you save it on Mac/Unix systems, you get LF linebreaks (and on stone-age Macs, CR linebreaks).

Use an editor that allows you to preserve the line break format of your files. No, Notepad doesn't, but most editors I've seen do. UltraEdit and EditPadPro are the ones I know, and I can recommend both. I'm pretty sure that IDEs like PyDev/Eclipse will handle that too, but I haven't tried.



回答2:

Make a Python script which replaces '\r\n' with '\n'

An run it every time you give the code to your boss.

:)



回答3:

I've had the same problem. Yes, doing a simple find-and-replace should fix this problem. However you'll have to do it every time you share code; you might want to think about automating it somehow. I never did do that myself.



回答4:

This sed one-liner will convert the Python script to have the desired line endings:

sed 's/\r\n/\n/g' <windows_script >unix_script