为什么这个带有 shebang #!/bin/sh 和 exec python 的片段在 4 个单引号内起作用?
问题描述
我试图理解这个问题的答案之一:
I'm trying to understand one of the answers to this question:
无法将参数传递给 python"#!/usr/bin/env python"
#!/bin/sh
''''exec python -u -- "$0" ${1+"$@"} # '''
这很好用,但我不明白为什么它在该行的开头使用四个刻度而不是三个.
This works well, but I do not understand why it works with four ticks at the beginning of that line rather than three.
另外,为什么散列在字符串的末尾附近?
In addition, why the hash near the end of that string?
解决方案
Python 支持三引号字符串:
Python supports triple-quoted strings:
'''something'''
Shell 仅支持单引号字符串:
Shell supports only single-quoted strings:
'something'
通过使用 four 引号,sh
将其视为 2 个空字符串,但 Python 将前三个视为三引号字符串的开头,并包含第四个作为字符串值的一部分.
By using four quotes, sh
sees that as 2 empty strings, but Python sees the first three as the start of a triple-quoted string, and includes the fourth as part of the string value.
该行的其余部分随后被 sh
解释为命令,但被 Python 解释为字符串的一部分.
The rest of the line is then interpreted as a command by sh
, but as part of a string by Python.
#
然后就 sh
而言形成一个注释,但它仍然是 Python 的一个字符串,用一个结束的三引号结束它.
The #
then forms a comment as far as sh
is concerned, but it is still a string to Python, closing it off with a closing triple-quote.
所以,总结一下:
sh
看到:空字符串 (''
) - 空字符串 (''
) - command (exec python -u -- "$0" ${1+"$@"}
) - comment (#'''
)- Python 看到:三引号字符串文字(包含字符
'exec python -u -- "$0" ${1+"$@"} #
)
所以 sh
执行该命令,将自身替换为 python -u --
脚本名称和其余命令行参数,Python 读取此文件并且只看到一个不会去任何地方的初始字符串文字.
So sh
executes that command, replacing itself with the python -u --
with the script name and the rest of the command line arguments, and Python reads this file and just sees an initial string literal that isn't going anywhere.
因为它是文件中的第一个字符串文字,它将被设置为 __main__
模块的文档字符串,但如果这是主脚本则几乎没有关系.
Because it is the first string literal in the file, it'll be set as the docstring for the __main__
module but that is hardly going to matter if this is the main script.
相关文章