What type of line breaks does a Python script normally have?

自闭症网瘾萝莉.ら 提交于 2019-12-23 20:43:09

问题


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


来源:https://stackoverflow.com/questions/6907245/what-type-of-line-breaks-does-a-python-script-normally-have

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