[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 14:33, Chris Angelico wrote:
> On Thu, Aug 16, 2018 at 8:32 PM, Thomas Jollans <tjol at tjol.eu> wrote:
>> 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.
> Good point. Still, for a lot of situations, it does allow you to
> invoke the .py file. I wonder if there's some sort of sneaky way to
> make the exec line appear as a comment to Python - probably involving
> quoting rules.

Easy as pie: (with an extra line)

'''exec' /usr/bin/env python3 -u -E -W error "$0" "$@"
import sys
print('hello', sys.executable)