python -c vs python - << heredoc

Kas*_*hif 16 python bash heredoc

我试图在Bash脚本中运行一些Python代码,所以我想了解之间的区别是什么:

#!/bin/bash
#your bash code

python -c "
#your py code
"
Run Code Online (Sandbox Code Playgroud)

VS

python - <<DOC
#your py code
DOC
Run Code Online (Sandbox Code Playgroud)

我检查了网络,但无法编译主题周围的位.你认为一个比另一个好吗?如果你想从Python代码块返回一个值到你的Bash脚本,那么heredoc是唯一的方法吗?

tri*_*eee 13

使用here文档的主要缺陷是脚本的标准输入将是here文档.因此,如果您有一个想要处理其标准输入的脚本,那么python -c几乎是您唯一的选择.

另一方面,使用python -c '...'单引号来满足shell的需要,因此你只能在Python脚本中使用双引号字符串; 使用双引号代替保护脚本免受shell引入其他问题(双引号中的字符串经历了各种替换,而单引号字符串在shell中是文字的).

顺便说一下,请注意,您可能也想单引引一个here-doc分隔符,否则Python脚本会受到类似的替换.

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
Run Code Online (Sandbox Code Playgroud)

作为替代方案,转义分隔符的工作方式相同,如果您愿意(python - <<\____HERE)


PEd*_*hur 8

如果您使用的是bash,则可以通过应用更多样板来避免heredoc问题:

python <(cat <<EoF

name = input()
print(f'hello, {name}!')

EoF
)
Run Code Online (Sandbox Code Playgroud)

这将使您无需放弃标准输入即可运行嵌入式Python脚本。开销与使用大致相同cmda | cmdb此技术称为“过程替换”

如果希望能够以某种方式验证脚本,建议您将其转储到临时文件中:

#!/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
Run Code Online (Sandbox Code Playgroud)

如果脚本无法运行,它将保留该脚本。


小智 7

如果您更喜欢使用python -c '...'而不必使用双引号转义,则可以使用here-documents首先在bash变量中加载代码:

read -r -d '' CMD << '--END'
print ("'quoted'")
--END
python -c "$CMD"
Run Code Online (Sandbox Code Playgroud)

python代码逐字加载到CMD变量中,不需要转义双引号.