python脚本中的错误,用于删除文件中的NULL字符

时间:2015-07-13 02:31:15

标签: bash python-2.7

新手问题:我想编写一个python脚本,删除文件中的所有NULL字符,并计算剩余的非NULL字符数。

等效的Linux命令行:

# 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:$

请帮我看看我的错误。

非常感谢

1 个答案:

答案 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