导入自行编写的Python Modu

2024-06-08 03:39:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经阅读了很多其他与此相关的S-O问题,但仍然难以让它为我工作。提前为重叠部分道歉!我在Windows7上使用Python2.7.10。

我正试图在PyCharm的Python控制台中导入一个我编写的模块(怀疑这是否重要)。在控制台中,我导航到包含我的模块的目录中:

/users/usn/.../Tools/my_file.py

这可以用pwd来确认。然后我试着

import my_file

但是得到错误importorror:没有名为my_file的模块。我尝试了很多变化,但都没有成功。如何在控制台中导入我编写的模块?

谢谢


Tags: 模块pyimport目录my错误pwdtools
3条回答

要导入模块,需要临时或永久地将其目录添加到环境变量中。

暂时

import sys
sys.path.append("/path/to/my/modules/")
import my_module

永久

将以下行添加到.bashrc文件(在linux中)并在终端中执行source ~/.bashrc

export PYTHONPATH="${PYTHONPATH}:/path/to/my/modules/"

信用/来源:saarrrranother stackexchange question

您需要将环境扩展到模块所在的文件夹。将此项添加到要导入模块的文件的顶部。

import sys
sys.path.append("/users/usn/.../Tools/")
import my_file

您也可以使用imp

import imp
my_file = imp.load_source('name', '/users/usn/.../Tools/my_file.py')

Load and initialize a module implemented as a Python source file and return its module object. If the module was already initialized, it will be initialized again. The name argument is used to create or access a module object. The pathname argument points to the source file. The file argument is the source file, open for reading as text, from the beginning.

相关问题 更多 >

    热门问题