【发布时间】:2018-07-03 00:06:19
【问题描述】:
在 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 directorycat: tr: No such file or directorycat: -d: No such file or directorycat: \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 相同的错误。
【问题讨论】:
-
我可能会被告知按要求回答问题,但是:没有理由使用 Python 中的 cat 和 tr 来删除回车符。打开文件,读取数据,并转换后写出。
-
@Ned Batchelder,文件可能很大,所以我不想在 python 中打开和编辑它。
-
@Shabnam 您不必将所有数据都保存在内存中。你的 Python 程序可以做 tr 做的事情。
标签: python