【发布时间】:2018-10-11 02:06:48
【问题描述】:
我在windows上使用python生成.sh文件,只用file.open(),file.write()
.但是当我在linux上运行这个.sh时,它会报如下错误。
/bin/bash^M:错误的解释器:没有这样的文件或目录
我生成的.sh文件的内容:
#!/bin/bash
export ICS_START=/rdrive/ics/itools/unx/bin/
source $ICS_START/icssetup.sh
......
我发现 vim 将其识别为 dos 文件。我猜是不是换行符有问题。
在我的 python 代码中,我使用file.write('xxxx\n')。据我所知,'\n' 是 linux/unix 上的换行符,'\r\n' 是 Windows 上的换行符。我不知道为什么在被linux识别时仍然有^M,因为我只写'\n'。
任何帮助将不胜感激。
【问题讨论】:
-
使用
dos2unix filename.sh修复换行符。 -
Python 在 Windows 上将
\n转换为\r\n,除非您以二进制模式打开文件。 -
@Barmar dos2unix 是我现在使用的方法。不知有没有办法从根本上解决。
-
过去我们使用
FTP时,它会在传输时自动转换换行符。不幸的是,scp等更现代的工具不这样做。 -
Using python to write text files with DOS line endings on linux、How can I force Python's file.write() to use the same newline format in Windows as in Linux (“\r\n” vs. “\n”)?、How to write Unix end of line characters in Windows using Python、How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script? 等可能重复