Retrieving the full command line

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jan 22 18:46:49 EST 2013


On Tue, 22 Jan 2013 15:07:18 +0000, Tim Golden wrote:

> On 22/01/2013 14:53, Terry Reedy wrote:
>> On 1/22/2013 4:24 AM, Tim Golden wrote:
>>> [Python 2.7/3.3 (and hg tip) running on Windows. Not Windows-specific,
>>> though].
>>>
>>> I use the python -mpackage incantation to run a package which has a
>>> __main__.py module and which uses relative imports internally.
>>>
>>> I'm developing under cherrypy which includes a reloader for
>>> development. The reloader attempts to rebuild the original command
>>> line by combining sys.executable and sys.argv and then does an execv.
>>>
>>> There does not appear to be any way within Python of determining the
>>> command line I used. The combination of sys.executable and sys.argv in
>>> this case will look like: "c:\python33\python.exe app/__main__.py".
>>> But running this precludes the use of package-relative imports.
>> 
>> If I understand right, the reloader should be updated to translate
>> 'x/__main__.py' to '-m x'. Filenames of form'__x__' are reserved, in a
>> sense, like similar identifiers in programs, and '__main__.py' should
>> not be used for a file meant to executed directly.
> 
> To be clear: it's Python itself, not the reloader, which is coming up
> with __main__.py. sys.executable is "c:\python33\python.exe" and
> sys.argv is ['c:\path\to\__main__.py'] for a program which has been
> started by "c:\python33\python.exe -mpath\to".

I don't believe you can give direct paths to the -m flag. It uses the 
normal import mechanism to locate a module or package, so you have to 
give it a name which would be importable.

c:\python33\python.exe -m app

would work, where "app" is either a package or module:

C:\something\on\PYTHONPATH\app\__main__.py
C:\something\on\PYTHONPATH\app.py


> Obviously, there is any number of ways around this specific issue,
> including what you suggest: a canonical rewrite of "python
> path\to\__main__.py" into "python -mpath\to". But it's not clear to me
> that this rewrite should be the responsibility of calling code.


I am a bit disturbed that you cannot distinguish between:

python C:\something\on\pythonpath\app\__main__.py

python -m app


by inspecting the command line. I consider it a bug, or at least a 
misfeature, if Python transforms the command line before making it 
available in sys.argv.


-- 
Steven



More information about the Python-list mailing list