我试图在Bash脚本中运行一些Python代码,所以我想了解之间的区别是什么:
#!/bin/bash
#your bash code
python -c "
#your py code
"
VS
python - <<DOC
#your py code
DOC
我检查了网络,但无法编译主题周围的位。你认为一个比另一个好吗?如果你想从Python代码块返回一个值到你的Bash脚本,那么heredoc是唯一的方法吗?
使用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
作为替代方案,如果您愿意,转义分隔符的工作方式相同(python - <<\____HERE
)
如果您正在使用bash,那么如果您应用更多的样板,则可以避免出现heredoc问题:
python <(cat <<EoF
name = input()
print(f'hello, {name}!')
EoF
)
这将允许您运行嵌入式Python脚本,而无需放弃标准输入。开销与使用cmda | cmdb
大致相同。 This technique is known as Process Substitution。
如果希望能够以某种方式验证脚本,我建议您将其转储到临时文件:
#!/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
如果脚本无法运行,这将保留脚本。
如果你更喜欢使用python -c '...'
而不必使用双引号转义,你可以先使用here-documents在bash变量中加载代码:
read -r -d '' CMD << '--END'
print ("'quoted'")
--END
python -c "$CMD"
python代码逐字加载到CMD变量中,不需要转义双引号。