user3346813
user3346813

Reputation:

From commands to subprocess

How to write the following line using subprocess library instead of commands. The idea is to get the same result but using subprocess.

commands.getoutput('tr -d "\'" < /tmp/file_1.txt > /tmp/file_2.txt')

Upvotes: 2

Views: 149

Answers (3)

jfs
jfs

Reputation: 414275

You don't need shell in this case, to run tr command. And since you've redirected the child process' stdout; you also don't need subprocess.check_output():

from subprocess import check_call

with open("/tmp/file_1.txt", "rb") as input_file:
    with open("/tmp/file_2.txt", "wb") as output_file:
        check_call(["tr", "-d", "'"], stdin=input_file, stdout=output_file)

Note: unlike commands.getoutput() it doesn't capture stderr. If you want to get stderr of the subprocess as a separate string:

from subprocess import Popen, PIPE

with open("/tmp/file_1.txt", "rb") as input_file:
    with open("/tmp/file_2.txt", "wb") as output_file:
        p = Popen(["tr", "-d", "'"], stdin=input_file, stdout=output_file,
                  stderr=PIPE)
stderr_data = p.communicate()[1]

Also, you could replace tr call with a pure Python:

from functools import partial

chunksize = 1 << 15
with open("/tmp/file_1.txt", "rb") as input_file:
    with open("/tmp/file_2.txt", "wb") as output_file:
         for chunk in iter(partial(input_file.read, chunksize), b''):
             output_file.write(chunk.replace(b"'", b""))

Upvotes: 0

Furquan Khan
Furquan Khan

Reputation: 1594

import subprocess    

p=subprocess.Popen('tr -d "\'" < /tmp/file_1.txt > /tmp/file_2.txt',shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output=p.communicate()[0]
print "o", output

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

The equivalent command to commands.getoutput is subprocess.check_output:

from subprocess import check_output
out = check_output('tr -d "\'" < /tmp/file_1.txt > /tmp/file_2.txt', shell=True)

Upvotes: 2

Related Questions