Simulating Pipes With run()
00:00
In the REPL, the code looks like this. You import subprocess
, then you use subprocess
.run()
to run the first command, which is ls
, and then usr/bin
.
00:12
And then stdout
is equal to subprocess.PIPE
. Now subprocess.PIPE
is a constant, it’s kind of like a flag that says, “Hey, let’s buffer the output of this process,” this ls
process here.
00:28
So that is my first process. And the second process is my grep
. So again, subprocess.run()
. The arguments are grep python
.
00:37
And then this is a trick here: as input
, we set that to be equal to the stdout
of the previous process. So ls_process.stdout
.
00:49
We feed that into the input
of the grep
process,
00:54
and then we also set the stdout
of the grep
process equal to the PIPE
constant.
01:00
And then we would like to print the output of the grep
process. So grep_process.stdout
. And then as you will have seen in a previous lesson, you then decode that from a bytes object into a text object.
01:15
So what does that give me? As expected, you have the same four files with the word Python appearing as output of your grep
process.
01:27 So if you think back to the graph and the slides we looked at before, you can see that indeed it is the output of the first process that’s being buffered, stuck in a pipe, and then fed into the second process.
01:43
Now, one final note here is that this is actually not a true pipe. This is more a simulation of pipes. The run()
function can’t actually create actual pipes.
01:55
It can simulate them using input
, but it can’t actually create real pipes. For that, we will need Popen
and that you will learn later on in the course.
02:05
And when I say later on in the course, I of course mean right now. In the next video, we’ll talk about Popen
.
Become a Member to join the conversation.