The original python command line

Damjan Georgievski gdamjan at gmail.com
Sun Mar 4 00:52:26 EST 2012


> How can I get the *really* original command line that started my python
> interpreter?
> 
> Werkzeug has a WSGI server which reloads itself when files are changed
> on disk. It uses `args = [sys.executable] + sys.argv` to kind of
> recreate the command line, and the uses subprocess.call to run that
> command line.
> 
> BUT that's problematic as, when you run::
> 
> 	python -m mypackage --config
> 
> sys.argv printed in mypackage/__main__.py will be::
> 
> 	['/full/path/to/mypackage/__main__.py', '--config']
> 
> so you get::
> 
> 	python /full/path/to/mypackage/__main__.py --config
> 
> instead of::
> 
> 	python -m mypackage --config
> 
> 
> the difference in the 2 cases is what the current package is, and
> whether you can use relative imports.

BTW, the same thing happens in Python 3.2.2. To reproduce::

mkdir /tmp/X
cd /tmp/X

mkdir mypackage
touch  mypackage/__init__.py mypackage/dummy.py

cat <<EOF > mypackage/__main__.py
from __future__ import print_function, absolute_import
import os, sys, subprocess

def rerun():
    new_environ = os.environ.copy()
    new_environ['TEST_CHILD'] = 'true'
    args = [sys.executable] + sys.argv
    subprocess.call(args, env=new_environ)

if os.environ.get('TEST_CHILD') != 'true':
    Role = 'Parent'
    rerun()
else:
    Role = 'Child'

try:
    from . import dummy
except:
    print('Exception in %s' % Role)
else:
    print('Success in %s' % Role)
EOF



Both::
	
	python2 -m mypackage

or::

	python3 -m mypackage


will print::

	Exception in Child
	Success in Parent



More information about the Python-list mailing list