Skip to content

Instantly share code, notes, and snippets.

@karlcow
Created July 23, 2014 02:42
Show Gist options
  • Select an option

  • Save karlcow/e397e5b0fc1f33d126c3 to your computer and use it in GitHub Desktop.

Select an option

Save karlcow/e397e5b0fc1f33d126c3 to your computer and use it in GitHub Desktop.

Let's say you want to send files to a program

python pipe_test.py --blah foo.txt bar.txt

AND send files content to a program with a pipe

cat foo.txt bar.txt | python pipe_test.py --blah

with the same script pipe_text.py

Here a piece of code

import fileinput
import argparse
# testing also arguments to see if it interferes. suspens… It doesn't :p
parser = argparse.ArgumentParser()
parser.add_argument("infiles", nargs="*")
parser.add_argument('--blah', help='do something',
action='store_true', dest="blah", default=True)
args = parser.parse_args()
filelist = args.infiles
# List of files
print "Files list: %s" % filelist
# Processing of the input
line_number = 0
for line in fileinput.input(args.infiles):
line_number += 1
print "%s - %s" % (line_number, line.strip())

so without the pipe

Files list: ['foo.txt', 'bar.txt']
1 - foo 1
2 - foo 2
3 - foo 3
4 - foo 4
5 - bar 1
6 - bar 2
7 - bar 3
8 - bar 4

with the pipe

Files list: []
1 - foo 1
2 - foo 2
3 - foo 3
4 - foo 4
5 - bar 1
6 - bar 2
7 - bar 3
8 - bar 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment