Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

piping from stdin to a python code in a bash script

Tags:

python

bash

I have a bash script, f, that contains python code. That python code reads from standard input. I want to be able to call my bash script as follows:

f input.txt > output.txt

In the example above, the python code will read from input.txt and will write to output.txt.

I'm not sure how to do this. I know that if I wanted to just write to a file, then my bash script would look like this

#!/bin/bash
python << EOPYTHON > output.txt
#python code goes here
EOPYTHON

I tried changing the second line in the code above to the following, but without luck

python << EOPYTHON $*

I'm not sure how else to go about doing this. Any suggestions?

EDIT I'll give a more concrete example. Consider the following bash script, f

#!/bin/bash
python << EOPYTHON 
import sys
import fileinput
for i in fileinput.input():
    sys.stdout.write(i + '\n')
EOPYTHON

I want to run my code with the following command

f input.txt > output.txt

How do I change my bash script so that it uses "input.txt" as the input stream?

like image 474
user2699231 Avatar asked Mar 25 '14 08:03

user2699231


2 Answers

As no one mentioned this, here is what author requested. The magic is to pass "-" as argument to cpython (instruction to read source code from stdin):

With output to file:

python - << EOF > out.txt
print("hello")
EOF

Execution sample:

# python - << EOF
> print("hello")
> EOF
hello

As data can't be passed via stdin anymore, here is another trick:

data=`cat input.txt`

python - <<EOF

data="""${data}"""
print(data)

EOF
like image 170
Reishin Avatar answered Nov 18 '22 12:11

Reishin


Updated Answer

If you absolutely must run the way you ask, you could do something like this:

#!/bin/bash
python -c 'import os
for i in range(3):
   for j in range(3):
     print(i + j)
'  < "$1"

Original Answer

Save your python code in a file called script.py and change your script f to this:

#!/bin/bash
python script.py < "$1"
like image 32
Mark Setchell Avatar answered Nov 18 '22 14:11

Mark Setchell