Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

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

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

Cannot pass an argument to python with "#!/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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...