为什么这个片段用家当#!/斌/里面4单引号SH和exec蟒蛇工作? [英] Why does this snippet with a shebang #!/bin/sh and exec python inside 4 single quotes work?

查看:149
本文介绍了为什么这个片段用家当#!/斌/里面4单引号SH和exec蟒蛇工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解这个问题的答案之一:

I'm trying to understand one of the answers to this question:

<一个href=\"http://stackoverflow.com/questions/3306518/cannot-pass-an-argument-to-python-with-usr-bin-env-python\">Cannot传递参数与&QUOT到Python;#!的/ usr /斌/包膜蟒蛇&QUOT;

#!/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.

这篇关于为什么这个片段用家当#!/斌/里面4单引号SH和exec蟒蛇工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆