为什么这个片段用家当#!/斌/里面4单引号SH和exec蟒蛇工作?
我想了解这个问题的答案之一:
I'm trying to understand one of the answers to this question:
Cannot传递参数与&QUOT到Python;#!的/ usr /斌/包膜蟒蛇"
#!/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 supports only single-quoted strings:
'something'
使用的四的报价, 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
PTED为命令,然后跨$ P $,但作为由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
看到:空字符串()的 - 空字符串(
)的 - 命令(
EXEC蟒蛇-u - $ 0$ {1 +$ @ }
)的 - 注释(#'''
)的 - Python看到:三引号字符串(包含字符
'EXEC蟒蛇-u - $ 0$ {1 +$ @}#
)的
-
sh
sees: empty string (''
) - empty string (''
) - command (exec python -u -- "$0" ${1+"$@"}
) - comment (# '''
) - Python sees: triple-quoted string literal (containing the characters
'exec python -u -- "$0" ${1+"$@"} #
)
所以 SH
执行该命令,替换与自身蟒蛇-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.
由于它是第一个字符串文件中的文字,它会被设置为文档字符串为 __主要__
模块,但就是难以将问题,如果这是主脚本。
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.