簡體   English   中英

嘗試靜音命令時Dos2unix無法正常工作

[英]Dos2unix not working when trying to silence command

我這樣在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 -y file1 file2 | cat -t並且可以看到行結尾沒有改變)。

file2是我正在比較file1的文件。 它具有Unix行結尾,因為它是在盒子上生成的。 但是, file1有可能沒有。

不確定,為什么,但我會試圖擺脫你的命令周圍的“噪音”並檢查返回代碼:

check_call(["dos2unix",file1], stdout=f_null , stderr=subprocess.STDOUT)
  • 傳遞為args列表,而不是命令行(支持包含空格的文件!)
  • remove 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM