Python -c vs โ€‹โ€‹python - << heredoc

I am trying to run a piece of python code in a bash script, so I wanted to understand what is best between:

 #!/bin/bash #your bash code python -c " #your py code " 

VS

 python - <<DOC #your py code DOC 

I checked the network but could not compile the bits around the topic. Do you think better is better than the other? If you want to return the value from the python code code to your bash script, then only heredoc?

thanks

+11
source share
3 answers

The main disadvantage of using the here document is that the standard document input will be the here document. So if you have a script that wants to handle its standard input, python -c is almost the only option.

On the other hand, using python -c '...' concatenates single quotes for shell needs, so you can only use double quoted strings in your Python script; instead, using double quotes to protect the script from the shell creates additional problems (double-quoted strings undergo different substitutions, while single-quoted strings are literal in the shell).

Also, note that you probably want to also quote the here-doc separator, otherwise the Python script undergoes similar replacements.

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

Alternatively, escaping works identically if you prefer this ( python - <<\____HERE )

+9
source

If you prefer to use python -c '...' without double quotes, you can first load the code in the bash variable using the docs here:

 read -r -d '' CMD << '--END' print ("'quoted'") --END python -c "$CMD" 

The python code is loaded verbatim into the CMD variable, and there is no need to avoid double quotes.

+6
source

If you use bash, you can avoid heredoc problems if you apply a little more than the standard template:

 python <(cat <<EoF name = input() print(f'hello, {name}!') EoF ) 

This will allow you to run the built-in Python script without giving up standard input. Overhead is basically the same as using cmda | cmdb cmda | cmdb cmda | cmdb cmda | cmdb . This method is known as the substitution process .

If you want to check the script somehow, I suggest you output it to a temporary file:

 #!/bin/bash temp_file=$(mktemp my_generated_python_script.XXXXXX.py) cat > $temp_file <<EoF # embedded python script EoF python3 $temp_file && rm $temp_file 

This will save the script if it does not start.

+1
source

All Articles