python -c vs python -<< heredoc
·
问题:python -c vs python -<< heredoc
我正在尝试在 Bash 脚本中运行一些 Python 代码,所以我想了解两者之间的区别:
#!/bin/bash
#your bash code
python -c "
#your py code
"
对比
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)
更多推荐

所有评论(0)