简体   繁体   中英

How to use input() function of Python in bash script?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM