pythonbashheredoc

python -c vs python -<< heredoc


I am trying to run some piece of Python code in a Bash script, so i wanted to understand what is the difference between:

#!/bin/bash
#your bash code

python -c "
#your py code
"

vs

python - <<DOC
#your py code
DOC

I checked the web but couldn't compile the bits around the topic. Do you think one is better over the other? If you wanted to return a value from Python code block to your Bash script then is a heredoc the only way?


Solution

  • The main flaw of using a here document is that the script's standard input will be the here document. So if you have a script which wants to process its standard input, python -c is pretty much your only option.

    On the other hand, using python -c '...' ties up the single-quote for the shell's needs, so you can only use double-quoted strings in your Python script; using double-quotes instead to protect the script from the shell introduces additional problems (strings in double-quotes undergo various substitutions, whereas single-quoted strings are literal in the shell).

    As an aside, notice that you probably want to single-quote the here-doc delimiter, too, otherwise the Python script is subject to similar substitutions.

    python - <<'____HERE'
    print("""Look, we can have double quotes!""")
    print('And single quotes! And `back ticks`!')
    print("$(and what looks to the shell like command substitutions and $variables!)")
    ____HERE
    

    As an alternative, escaping the delimiter works identically, if you prefer that (python - <<\____HERE)