Reputation: 1342
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
Upvotes: 0
Views: 801
Reputation: 4135
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.
Upvotes: 1