简体   繁体   中英

What's the difference between pipes and subprocess module?

I am getting confused with pipes and subprocess module.

here is my code:

import pipes
import subprocess


with open('123.txt', 'w') as f:
    f.write('a line 1\n')
    f.write('a line 2\n')

t = pipes.Template()
t.append('grep a', '--')
f = t.open('123.txt', 'r')
print(f.readlines())

with open('123.txt', 'r') as f:
    p = subprocess.Popen('grep a', stdin=f, stdout=subprocess.PIPE, shell=True, universal_newlines=True)

print(p.readlines())

their outputs are exactly the same:

['a line 1\n', 'a line 2\n']
['a line 1\n', 'a line 2\n']

My question is:

  1. What's the difference between these two modules.

  2. Can I write strings through a subprocess.PIPE(stdin) and redirect to another subprocess.PIPE(stdout). In this situation what args should I use in subprocess.Popen

Stick with subprocess . pipes is *NIX specific, barely maintained, and built on the semi-deprecated os.system / os.pipe primitives that subprocess exists to replace. While subprocess doesn't specifically mention the pipes module, it does provide examples for Replacing shell pipelines which will handle the cases you seem to care about, and without the shells implicitly involved in pipes (due to it being built on os.system / os.popen ), subprocess can be safer and faster (if you don't use shell=True that is) and more portable to boot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM