[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 2018-08-16 01:05, Chris Angelico wrote:
> 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:

Well, sorta. Executable text files without a shebang line are not
executable per se, but most shells pretend they are. If you try to run a
shebang-less script through, say, Python's subprocess module, it won't work.

> 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. :)