Retrieving the full command line

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Jan 22 20:14:15 EST 2013


On 22 January 2013 09:24, Tim Golden <mail at timgolden.me.uk> 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.

I tried this on Linux but I imagine that it works the same on Windows.
You can check the value of the __package__ module global:

~$ mkdir tmp
~$ touch tmp/__init__.py
~$ vim tmp/__main__.py
~$ cat tmp/__main__.py
if __package__ is None:
    print 'Running as a script'
else:
    print 'Running with the -m option'
~$ python tmp/__main__.py
Running as a script
~$ python -m tmp
Running with the -m option


Oscar



More information about the Python-list mailing list