I am trying to integrate a Python script into a bash script. However when I use the input() function, I am getting an EOFError. How can I fix this problem?
#!/bin/bash
python3 <<END
print(input(">>> "))
END
You cannot source both the script and the user input through the program's standard input. (That's in effect what you're trying to do. << redirects the standard input.)
Ideally, you would provide the script as command line argument instead of stdin using -c SCRIPT instead of <<EOF heredoc EOF:
#!/bin/bash
python3 -c 'print(input(">>> "))'
Note that you may need to mind your quoting and escaping in case you have a more complicated Python script with nested quotes.
You can still let the script run over multiple lines, if you need to:
#!/bin/bash
python3 -c '
import os.path
path_name = input("enter a path name >>> ")
file_exists = os.path.exists(path_name)
print("file " + path_name + " " +
("exists" if file_exists else "does not exist"))
'
Note that you will get into trouble when you want to use single quotes in your Python script, as happens when you want to print doesn't instead of does not.
You can work around that using several approaches. The one I consider most flexible (apart from putting you into quoting hell) is surrounding the Python script with double quotes instead and properly escape all inner double quotes and other characters that the shell interprets:
#!/bin/bash
python3 -c "
print(\"It doesn't slice your bread.\")
print('But it can', 'unsliced'[2:7], 'your strings.')
print(\"It's only about \$0. Neat, right?\")
"
Note that I also escaped $, as the shell would otherwise interpret it inside the surrounding double quotes and the result may not be what you wanted.
#!/bin/bash python3 -c 'print(input(">>>"))' python3 <<END value_of_input = ? ENDinput() function. However it gave an EOFError. I need to run a bash script and this bash script contains Python codes. Many Python codes can be written in that bash script but input function can not be used properly. That's my problem. I guess you understood what I was trying to show you in my previous comment.EOFError is that you're using a here document. I.e. the <<. This puts the script into python3's standard input instead of the terminal's standard input. So python3 just receives the script. Then starts interpreting the script and then when it hits input() there's no more there, as from Python's point of view, the input ended right after the script. After the here document. Hence you should be using -c '...' instead of <<EOF ... EOF