简体   繁体   中英

Python internal pipe in subprocess using list arguments?

It is possible to create a subprocess like this...

commandlist = ['cat', '/some/file']

sp = subprocess.Popen(commandlist)

But is it possible to pipe the output of that sequence into another command inside the same subprocess?

For example, what would be the sequence/list equivalent of cat /some/file | sed 's/foo/bar/' cat /some/file | sed 's/foo/bar/' ?

I would like to avoid using a string input with shell=True and was wondering if it can be done without creating 2 subprocesses.

Thanks, Chris

The pipe syntax is a shell construct, so you can use the shell to execute it:

sp = subprocess.Popen("cat /some/file | sed 's/foo/bar/'", shell=True)

But pipes themselves are not limited to the shell, so you can establish the pipe in Python:

sp1 = subprocess.Popen(['cat', '/some/file'], stdout=subprocess.PIPE)
sp2 = subprocess.Popen(['sed', 's/foo/bar'], stdin=sp1.stdout)

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