我是这样从Python内部调用dos2unix的:

call("dos2unix " + file1, shell=True, stdout=PIPE)

但是,为了使Unix输出静音,我执行了以下操作:
f_null = open(os.devnull, 'w')
call("dos2unix " + file1, shell=True, stdout=f_null , stderr=subprocess.STDOUT)

这似乎行不通命令不再作为我对file1file2执行的diff被调用(执行了diff -y file1 file2 | cat -t操作,可以看到行尾没有改变)。
file2是我比较的文件。它有unix行结尾,因为它是在box上生成的。但是,有可能file1不会。

最佳答案

不确定,为什么,但我会尽量消除命令周围的“噪音”并检查返回代码:

check_call(["dos2unix",file1], stdout=f_null , stderr=subprocess.STDOUT)

作为参数列表传递,而不是命令行(支持其中包含空格的文件!)
removeshell=True因为dos2unix不是内置的shell命令
使用check_call使其引发异常而不是静默失败
无论如何,有可能dos2unix检测到输出不再是tty,并决定将输出转储到tty中(dos2unix可以从标准输入工作到标准输出)。我同意这个解释。您可以通过重定向到一个真实的文件而不是os.devnull来检查它,并检查结果是否存在。
但是我会做一个纯python解决方案(有一个安全备份),它是可移植的,不需要dos2unix命令(所以它也可以在Windows上工作):
with open(file1,"rb") as f:
   contents = f.read().replace(b"\r\n",b"\n")
with open(file1+".bak","wb") as f:
   f.write(contents)
os.remove(file1)
os.rename(file1+".bak",file1)

完全读取文件很快,但可能会阻塞真正的大文件。也可以逐行解决(仍使用二进制模式):
with open(file1,"rb") as fr, open(file1+".bak","wb") as fw:
   for l in fr:
      fw.write(l.replace(b"\r\n",b"\n"))
os.remove(file1)
os.rename(file1+".bak",file1)

10-06 01:01