osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

How to pass Python command line options (vs arguments) when running script directly vs via Python interpreter?


On Thu, Aug 16, 2018 at 8:51 AM, Cameron Simpson <cs at cskk.id.au> wrote:
> And as an additional alternative, when I want something weird (extra python
> args or the like) I usually make my script.py into a module and invoke it
> via a shell script, eg:
>
>  #!/bin/sh
>  exec /particular/python python-opts... -m script_module ${1+"$@"}
>
> Obviously that'd need a little adaption under Windows.

Since an executable file without a shebang should normally be invoked
through /bin/sh, you can actually combine this technique into the
script itself with a cool hack:


exec /usr/local/bin/python3 -x -W error $0 "$@"
"""
This is an example script.

It is executable and will invoke itself through Python.
"""
import warnings
warnings.warn("This should be an error.")
print("This shouldn't happen.")


The "-x" parameter means "skip the first line", and in a sense, the
exec line is a non-standard shebang. :)

ChrisA