Skip to content Skip to sidebar Skip to footer

How To Run Code With Sys.stdin As Input On Multiple Text Files

I am using sys.stdin in my code, and I want to know how to test my code on multiple text files. My code(test.py) is: for line in sys.stdin: line = line.strip() words = line.s

Solution 1:

echo"test1.txt""test2.txt" | test.py

Won't actually run test.py, you need to use this command instead:

echo"test1.txt""test2.txt" | python test.py

However, another method for getting arguments into python would be:

import sys
for arg in sys.argv:
    print line

Which when run like so:

python test.py "test1""test2"

Produces the following output:

test.py
test1
test2

The first argument of argv is the name of the program. This can be skipped with:

import sys
for arg in sys.argv[1:]:
    print line

A further problem you appear to be having is you're assuming that python is opening the text files you're handing it in the loop - this isn't true. If you print in the loop you'll see it's only printing the strings you gave it initially.

If you actually want to open and parse the files, do something like this in the loop:

import sys

args = sys.stdin.readlines()[0].replace("\"","").split()
forargin args:
    arg = arg.strip()
    with open(arg, "r") as f:
        for line in f:
            line = line.strip()
            words = line.split()

The reason we have that weird first line is that stdin is a stream, so we have to read it in via readlines().

The result is a list with a single element (because we only gave it one line), hence teh [0]

Then we need to remove the internal quotes, because the quotes aren't really required when piping, this would also work:

echo test1.txt test2.txt | python test.py

Finally, we have to split the string into the actual filenames.

Post a Comment for "How To Run Code With Sys.stdin As Input On Multiple Text Files"