如何从当前非默认目录导入模块
我正在使用Python 2.7。我对 python 语言相当陌生。我有两个 python 模块 - “Trailcrest.py”和“Glyph.py”,它们都在同一文件夹中,但不在 Python27 文件夹中。
我需要将“Trailcrest.py”导入“Glyph.py”,但我收到消息“不存在这样的模块”。
此外,无论我使用什么方式导入模块都不需要依赖于固态路径。该程序是跨平台的,并且可以根据用户的喜好更改路径。但是,这两个模块将始终位于同一文件夹中。
我该怎么做?
I'm using Python 2.7. I'm rather new to the python langauge. I have two python modules - "Trailcrest.py" and "Glyph.py", both in the same folder, but not in the Python27 folder.
I need to import "Trailcrest.py" into "Glyph.py", but I am getting the message that "no such module exists".
Additionally, whatever means I use to import the module needs to not be dependent on a solid-state path. This program is cross-platform, and the path can be changed depending on the user's preferences. However, these two modules will always be in the same folder together.
How do I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您在同一个文件夹中有
Trailcrest.py
和Glyph.py
,则将一个导入到另一个中就像这样简单:如果这不起作用,则似乎存在某些问题你的Python设置有问题。您可能想检查 sys.path 中的内容。
If you have
Trailcrest.py
andGlyph.py
in the same folder, importing one into the other is as simple as:If this does not work, there seems to be something wrong with your Python setup. You might want to check what's in
sys.path
.详细说明 Ferdinand Beyer 的答案,
sys.path
是默认模块导入器检查的文件位置列表。有些(尽管不是所有)Python 安装都会将当前目录或 __main__ 模块的目录添加到路径中。为了确保相对于给定模块的路径在该模块中是可导入的,请执行以下操作:但是类似的操作不应使其成为“生产”产品。相反,使用诸如
distutils
之类的工具将模块的包安装到 python site-packages 目录中。To elaborate a bit on Ferdinand Beyer's answer,
sys.path
is a list of file locations that the default module importer checks. Some, though not all installations of python will add the current directory or the directory of the__main__
module to the path. To make sure that the paths relative to a given module are importable in that module, do something like this:But something like that shouldn't ever make it into a "production" product. Instead, use something like
distutils
to install the module's package into the python site-packages directory.这也可以使用环境变量 PYTHONPATH 来实现,它也会影响 Python 的搜索路径。这可以在 shell 脚本中完成,这样就不需要更改 Python 文件。如果您希望从当前工作目录导入,请在 bash 中使用
.
表示法:This can also be achieved using the environment variable
PYTHONPATH
which also influences Python's search path. This can be done in a shell script so that the Python files do not need to be altered. If you want it to import from the current working directory use the.
notation in bash: