[Python-ideas] Syntax to import modules before running command from the command line

Nick Coghlan ncoghlan at gmail.com
Fri Jan 5 03:12:59 EST 2018


On 5 January 2018 at 16:28, Steve Barnes <gadgetsteve at live.co.uk> wrote:
> Currently invoking `python -c "some;separated;set of commands;"` will,
> if you need to use any library functions, require one or more import
> somelib; sections in the execution string. This results in rather
> complex "one liners".
>
> On the other hand `python -m somelib` will load somelib and attempt to
> execute its `__main__()` or give an error if there isn't one.

That's not quite how the -m switch works, but that doesn't affect your
core point: "-m somemodule" terminates the option list and defines
what will be run as `__main__`, so you can't compose it with other
options (like `-c`).

> What I would like to suggest is a mechanism to pre-load libraries before
> evaluating the -c option as this would allow the use of code from
> libraries that don't have a `__main__` function, or those that do but it
> doesn't do what you want.

This could be an interesting alternative to the old "python -C" idea
in https://bugs.python.org/issue14803 (which suggests adding an
alternative to "-c" that runs the given code *before* running
`__main__`, rather than running it *as* `__main__`).

To summarise some of the use cases from that discussion:

* setting `__main__.__requires__` to change how `import pkg_resources`
selects default package versions
* reducing the proliferation of `-X` options to enable modules like
tracemalloc and faulthandler
* providing a way to enable code coverage as early as possible on
startup (and have the setting be inherited by subprocesses)

The main downside I'd see compared to that `python -C` and
PYTHONRUNFIRST idea is that it might encourage the definition of
modules with side-effects in order to use it to reconfigure the
interpreter at startup.

That concern could potentially be mitigated if we did both:

* -M/PYTHONIMPORTFIRST: implicit imports in __main__ on startup
* -C/PYTHONRUNFIRST: code to run in __main__ on startup (after the
implicit imports)

However, the issue then is that "python -M numpy" would just be a less
flexible alternative to a command like "python -C 'import numpy as
np'".

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list