What does "input() already active" mean in python fileinput module?
Question: I'm trying to read 2nd line in text.txt file:

    
    
    import fileinput
    
    x = 0
    for line in fileinput.input([os.path.expandvars("$MYPATH/text.txt")]):
            if x < 3:
                x += 1
                if x == 2:
                    mydate = line
    fileinput.close()
    print "mydate : ", mydate 
    

But I get an error:

    
    
    Traceback (most recent call last):
      File "/tmp/tmpT8RvF_.py", line 4, in <module>
        for line in fileinput.input([os.path.expandvars("$MYPATH/text.txt")]):
      File "/usr/lib64/python2.6/fileinput.py", line 102, in input
        raise RuntimeError, "input() already active"
    RuntimeError: input() already active
    

What is wrong above?


Answer: To get the second line from the `fileinput.input()` iterable, just call
`.next()` twice:

    
    
    finput = fileinput.input([os.path.expandvars("$MYPATH/text.txt")])
    finput.next()  # skip first line
    mydate = finput.next()  # store second line.
    

You can also use the [`itertools.islice()`
function](http://docs.python.org/2/library/itertools.html#itertools.islice) to
select just the second line:

    
    
    import itertools
    
    finput = fileinput.input([os.path.expandvars("$MYPATH/text.txt")])
    mydate = itertools.islice(finput.next(), 1, 2).next()  # store second line.
    

Both methods ensure that no more than two lines are ever read from the input.

The `.input()` function returns a global singleton object, that the other
functions operate on. You can only run _one_ `fileinput.input()` instance _at
a time_. Make sure you called `fileinput.close()` before you open a new
`input()` object.

You should use the `fileinput.FileInput()` class instead to create multiple
instances.

