Assessment: Command-Line Programs

Sep 29, 2014 • Isabelle Laforest

Multiple Choice Question

Given the following script (for IPython Notebooks):

!cat count-stdin.py
import sys
count=0
for line in sys.stdin:
     count +=1
print count, 'lines in standard input'

Which of these choices will successfully give you the line count of the small.csv file?

a) ipython count-stdin.py small.csv
b) !cat count-stdin.py small.csv
c) %run count-stdin.py < small.csv
d) !ipython count-stdin.py < small.csv
e) %run count-stdin.py small.csv
f) !ipython count-stdin.py | small.csv

Question #2

Given that you have three files (small-01.csv, small-02.csv, small-03.csv) that have this structure:

0,1,1
2,1,0

Debug the following script designed to create a function (readings.py) that could apply ---min, ---max and ---mean actions to multiple "small" files:

cat readings.py
import sys
import numpy
def main():
     script=sys.argv[0]
     action=sys.argv[1]
     filenames=sys.argv[2]

assert action in ['--min", '--mean','--max'],
    Action is not one of --min, --mean, or --max: ' + action
if len(filenames)==1
    process(sys.stdin,action)
else:
    for f in filenames:
         process(f,action)

def process(filename, action):
    data=np.loadtxt(filename, delimiter=',')

if action == 'min':
    values=data.min(axis=1)
elif action == 'mean':
    values=data.mean(axis=1)
elif action == 'max':
    values=data.max(axis=1)

for m in values:
    print m
main()