如何在共享文件夹中导入python模块?
我在 Windows 计算机上的共享文件夹中有一些 python 模块。
文件是 \mtl12366150\test\mymodule.py
os.path.exists 告诉我这个路径是有效的。
我将文件夹 \mtl12366150\test 附加到 sys.path 中(并且 os.path.exists 告诉我该路径是有效的)。
当我尝试导入 mymodule 时,出现错误,提示该模块不存在。
有没有办法导入位于共享路径中的模块?
I have some python modules in a shared folder on a Windows machine.
The file is \mtl12366150\test\mymodule.py
os.path.exists tells me this path is valid.
I appended to sys.path the folder \mtl12366150\test (and os.path.exists tells me this path is valid).
When I try to import mymodule I get an error saying the module doesn't exist.
Is there a way to import module that are located in shared path?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您是否忘记在附加 sys.path 组件中使用原始字符串或转义反斜杠? 请记住,“\t”是制表符,而 r“\t”或“\t”是反斜杠后跟制表符。
在大多数应用程序中,即使对于 Windows 路径,您实际上最好使用正斜杠而不是反斜杠,并且大多数 Windows API 都会很好地接受它们。 否则,请小心使用原始字符串!
[简单的Python模块上面的目录中不需要添加__init__.py文件]
Did you forget to use a raw string, or escape the backslashes, in your additional sys.path component? Remember that "\t" is a tab, whereas r"\t" or "\t" are a backslash followed by a tab.
In most applications you are actually better off using forward slashes rather than backslashes even for Windows paths, and most Windows APIs will accept them just fine. Otherwise, be careful to use raw strings!
[There is no need to add __init__.py files in the directories above a simple Python module]
你说 os.path.exists() 说路径在那里,但你绝对确定你逃脱了 \ 吗? 尝试这个:
You say os.path.exists() says the path is there, but are you absolutely sure you escaped the \? Try this:
要导入 python 项目,其上方的每个文件夹中都需要有一个
__init__.py
文件,以表明它是有效的 python 包。__init__.py
文件可以为空,它们只是为了显示结构。To import a python item there needs to be a
__init__.py
file in each of the folder above it to show that it is a valid python package.The
__init__.py
files can be empty, they are there just to show structure.正如 S.Lott 所说,最好的方法是设置 PYTHONPATH 环境变量。 我手边没有 Windows 盒子,但从命令提示符来看它看起来像这样:
As S.Lott said, the best approach is to set the PYTHONPATH environment variable. I don't have a windows box handy, but it would look something like this from your command prompt:
我想我找到了答案。 我之前使用的是 Python 2.6.1,现在可以使用 Python 2.6.2。 我在 python 2.5.4 中也有同样的错误行为。
I think I found the answer. I was using Python 2.6.1 and with Python 2.6.2 it now works. I had the same faulty behavior with python 2.5.4.
“我附加到 sys.path ...”
请不要这样做。
从应用程序外部设置
PYTHONPATH
环境变量。"I appended to sys.path ..."
Please don't.
Set the
PYTHONPATH
environment variable from outside your application.