How to process pipelines using Python
This article describes how to process pipelines in Python. Share it with you for your reference. The specific analysis is as follows:
What is the most amazing magic in Linux? I believe different people have different opinions, but if there is no pipeline, I am afraid that magic will be lost in the beautiful magic.
This section describes how to use Python to process these pipelines.
Pipeline call subroutine
We want to use a sub-program in the program, but we need to dynamically PASS Parameters (the dynamic here refers to deciding what to input based on the results of the previous subprogram input). What should we do, don't worry, there is subprocess!
Next I will first introduce an example code and its output results!
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 |
#! /Usr/bin/python
From subprocess import *
# Subprocess management, which can be used to create many sub-process files. We need to introduce this file.
P = Popen (["cat", "-n"], bufsize = 1024, stdin = PIPE,
Stdout = PIPE, close_fds = True)
# The first parameter to open a program is a list (program name, parameter)
# The second parameter is the buffer size.
# Stdin. stdout is used to set whether to open these pipelines. If its value is subprocess. PIPE,
# It will be opened. stderr is the same as stdin.
# Close_fds is set to true (unix-only). All file descriptors except (, 2) are closed before the subroutine is executed.
(Fin, fout) = (p. stdin, p. stdout)
For I in range (10): # explain _^
Fin. write ("line" + str (I ))
Fin. write ('\ n ')
Fin. flush ()
Print fout. readline ()
|
The output result is:
?
|
1
2
3
4
5
6
7
8
9
10 |
Line0
Line1
Line2
Line3
Line4
Line5
Line6
Line7
Line8
Line9
|
I hope this article will help you with Python programming.