Why does this snippet with a shebang #!/bin/sh and exec python inside 4 single quotes work?

和自甴很熟 提交于 2019-11-27 11:50:53

Python supports triple-quoted strings:

'''something'''

Shell supports only single-quoted strings:

'something'

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.

The rest of the line is then interpreted as a command by sh, but as part of a string by 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.

So, to summarize:

  • 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+"$@"} #)

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.

I just use:

#!/bin/sh
''':'
exec python -tt "$0" "$@"
'''
# The above shell shabang trick is more portable than /usr/bin/env and supports adding arguments to the interpreter (python -tt)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!