gpt4 book ai didi

python -c 与 python -<< heredoc

转载 作者:太空狗 更新时间:2023-10-29 16:53:29 26 4
gpt4 key购买 nike

我正在尝试在 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 的需要绑定(bind)单引号,因此您只能在 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)

关于python -c 与 python -<< heredoc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30702519/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com