Retrieving the full command line

Oscar Benjamin oscar.j.benjamin at
Thu Jan 24 12:30:29 CET 2013

On 24 January 2013 10:56, Tim Golden <mail at> wrote:
> On 24/01/2013 10:06, Oscar Benjamin wrote:
>> On 24 January 2013 04:49, Steven D'Aprano
>> <steve+comp.lang.python at> wrote:
>> [SNIP]
>>> Contrariwise, I don't believe that there is currently *any* way to
>>> distinguish between running a script with or without -m. That should be
>>> fixed.
>> As I said earlier in the thread, the __package__ module global
>> distinguishes the two cases:
>> ~$ mkdir pkg
>> ~$ touch pkg/
>> ~$ vim pkg/
>> ~$ cat pkg/
>> import sys
>> if __package__ is None:
>>     cmdline = [sys.executable] + sys.argv
>> else:
>>     cmdline = [sys.executable, '-m', __package__] + sys.argv[1:]
>> print(cmdline)
>> ~$ python pkg/ arg1 arg2
>> ['q:\\tools\\Python27\\python.exe', 'pkg/', 'arg1', 'arg2']
>> ~$ python -m pkg arg1 arg2
>> ['q:\\tools\\Python27\\python.exe', '-m', 'pkg', 'arg1', 'arg2']
> Reasonable (and thanks for the clear example), but it doesn't work
> if the package which is reconstructing the command line the package
> which was the target of the original command line. In my case,
> I'm making use of the cherrypy reloader, whose __package__ is
> cherrypy.process. But the command which invoked the program was
> python -m myapp.
> ie I'm issuing "python -m myapp". In myapp.__main__ I'm importing
> cherrypy, itself a package, and somewhere in cherrypy.whatever there is
> code which attempts to reconstruct the command line.

Easy enough:

~$ mkdir pkg
~$ touch pkg/
~$ vim pkg/
~$ cat pkg/
import pkg.whatever
~$ vim pkg/
~$ cat pkg/
import sys
import pkg.__main__ as main
cmdline = [sys.executable, '-m', main.__package__] + sys.argv[1:]
~$ python -m pkg
['q:\\tools\\Python27\\python.exe', '-m', 'pkg']
~$ python -m pkg arg1 arg32
['q:\\tools\\Python27\\python.exe', '-m', 'pkg', 'arg1', 'arg32']

I don't really understand what your spec is. Why do you need to
inspect this information from sys.argv? Can you not just always use
'python -m pkg' as your entry point?


More information about the Python-list mailing list