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

Cameron Simpson cs at cskk.id.au
Wed Aug 15 18:51:43 EDT 2018


On 15Aug2018 20:54, eryk sun <eryksun at gmail.com> wrote:
>On Wed, Aug 15, 2018 at 9:22 AM, Thomas Jollans <tjol at tjol.eu> wrote:
>> If you really want to, you can pass a *single* argument in your #! line,
>> e.g.:
>>
>> #!/usr/bin/python3 -Wd
>
>This works for options that can be grouped into a single argument.
>Multiple -X options aren't supported, nor is combining a -X option
>with other options.
>
>Using a shebang also works in Windows if .py files are associated with
>the py.exe launcher, which can handle multiple arguments in the
>shebang instead of just one.

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.

This has a few advantages:

  - you can use several python-opts

  - your script, unless very trivial, will usually have some reusable pieces; 
    by making it a module with a main() function you can make those pieces 
    available for _other_ modules to import and use!

Making your script a module may seem like some extra effort to little benefit, 
but after you've done it a few times it is easy and I at least now have a suite 
of little modules whose components get reused all the time.

Cheers,
Cameron Simpson <cs at cskk.id.au>



More information about the Python-list mailing list