4

我以这种方式从 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)

这似乎不起作用。该命令不再被调用,因为我在file1反对时执行的差异file2(做了 adiff -y file1 file2 | cat -t并且可以看到行尾没有改变)。

file2是我要比较的文件file1。它在盒子上生成时具有 Unix 行尾。但是,有机会file1不会。

4

1 回答 1

3

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

check_call(["dos2unix",file1], stdout=f_null , stderr=subprocess.STDOUT)
  • 作为参数列表传递,而不是命令行(支持包含空格的文件!)
  • remove shell=Trueasdos2unix不是内置的 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)
于 2018-04-09T09:05:27.223 回答