在Python中调用unix命令的最佳方法是什么? cat file1.txt | tr -d '\r' > file2.txt
我试过以下情况:
1。
cmd = "cat file1 | tr -d \'\r\'> file2"
args = shlex.split(cmd)
p = subprocess.Popen(args, shell=True)
我得到了cat: stdin: Input/output error
2
f = open(file2, "w")
p = subprocess.call(args, stdout=f)
我得到了:
cat: |: No such file or directory
cat: tr: No such file or directory
cat: -d: No such file or directory
cat: \r: No such file or directory
3
p = subprocess.Popen(args, stdout=subprocess.PIPE)
(out,err) = p.communicate()
print(out)
虽然有效,但我不知道为什么当我使用file.write(out)
代替print(out)
时,我会得到与案例2相同的错误。
答案 0 :(得分:1)
只需在Python中执行:
with open("file1.txt", "rb") as fin:
with open("file2.txt", "wb") as fout:
while True:
data = fin.read(100000)
if not data:
break
data = data.replace(b"\r", b"")
fout.write(data)