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

Nick Coghlan ncoghlan at gmail.com
Tue Jan 9 21:39:31 EST 2018


On 10 January 2018 at 07:54, Barry Warsaw <barry at python.org> wrote:
> Steve Barnes 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.
>>
>> 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.
>
> It would be really cool if you could somehow write a file with a bunch
> of commands in it, and then get Python to execute those commands.  Then
> it could still be a one line invocation, but you could do much more
> complex things, including import a bunch of modules before executing
> some code.

You jest, but doing that and then going on to process the rest of the
command line the same way the interpreter normally would is genuinely
tricky. Even `python -m runpy [other args]` doesn't emulate it
perfectly, and its responsible for implementing large chunks of the
regular behaviour :)

For the coverage.py use case, an environment-based solution is also
genuinely helpful, since you typically can't modify subprocess
invocations just because the software is being tested. At the moment,
there are approaches that rely on using either `sitecustomize` or
`*.pth` files, but being able to write `PYTHONRUNFIRST="import
coverage; coverage.process_startup()"` would be a fair bit clearer
about what was actually going on.

That example also shows why I'm wary of offering an import-only
version of this: I believe it would encourage folks to write modules
that have side effects on import, which is something we try to avoid
doing.

Cheers,
Nick.

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


More information about the Python-ideas mailing list