Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

sublimetext3 - How can I import a Python module in a Sublime Text plugin?

I'm having trouble making a Sublime Text 3 plugin. I just installed wxPython with Python 2.7 on my Macintosh.

In the terminal, my Mac can find wxPython (import wx). But the source code of a Sublime Text plugin cannot import wxPython.

You can check out the screen capture below.

ImportError: No module named 'wx'

How can I fix this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Plugins are executed using Sublime's internal Python interpreter, not any version of Python installed on your computer. Nearly all of the standard library is included, but a few packages (including Tkinter, among others) are not. To my knowledge it is not possible to use pip, for example, to install 3rd-party modules into Sublime Text.

However, if you would like to include some 3rd-party code, just put it in your plugin's directory. For example, if you store your plugin code in Packages/MyPlugin (where Packages is the directory opened by selecting Preferences -> Browse Packages...), and you want to include the 3rd-party library foobar, just copy the foobar directory into Packages/MyPlugin. Then, in your plugin code, use the following template, assuming you're trying to code for both ST3 (Python 3.3) and ST2 (Python 2.6):

try: #ST3
    from .foobar import mymodule
except ImportError: #ST2
    from foobar import mymodule

Obviously, if you're just planning on supporting ST3 (there are enough differences in the API to make programming for both versions annoying), you won't need the try/except clause. Also, if you are going to be distributing your plugin via Package Control or some other method, make sure you can redistribute the 3rd-party code, and that your license is compatible with its license.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...