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?
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With