不确定,为什么,但我会尝试消除命令周围的“噪音”并检查返回码:
check_call(["dos2unix",file1], stdout=f_null , stderr=subprocess.STDOUT)
- 作为参数列表传递,而不是命令行(支持包含空格的文件!)
- remove
shell=True
asdos2unix
不是内置的 shell 命令
- 使用
check_call
所以它会引发异常而不是静默失败
无论如何,有可能dos2unix
检测到输出不再是 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)