3

I have a small python program that parses a text file and writes the output to another file. Currently, I am writing a bash script to call this program several times, it looks something like:

for i in $(seq 1 100); do

          python /home/Documents/myProgram.py myTextFile$i

done

This works fine but I want to know if it is possible to have the python program inside the bash script file so when another user runs the script they don't need to have the python program in their memory; i.e., is it possible to copy and paste the python program into the bash script and run it from within the script itself?

4
  • 5
    Alternatively, you could echo the program to a file next to the script, run it from there, and rm that file afterwards. But really, don't do this. You won't have any syntax highlighting for that program, making it close to impossible to maintain. Rather just package it together with the script, or make your Python script to replace the bash part entirely. Commented Jul 22, 2014 at 20:15
  • This probably also depends a bit in what is in the Python program... Commented Jul 22, 2014 at 20:17
  • @tobias_k: +1 for replacing since Python can also do for loops. Commented Jul 22, 2014 at 20:17
  • not directly related to your question, but considered an improvement, would be: for i in {1..100}; do ... - reason: brace expansion is bash built-in, no need to subshell, while seq isn't, needs subshell and is not ubiquitous. some would prefer for (( ...; ; )) style loops, but those you have in python too Commented Jul 22, 2014 at 20:21

4 Answers 4

14
#!/bin/bash

python - 1 2 3 << 'EOF'
import sys

print 'Argument List:', str(sys.argv)
EOF

Output:

Argument List: ['-', '1', '2', '3']
Sign up to request clarification or add additional context in comments.

Comments

5

I think you should be able to put:

python  << END
[Python code here]
END

But I have not tested this.

2 Comments

Yup, @Cyrus seems to have it.
We had the same idea to use here document.
1

for simple scripts you can also run python with the -c option. For example

python -c "x=1; print x; print 'great program eh'"

I wouldn't recommend writing anything too complicated, but it could work for something simple.

Comments

0

Pardon the thread necromancy, but here's a technique that is missing that may be useful to someone.

#!/bin/bash
""":" # Hide bash from python
for i in $(seq 1 100); do
  python3 $(readlink -f "$0") myTextFile$i
done
exit
"""
# Python script starts here
import sys
print('Argument List: ', str(sys.argv))

However, I do agree with the general recommendation to just do the loop in Python.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.