What is mechanism that is causing "google" module to be imported in python 2.7

Viewed 65

This is python 2.7 on MacOS

Here's my testcase - file called mytest.py:

import sys
print sys.modules.keys()

I run as python -s mytest.py.

output is: ['google', 'copy_reg', 'sre_compile', '_sre', 'encodings', 'site', '__builtin__', 'sysconfig', '__main__', 'encodings.encodings', 'abc', 'posixpath', '_weakrefset', 'errno', 'google.logging', 'encodings.codecs', 'sre_constants', 're', '_abcoll', 'types', '_codecs', 'encodings.__builtin__', '_warnings', 'genericpath', 'stat', 'zipimport', '_sysconfigdata', 'warnings', 'UserDict', 'encodings.utf_8', 'sys', '_osx_support', 'codecs', 'os.path', '_locale', 'signal', 'traceback', 'linecache', 'posix', 'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref']

I believe that google is being imported via a .pth file that is processed by the automatically imported site.py, but my understanding is that the -s switch suppresses the automatic site.py import.

What is causing "google" to be imported?

2 Answers

According to [Python 2.Docs]: Command line and environment - Miscellaneous options (also visible when typing python -h in terminal):

-s

    Don’t add the user site-packages directory to sys.path.
    New in version 2.6.
    See also PEP 370 - Per user site-packages directory

-S

    Disable the import of the module site and the site-dependent manipulations of sys.path that it entails.

You passed -s (lower case), instead of -S (higher case), so site.py was still executed at startup (and also the .pth file that imports google).

To fix it, pass the proper argument to the interpreter:

python -S mytest.py

You want captial -S to exclude the site.py module.

Also, if you run Python with verbose mode on, it prints debug info for each import to stderr:

$ python -S -v -c "pass"
# installing zipimport hook
import zipimport # builtin
# installed zipimport hook
import encodings # directory /usr/lib/python2.7/encodings
# /usr/lib/python2.7/encodings/__init__.pyc matches /usr/lib/python2.7/encodings/__init__.py
import encodings # precompiled from /usr/lib/python2.7/encodings/__init__.pyc
# /usr/lib/python2.7/codecs.pyc matches /usr/lib/python2.7/codecs.py
import codecs # precompiled from /usr/lib/python2.7/codecs.pyc
import _codecs # builtin
...

Search through that for the google module and the combination of the location and order may give a hint.

Related