Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a unix filter in python?

I want to write a program that reads stdin (unbuffered) and writes stdout (unbuffered) doing some trivial char-by-char transformation. For the sake of the example let's say I want to remove all chars x from stdin.

like image 243
flybywire Avatar asked Oct 19 '09 17:10

flybywire


People also ask

How do you write UNIX in Python?

You cannot use UNIX commands in your Python script as if they were Python code, echo name is causing a syntax error because echo is not a built-in statement or function in Python. Instead, use print name . To run UNIX commands you will need to create a subprocess that runs the command.

How do you program a filter in Python?

The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. syntax: filter(function, sequence) Parameters: function: function that tests if each element of a sequence true or not.

How do I apply a filter in Unix?

In UNIX/Linux, filters are the set of commands that take input from standard input stream i.e. stdin, perform some operations and write output to standard output stream i.e. stdout. The stdin and stdout can be managed as per preferences using redirection and pipes. Common filter commands are: grep, more, sort.

What is Unix in Python?

Python. Unix is an operating system which was developed in around 1969 at AT&T Bell Labs by Ken Thompson and Dennis Ritchie. There are many interesting Unix commands we can use to carry out different tasks.


2 Answers

Read from sys.stdin and write to sys.stdout (or use print). Your example program:

import sys

for line in sys.stdin:
    print line.replace("x", ""),

There isn't a standard way to make stdin unbuffered, and you don't want that. Let the OS buffer it.

like image 175
Jed Smith Avatar answered Oct 19 '22 09:10

Jed Smith


You can use the fileinput class, which lets you process inputs like the Perl diamond operator would. From the docs:

import fileinput
for line in fileinput.input():
    process(line)

where process does something like print line.replace('x','').

You can follow this StackOverflow question for how to unbuffer stdout. Or you can just call sys.stdout.flush() after each print.

like image 15
Emil Sit Avatar answered Oct 19 '22 11:10

Emil Sit