尝试使命令静音时,Dos2unix无法正常工作 [英] Dos2unix not working when trying to silence command

查看:330
本文介绍了尝试使命令静音时,Dos2unix无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was calling dos2unix from within Python this way:

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

无论如何,我都是这样做的:

However to silence the Unix output, I did this:

f_null = open(os.devnull, 'w')
call("dos2unix " + file1, shell=True, stdout=f_null , stderr=subprocess.STDOUT)

这似乎不起作用.该命令不再被调用,因为我在file1file2上执行的差异(没有diff -y file1 file2 | cat -t并且可以看到行尾未更改).

This doesn't seem to work. The command isn't being called anymore as the diff that I perform on the file1 against file2 (did a diff -y file1 file2 | cat -t and could see the line endings hadn't changed).

file2是我正在比较file1的文件.它具有在包装盒上生成的Unix行尾.但是,file1可能没有.

file2 is the file I am comparing file1 against. It has Unix line endings as it is generated on the box. However, there is a chance that file1 doesn't.

推荐答案

不确定,为什么,但是我会尝试消除您命令&周围的噪音"检查返回码:

Not sure, why but I would try to get rid of the "noise" around your command & check return code:

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

  • 作为args列表而不是命令行传递(支持其中包含空格的文件!)
  • 删除shell=True,因为dos2unix不是内置的shell命令
  • 使用check_call,因此引发异常,而不是无声地失败
    • pass as list of args, not command line (support for files with spaces in it!)
    • remove shell=True as dos2unix isn't a built-in shell command
    • use check_call so it raises an exception instead of failing silently
    • 无论如何,dos2unix可能检测到输出不再是tty,并决定转储输出(dos2unix可以从标准输入&至标准输出工作).我会解释一下.您可以通过重定向到 real 文件而不是os.devnull来检查它,并检查结果是否在那里.

      At any rate, it is possible that dos2unix detects that the output isn't a tty anymore and decides to dump the output in it instead (dos2unix can work from standard input & to standard output). I'd go with that explanation. You could check it by redirecting to a real file instead of os.devnull and check if the result is there.

      但是我会改做一个纯python解决方案(为了安全起见带有备份),该解决方案可移植并且不需要dos2unix命令(因此它也适用于Windows):

      But I would do a pure python solution instead (with a backup for safety), which is portable and doesn't need dos2unix command (so it works on Windows as well):

      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)
      

      完全读取文件速度很快,但可能会阻塞非常大的文件.逐行解决方案也是可行的(仍然使用二进制模式):

      reading the file fully is fast, but could choke on really big files. A line-by-line solution is also possible (still using the binary mode):

      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)
      

      这篇关于尝试使命令静音时,Dos2unix无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆