我是这样从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上执行的区别(做了一个diff -y file1 file2 | cat -t,可以看到行尾没有改变)。
file2是我比较file1的文件。它有Unix行的结尾,因为它是在盒子上生成的。然而,file1有可能不这样做。
发布于 2018-04-09 09:05:27
不确定,但我会尝试消除命令周围的“噪音”&检查返回代码:
check_call(["dos2unix",file1], stdout=f_null , stderr=subprocess.STDOUT)shell=True,因为dos2unix不是内置的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)https://stackoverflow.com/questions/49729099
复制相似问题