理解 Python 脚本需要帮助
我正在分析来自 Google 的存储库脚本(说明位于 http://source.android.com/source/ download.html)
repo 脚本是用 Python 编写的。那里有一部分说:
if sys.argv[-1] =='#%s' % magic
有人可以从语义上解释该行的含义吗?我对 Python 有点生疏了。整个代码块是:
magic='--calling-python-from-/bin/sh--'
"""exec" python -E "$0" "$@" """#$magic"
if __name__ == '__main__':
import sys
if sys.argv[-1] =='#%s' % magic:
del sys.argv[-1]
I am analyzing the repo script from Google (instructions at http://source.android.com/source/downloading.html)
The repo script is written in Python. There is a part in there that says:
if sys.argv[-1] =='#%s' % magic
Can somebody explain semantically what that line means? I am a bit rusty on my Python. The entire block of code for this is:
magic='--calling-python-from-/bin/sh--'
"""exec" python -E "$0" "$@" """#$magic"
if __name__ == '__main__':
import sys
if sys.argv[-1] =='#%s' % magic:
del sys.argv[-1]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当时的一篇:
sys.argv
< /a> 保存传递给 Python 脚本的命令行参数列表。 这意味着 sys-argv[-1] 是最后一个参数。'#%s'% magic
。%
格式化您的字符串,这意味着您看到%s
的地方将是magic
的值(如果magic< /code> 不是字符串,它将被转换:
str(magic)
)。在您的代码中,该字符串将为:'#--calling-python-from-/bin/sh--'
。del sys.argv[-1]
。这是不言自明的:意味着列表 sys.argv 的最后一个值将被删除。总而言之,这意味着:如果最后一个命令行参数是
#--calling-python-from-/bin/sh--
,该参数将从 sys 中删除.argv.One piece at the time:
sys.argv
holds the list of command line arguments passed to a Python script. Meaning thatsys-argv[-1]
is the last argument.'#%s' % magic
. The%
formats your string, which means the where you see%s
there's going to be the value ofmagic
(ifmagic
is not a string it will be converted:str(magic)
). In your code that string is going to be:'#--calling-python-from-/bin/sh--'
.del sys.argv[-1]
. This is self-explainatory: means that the last value of the listsys.argv
is going to be removed.All together it means that: if the last command line argument is
#--calling-python-from-/bin/sh--
that argument is going to be removed fromsys.argv
.它将 magic 格式化为格式为 '#nnn' 的字符串,其中 n 被
magic
转换为字符串,并将该字符串与命令行上传递的最后一个参数进行比较(负索引从列表末尾开始索引) )。如果找到,则将 arg 从参数列表中删除。It formats magic as a string in the format '#nnn' where n is
magic
converted to a string and compares the string with the last argument passed on the command line (negative indexes index the list from its end). If found, the arg is removed from the list of arguments.