Python Interface to Shell Pipelines

PythonProgrammingServer Side Programming

To use the UNIX command pipeline mechanism using python. In the command pipelining a sequence converts from one file to another file.

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

To use this module, we should import it using −

import pipes

The pipes holds Template class −

class pipes.Template

This class is basically an abstraction of a pipeline. It has different methods. These 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, and same template object.

Method Template.debug(flag)

This method is used to Debug the process. When the flag is true, the debugging mode is on. When it is on, the 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 −

Sr.No. Character & Description
1

‘–‘

Command reads the standard Input

2

‘f’

Command will read a given file on the command line

3

‘.’

Command does not read any input. So it will be at the first position.

For the second letter, it means.

Sr.No. Character & Description
1

‘–‘

Command writes to the standard output

2

‘f’

Command will write a file on the command line

3

‘.’

Command does not write any output. So it will be 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 the append() method.

Method Template.open(file, mode)

This method is used to open a file to read or write. But reading or writing operations are done by the pipelines.

Method Template.copy(infile, outfile)

This method is used to copy from infile to outfile, by the pipeline.

Example Code

Live Demo

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

$ 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
raja
Published on 31-Oct-2018 13:37:17
Advertisements