新手问题:我想编写一个python脚本,删除文件中的所有NULL字符,并计算剩余的非NULL字符数。
# Linux-machine:$ tr -dc [:print:] < raw-test.txt | wc -c
# Linux-machine:$ more -f raw-test.txt
abcdefghij^@^@^@^@^@^@.....
raw-test.txt文件中有10个非NULL字符(abcdefghij)。
Python代码:
import subprocess
p = subprocess.Popen(["tr", "-d", "-c", "[:print:]", "<", "raw-test.txt"], stdout=subprocess.PIPE)
output, err = p.communicate()
print output
# Linux-machine:$ python raw-test-trim.py
usage: tr [-Ccsu] string1 string2
tr [-Ccu] -d string1
tr [-Ccu] -s string1
tr [-Ccu] -ds string1 string2
# Linux-machine:$
请帮我看看我的错误。
非常感谢
答案 0 :(得分:1)
< infile
,> outfile
等IO重定向是shell的语法。操作系统无法识别它。
使用子进程,您应该设置shell=True
或使用python open()进行重定向。
import subprocess
p = subprocess.Popen('tr -d -c [:print:] < raw-test.txt', shell=True, stdout=subprocess.PIPE)
output, err = p.communicate()
print output
with open('raw-test.txt', 'rb') as f:
p = subprocess.Popen(["tr", "-d", "-c", "[:print:]"], stdin=f, stdout=subprocess.PIPE)
output, err = p.communicate()
print output