English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python interface for Shell pipelines

To use Python to use the UNIX command pipeline mechanism. In the command pipeline, the sequence is converted from one file to another.

This module uses/ bin / sh command line. Therefore, we need the os.system() and os.popen() methods.

To use this module, we should use-Import it

import pipes

The pipeline holds the Template class-

Class Pipeline. Template

This class is essentially an abstraction of the pipeline. It has different methods. They are as follows.

Method Template.reset()

This method is used to restore the pipeline template to its initial position.

Method Template.clone()

This method is used to create another new object with the same template.

Method Template.debug(flag)

This method is used for debugging process. When this flag is true, the debug mode is enabled. When enabled, commands will be printed during execution.

Method Template.append(command, kind)

This method is used to insert a new task at the end. The command must be a bourne shell command. The kind variable consists of two characters.

For the first letter, it means-

NumberCharacters and Descriptions
1

'–'

The command reads standard input

2

'F'

The command will read the given file on the command line

3

'.

The command does not read any input. Therefore, it will be at the first position.

For the second letter, it means.

NumberCharacters and Descriptions
1

'–'

The command writes to standard output

2

'F'

The command will write the file on the command line

3

'.

command does not write any output. Therefore, it will be located at the last position.

Method Template.prepend(command, kind)

This method is used to insert a new task at the beginning. The command must be a bourne shell command. It is similar to theappend()Method.

Method Template.open(file, mode)

This method is used to open a file to be read or written. However, the read or write operation is performed by the pipeline.

Method Template.copy(infile, outfile)

This method is used to copy from infile to outfile through a pipeline.

Example Code

import pipes
my_template = pipes.Template()
my_template.append('tr a-z A-Z', '"--)
my_template.prepend('echo Python Programming', '")--)  # Prepend the item into queue
my_template.append('rev', '")--)
my_template.debug(True)
my_file = my_template.open('test_file', 'w')
my_file.close()
content = open('test_file').read()
print(content)

Output Result

$ python3 example.py
echo Python Programming |
tr a-z A-Z |
rev > test_file
+ rev
+ tr a-z A-Z
+ echo Python Programming
GNIMMARGORP NOHTYP