Python and Java program that work as pipes
--D. Thiebaut (talk) 08:45, 18 February 2017 (EST)
Two programs, one in Python and one in Java show how to code an application to take its input either from a file name given on the command line, or from stdin, fed through a pipe. Both programs are illustrated by having them filter a text file containing poems. The contents of the file is given at the end of this page.
Pipes in Python
Source
#! /usr/bin/env python ''' gremlin.py D. Thiebaut This python program illustrates how to write a program that will work equally well with information taken from a file specified on the command line, or information fed through stdin. Typical use: chmod +x gremlin.py ./gremlin.py someFileName.txt cat someFileName.txt | ./gremlin.py ''' from __future__ import print_function import sys def main(): # open the first argument on command line, or stdin if none is specified with open(sys.argv[1], 'r') if len(sys.argv) > 1 else sys.stdin as f: # read the whole contents and put it in memory lines = f.readlines() f.close() # filter each line and replace 'g' characters by "gremlin", # upper or lowercase. for line in lines: print( line.strip() .replace('g', 'gremlin' ) .replace( 'G', 'Gremlin' ) ) main()
Output
Pipes in Java
Source
/* Gremlin.java D. Thiebaut A program illustrating how an app can work with both a file and with stdin as input. This program takes either a file given as argument, or stdin, and filters it, replacing all 'g' characters by "gremlin" and all 'G' characters by "Gremlin" Typical use: javac Gremlin.java java Gremlin someFileName.txt cat someFileName.txt | java Gremlin Some code taken from https://www.caveofprogramming.com/java/java-file-reading-and-writing-files-in-java.html */ import java.io.*; import java.util.Scanner; class Gremlin { public static void main(String[] args) { // read from pipe if ( args.length == 0 ) { Scanner sc = new Scanner(System.in); //System.out.println("Printing the file passed in:"); while(sc.hasNextLine()) System.out.println(sc.nextLine()); } // read from file specified as argument (reads only first of // several arguments). else { // The name of the file to open. String fileName = args[0]; // This will reference one line at a time String line = null; try { // FileReader reads text files in the default encoding. FileReader fileReader = new FileReader(fileName); // Always wrap FileReader in BufferedReader. BufferedReader bufferedReader = new BufferedReader(fileReader); while((line = bufferedReader.readLine()) != null) { // filter away! line = line.replace( "g", "gremlin" ).replace( "G", "Gremlin" ); System.out.println(line); } // Always close files. bufferedReader.close(); } catch(FileNotFoundException ex) { System.out.println( "Unable to open file '" + fileName + "'"); } catch(IOException ex) { System.out.println("Error reading file '" + fileName + "'"); } } } }
Output
Poem File
The file, named snowPoems.txt, and used in these examples is the following:
Neither Snow - Poem by Billy Collins When all of a sudden the city air filled with snow, the distinguishable flakes blowing sideways, looked like krill fleeing the maw of an advancing whale. At least they looked that way to me from the taxi window, and since I happened to be sitting that fading Sunday afternoon in the very center of the universe, who was in a better position to say what looked like what, which thing resembled some other? Yes, it was a run of white plankton borne down the Avenue of the Americas in the stream of the wind, phosphorescent against the weighty buildings. Which made the taxi itself, yellow and slow-moving, a kind of undersea creature, I thought as I wiped the fog from the glass, and me one of its protruding eyes, an eye on a stem swiveling this way and that monitoring one side of its world, observing tons of water tons of people colored signs and lights and now a wildly blowing race of snow. Billy Collins ---------------------------------------------------------- Shoveling Snow With Buddha - Poem by Billy Collins In the usual iconography of the temple or the local Wok you would never see him doing such a thing, tossing the dry snow over a mountain of his bare, round shoulder, his hair tied in a knot, a model of concentration. Sitting is more his speed, if that is the word for what he does, or does not do. Even the season is wrong for him. In all his manifestations, is it not warm or slightly humid? Is this not implied by his serene expression, that smile so wide it wraps itself around the waist of the universe? But here we are, working our way down the driveway, one shovelful at a time. We toss the light powder into the clear air. We feel the cold mist on our faces. And with every heave we disappear and become lost to each other in these sudden clouds of our own making, these fountain-bursts of snow. This is so much better than a sermon in church, I say out loud, but Buddha keeps on shoveling. This is the true religion, the religion of snow, and sunlight and winter geese barking in the sky, I say, but he is too busy to hear me. He has thrown himself into shoveling snow as if it were the purpose of existence, as if the sign of a perfect life were a clear driveway you could back the car down easily and drive off into the vanities of the world with a broken heater fan and a song on the radio. All morning long we work side by side, me with my commentary and he inside his generous pocket of silence, until the hour is nearly noon and the snow is piled high all around us; then, I hear him speak. After this, he asks, can we go inside and play cards? Certainly, I reply, and I will heat some milk and bring cups of hot chocolate to the table while you shuffle the deck. and our boots stand dripping by the door. Aaah, says the Buddha, lifting his eyes and leaning for a moment on his shovel before he drives the thin blade again deep into the glittering white snow. Billy Collins