简体   繁体   English

PyCharm ImportError:如何导入自己的模块?

[英]PyCharm ImportError: how can you import your own modules?

I'm working with Python 2.7.3 using PyCharm in Mountain Lion. 我正在使用Mountain Lion中的PyCharm使用Python 2.7.3。 I'm trying to build my own library with functions that I use often. 我正在尝试使用经常使用的功能来构建自己的库。

I added the library directory to the system path, and to the Pythonpath, and everything works correctly using the terminal, but not in PyCharm. 我将库目录添加到系统路径和Pythonpath,并且一切都可以使用终端正常运行,但不能在PyCharm中运行。

I've set the Project Interpreter to be the one that I'm using in the terminal, and checked that the paths are OK, but I'm not able to use my modules from PyCharm. 我将项目解释器设置为我在终端中使用的解释器,并检查路径是否正常,但是我无法使用PyCharm中的模块。 When I do: 当我做:

import my_lib

and execute it, it says: 并执行它,它说:

ImportError: No module named my_lib

The folder structure I use is like this: 我使用的文件夹结构是这样的:

/Users/myuser/code/__init__.py
                  /my_lib/__init__.py
                         /function1
                         /function2
                         / ...

And the path includes /Users/myuser/code and I've added _/Users/myuser/code/my_lib_ with the hope that this was the problem but had no luck. 路径包括/ Users / myuser / code ,我添加了_ / Users / myuser / code / my_lib_,希望这是问题所在,但没有运气。 By the way, both of the init files are empty. 顺便说一下,两个初始化文件都是空的。

Does any of you know why this would happen? 你们当中有人知道为什么会这样吗?

I couldn't understand completely but, I think you are looking for following solution. 我无法完全理解,但是,我认为您正在寻找以下解决方案。

To be able to add a lib from specific path, you can use 为了能够从特定路径添加库,可以使用

import sys
sys.path.insert(0, "my_lib/function1)
# suppose that in function1, there is mylib.py file so

import mylib

You need to add your library to the "External Libraries" That are visible in Project Window. 您需要将库添加到在“项目”窗口中可见的“外部库”。

What id is coping my lib folder to the C:\\Python\\Lib\\My_lib 什么id将我的lib文件夹复制到C:\\ Python \\ Lib \\ My_lib

Work like a charm ;) 像魅力一样工作;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM