Errors in python script to remove NULL chars in a file
Question: Newbie question: I want to write a python script which removes all the NULL
characters in a file and count how many non-NULL characters left.

## Equivalent Linux command line:

    
    
    # Linux-machine:$ tr -dc [:print:] < raw-test.txt | wc -c
    # Linux-machine:$ more -f raw-test.txt
    abcdefghij^@^@^@^@^@^@.....
    

raw-test.txt file has 10 non-NULL characters in it (abcdefghij).

Python code:

* * *
    
    
    import subprocess
    p = subprocess.Popen(["tr", "-d", "-c", "[:print:]", "<", "raw-test.txt"], stdout=subprocess.PIPE)
    output, err = p.communicate()
    print output
    

## Errors:

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

Please help me see my errors.

Thanks much


Answer: IO redirections like `< infile`, `> outfile` are syntax from shell. OS doesn't
recognize it.

With subprocess, you should either set `shell=True` or use python open() to
redirect.

    
    
    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
    

