Manuel
Manuel

Reputation: 473

Passing piped data to Python program and also an input file

I want to pass data to a Python file using a pipe and also specifying an input file like:

cat file.txt|python script.py -u configuration.txt

I currently have this:

for line in fileinput.input(mode='rU'):
    print(line)

I know there can be something with sys.argv but maybe using fileinput there is a clean way to do it?

Thanks.

Upvotes: 0

Views: 24

Answers (1)

David Z
David Z

Reputation: 131600

From the documentation:

If a filename is '-', it is also replaced by sys.stdin. To specify an alternative list of filenames, pass it as the first argument to input().

So you can create a list containing '-' as well as the contents of sys.argv[1:] (the default), and pass that to input(). Or alternatively just put - in the list of arguments of your Python program:

cat file.txt|python script.py -u - configuration.txt

or

cat file.txt|python script.py -u configuration.txt -

depending on whether you want data provided on standard input to be processed before or after the contents of configuration.txt.

If you want to do anything more complicated than just processing the contents of standard input as if it were an input file, you probably should not be using the fileinput module.

Upvotes: 1

Related Questions