user1179317
user1179317

Reputation: 2923

How to redirect input to python script

How come this command python test.py <(cat file1.txt) does not work accordingly. I could've sworn I had this working previously. Basically, I would like to get the output of that cat command as an input to the python script.

This command

cat file1.txt | python test.py

works okay, which outputs:

reading:  file11
reading:  file12

Which are based on the following scripts/files below.

The reason I want this to work is because I really want to feed in 2 input files like

python test.py <(cat file1.txt) <(cat file2.txt)

And would like some python output like:

reading:  file11 file21
reading:  file12 file22

I know this is a very simple example, and I can just read in or open() both files inside the python script and iterate accordingly. This is a simplified version of my current screnario, the cat command is technically another executable doing other things, so its not as easy as just reading/opening the file to read.

Sample script/files:

test.py:

import sys

for line in sys.stdin:
   print("reading: ", line.strip())

sys.stdin.close()

file1.txt:

file11
file12

file2.txt:

file21
file22

Upvotes: 1

Views: 2862

Answers (2)

user1179317
user1179317

Reputation: 2923

changing test.py to:

import sys

input1 = open(sys.argv[1], "r")
input2 = open(sys.argv[2], "r")

for line1, line2 in zip(input1, input2):
   print("reading: ", line1.strip(), line2.strip())

input1.close()
input2.close()

will enable python test.py <(cat file1.txt) <(cat file2.txt) to work

Upvotes: 1

kosciej16
kosciej16

Reputation: 7158

Actually it depends on shell you are using. I guess you use bash which unfortunately can't have it working as only last redirection from specific descriptor is taken. You could create temporary file, redirect output of scripts to it and then feed your main script with tmp file.

Or if you don't mind you can switch e.g to zsh, which has such feature enabled by default.

Upvotes: 0

Related Questions