Mixing Python and shell scripts

#!/bin/sh """": if which python >/dev/null; then exec python "$0" "$@" else echo "${0##*/}: Python not found. Please install Python." >&2 exit 1 fi """ __doc__ = """ Demonstrate how to mix Python + shell script. """ import sys print "Hello World!" print "This is Python", sys.version print "This is my argument vector:", sys.argv print "This is my doc string:", __doc__ sys.exit (0)
Sometimes it might be useful to write a script that can be used as a shell script or as a Python script at the same time. This is possible.

The trick is that a sequence of four quote characters means an empty string to the shell, but in Python it starts a triple-quoted string that begins with a quote character. So you can embed shell commands within that triple-quoted string. Note that the first string in a module or script is simply stored as the doc string for that module, but other than that it is simply ignored by the Python interpreter.

The following example demonstrates that trick. It is started as a shell script (because of the #!/bin/sh line). The embedded shell commands check if Python is installed. If not, a useful error message is displayed and the script exits. Otherwise, if Python is found, the script is re-executed with it. Python ignores the triple-quoted doc string and executes the rest like a normal Python program.

If you want to have a a real doc string for your program, you will have to assign it afterwards. The script below shows how to do this, too.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.