Manually importing gtk fails: module not found

2019-09-09 11:46发布

问题:

So I would like to execute a python script from command line then and again, and it has to be very quick. Imports in python are slow because the entire sys.path is searched for the respective modules.

Thus, my idea was to replace

import sys
import gdk.gtk

with

import sys
import imp
imp.load_source("gtk.gdk", "/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py")

(I got that path from os.path.abspath(gtk.__file__)

However, python tells me this is invalid: module 'gtk' not found. But isn't this exactly what I am trying to import here?

  1. what am I doing wrong? or
  2. would there be a better way to achieve a direct import?

(error messages in detail below)

/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:23: 
    RuntimeWarning: Parent module 'gtk' not found while handling absolute import
    import sys
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:30: 
    RuntimeWarning: Parent module 'gtk' not found while handling absolute import
    import gobject as _gobject
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: 
    RuntimeWarning: Parent module 'gtk' not found while handling absolute import
    from gtk import _gtk

回答1:

Importing the compiled __init__.pyc seems to work here, using import_module instead of import_source. However, the import is still notably slow...

# done manually once
file,filename,descr=imp.find_module('gtk')
print file,filename,descr

script:

# script
gtk=imp.load_module('gtk',FILE,FILENAME,DESCRIPTION) # the respective values
# gtk=imp.load_module("gtk",None,"/usr/lib/python2.7/dist-packages/gtk-2.0/gtk",('','',5))
from gtk import gdk