PyCharm 错误:尝试导入自己的模块时出现“无模块”(python 脚本)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28705029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:38:15  来源:igfitidea点击:

PyCharm error: 'No Module' when trying to import own module (python script)

pythonmodulepycharm

提问by Claus

I have written a module (a file my_mod.pyfile residing in the folder my_module). Currently, I am working in the file cool_script.pythat resides in the folder cur_proj. I have opened the folder in PyCharm using File -- open (and I assume, hence, it is a PyCharm project).

我已经编写了一个模块(my_mod.py驻留在文件夹中的文件文件my_module)。目前,我正在处理位于文件cool_script.py夹中的文件cur_proj。我已经使用 File -- open 在 PyCharm 中打开了文件夹(我假设,因此,它是一个 PyCharm 项目)。

In ProjectView (CMD-7), I can see my project cur_proj(in red) and under "External Libraries" I do see my_module. In cool_script.py, I can write

在 ProjectView (CMD-7) 中,我可以看到我的项目cur_proj(红色),在“外部库”下我可以看到my_module. 在cool_script.py中,我可以写

from my_module import my_mod as mm

and PyCharm even makes suggestion for my_mod. So far so good.

PyCharm 甚至为 my_mod 提出了建议。到现在为止还挺好。

However, when I try to run cool_script.py, PyCharm tells me "No module named my_module"

但是,当我尝试运行 cool_script.py 时,PyCharm 告诉我 “没有名为 my_module 的模块”

This seems strange to me, because

这对我来说似乎很奇怪,因为

A) in the terminal (OS 10.10.2), in python, I can import the module no problem -- there is a corresponding entry in the PYTHONPATH in .bashrc

A)在终端(OS 10.10.2)中,在python中,我可以导入模块没问题-.bashrc中的PYTHONPATH中有相应的条目

B) in PyCharm -- Settings -- Project cur_proj -- Project Interpreter -- CogWheel next to python interpreter -- more -- show paths for selected interpreter icon, the paths from PYTHONPATH do appear (as I think they should)

B) 在 PyCharm -- 设置 -- 项目 cur_proj -- 项目解释器 -- python 解释器旁边的 CogWheel -- 更多 -- 显示所选解释器图标的路径,来自 PYTHONPATH 的路径确实出现(我认为它们应该)

Hence, why do I get the error when I try to run cool_script.py? -- What am I missing?

因此,当我尝试运行cool_script.py 时为什么会出现错误?——我错过了什么?

Notes:

笔记:

Addendum 2015-Feb-25

附录 2015-Feb-25

When I go in PyCharm to Run -- Edit Configurations, for my current project, there are two options that are selected with a check mark: "Add content roots to PYTHONPATH" and "Add source roots to PYTHONPATH". When I have both unchecked, I can load my module.

当我进入 PyCharm 运行 -- 编辑配置时,对于我当前的项目,有两个带有复选标记的选项被选中:“将内容根目录添加到 PYTHONPATH”和“将源目录添加到 PYTHONPATH”。当我都取消选中时,我可以加载我的模块。

So it works now -- but why?

所以它现在有效——但为什么呢?

Further questions emerged:

进一步的问题出现了:

  • What are "content roots" and what are "source roots"? And why does adding something to the PYTHONPATH make it somehow break?
  • should I uncheck both of those options all the time (so also in the defaults, not only the project specific configurations (left panel of the Run/Debug Configurations dialog)?
  • 什么是“内容根”,什么是“源根”?为什么在 PYTHONPATH 中添加一些东西会使它以某种方式中断?
  • 我应该一直取消选中这两个选项吗(在默认设置中也是如此,不仅是项目特定的配置(运行/调试配置对话框的左面板)?

回答by Tom

my_moduleis a folder not a module and you can't import a folder, try moving my_mod.pyto the same folder as the cool_script.pyand then doimport my_mod as mm. This is because python only looks in the current directory and sys.path, and so wont find my_mod.pyunless it's in the same directory

my_module是文件夹而不是模块,您无法导入文件夹,请尝试移动my_mod.py到与 相同的文件夹cool_script.py,然后执行import my_mod as mm. 这是因为 python 只在当前目录和 中sys.path查找,所以my_mod.py除非它在同一目录中,否则不会找到

Or you can look herefor an answer telling you how to import from other directories.

或者您可以在此处查看答案,告诉您如何从其他目录导入。

As to your other questions, I do not know as I do not use PyCharm.

至于你的其他问题,我不知道,因为我不使用 PyCharm。

回答by RA123

Content roots are folders holding your project code while source roots are defined as same too. The only difference i came to understand was that the code in source roots is built before the code in the content root.

内容根是保存项目代码的文件夹,而源根也被定义为相同的。我开始理解的唯一区别是源根中的代码是在内容根中的代码之前构建的。

Unchecking them wouldn't affect the runtime till the point you're not making separate modules in your package which are manually connected to Django. That means if any of your files do not hold the 'from django import...' or any of the function isn't called via django, unchecking these 2 options will result in a malfunction.

取消选中它们不会影响运行时,直到您没有在包中制作单独的模块,这些模块手动连接到 Django。这意味着如果您的任何文件不包含“from django import...”或任何函数未通过 django 调用,则取消选中这两个选项将导致故障。

Update - the problem only arises when using Virtual Environmanet, and only when controlling the project via the provided terminal. Cause the terminal still works via the default system pyhtonpath and not the virtual env. while the python django control panel works fine.

更新 - 该问题仅在使用 Virtual Environmanet 时出现,并且仅在通过提供的终端控制项目时出现。因为终端仍然通过默认系统 pyhtonpath 而不是虚拟环境工作。而 python django 控制面板工作正常。

回答by Shravan Shetty

This can be caused when Python interpreter can't find your code. You have to mention explicitly to Python to find your code in this location.

这可能是由于 Python 解释器找不到您的代码造成的。您必须明确地向 Python 提及才能在此位置找到您的代码。

To do so:

这样做:

  • Go to your python console
  • Add sys.path.extend(['your module location'])to Python console.
  • 转到您的 python 控制台
  • 添加sys.path.extend(['your module location'])到 Python 控制台。

In your case:

在你的情况下:

  • Go to your python console,
  • On the start, write the following code:

    import sys
    sys.path.extend([my module URI location])
    
  • Once you have written this statement you can run following command:

    from mymodule import functions
    
  • 转到您的python控制台,
  • 在开始时,编写以下代码:

    import sys
    sys.path.extend([my module URI location])
    
  • 编写此语句后,您可以运行以下命令:

    from mymodule import functions
    

回答by RubberDuckRabbit

I was getting the error with "Add source roots to PYTHONPATH" as well. My problem was that I had two folders with the same name, like project/subproject1/thing/srcand project/subproject2/thing/srcand I had both of them marked as source root. When I renamed one of the "thing"folders to "thing1"(any unique name), it worked.

我也收到了“将源根目录添加到 PYTHONPATH”的错误消息。我的问题是我有两个同名的文件夹,例如project/subproject1/thing/srcproject/subproject2/thing/src并且我将它们都标记为源根目录。当我将其中一个"thing"文件夹重命名为"thing1"(任何唯一名称)时,它起作用了。

Maybe if PyCharm automatically adds selected source roots, it doesn't use the full path and hence mixes up folders with the same name.

也许如果 PyCharm 自动添加选定的源根目录,它不会使用完整路径,因此会混淆具有相同名称的文件夹。

回答by Beatriz Fonseca

If your own module is in the same path, you need mark the path as Sources Root. In the project explorer, right-click on the directory that you want import. Then select Mark Directory Asand select Sources Root.

如果您自己的模块在同一路径中,则需要将该路径标记为Sources Root. 在项目资源管理器中,右键单击要导入的目录。然后选择Mark Directory As并选择Sources Root

I hope this helps.

我希望这有帮助。

回答by tomchappell

The key confusing step that must be done is to recreate the run configuration for the source file that you're trying to execute, so that the IDE picks up the new paths.

必须完成的关键混淆步骤是为您尝试执行的源文件重新创建运行配置,以便 IDE 选择新路径。

The way that actually worked for me was to go to Run/Edit Configurations..., select the configuration for the file that you're trying to run on the left side, uncheck the "Add source roots to PYTHONPATH" box, save, and then go back and check the box and save. THEN it would work.

实际对我有用的方法是转到运行/编辑配置...,选择您尝试在左侧运行的文件的配置,取消选中“将源根目录添加到 PYTHONPATH”框,保存,然后返回并选中该框并保存。那么它会起作用。

回答by Virendra Patel

What I tried is to source the location where my files are.

我尝试的是找到我的文件所在的位置。

e.g. E:\git_projects\My_project\__init__.py is my location.

例如 E:\git_projects\My_project\__init__.py is my location.

I went to File -> Setting -> Project:My_project -> Project Structure and added the content root to about mention place E:\git_projects\My_project

我去了文件 - >设置 - >项目:My_project - >项目结构并将内容根添加到关于提及的地方 E:\git_projects\My_project

it worked for me.

它对我有用。

回答by AB Abhi

Pycharm 2017.1.1

pycharm 2017.1.1

  1. Click on View->ToolBar& View->Tool Buttons
  2. On the left pane Projectwould be visible, right click on it and press Autoscroll to sourceand then run your code.
  1. 点击View->ToolBar&View->Tool Buttons
  2. 在左侧窗格Project中将可见,右键单击它并按下Autoscroll to source然后运行您的代码。

This worked for me.

这对我有用。

回答by Oleg Silkin

PyCharm Community/Professional 2018.2.1

PyCharm 社区/专业版 2018.2.1

I was having this problem just now and I was able to solve it in sort of a similar way that @Beatriz Fonseca and @Julie pointed out.

我刚才遇到了这个问题,我能够以类似于@Beatriz Fonseca 和@Julie 指出的方式解决它。

If you go to File-> Settings-> Project: YourProjectName-> Project Structure, you'll have a directory layout of the project you're currently working in. You'll have to go through your directories and label them as being either the Sourcedirectory for all your Source files, or as a Resourcefolder for files that are strictly for importing.

如果您转到File-> Settings-> Project: YourProjectName-> Project Structure,您将拥有当前正在处理的项目的目录布局。您必须浏览您的目录并将它们标记Source为所有源文件的目录,或作为Resource严格用于导入的文件的文件夹。

You'll also want to make sure that you place __init__.pyfiles within your resource directories, or really anywhere that you want to import from, and it'll work perfectly fine.

您还需要确保将__init__.py文件放置在您的资源目录中,或者您想要从中导入的任何地方,并且它会完全正常工作。

I hope this answer helps someone, and hopefully JetBrains will fix this annoying bug.

我希望这个答案对某人有所帮助,并希望 JetBrains 能够修复这个烦人的错误。

回答by PyFox

The solution for this problem without having to Mark Directory as Source Root is to Edit Run Configurations and in Execution select the option "Redirect input from" and choose script you want to run. This works because it is then treated as if the script was run interactively in this directory. However Python will still mark the module name with an error "no module named x":

解决此问题而不必将目录标记为源根的解决方案是编辑运行配置并在执行中选择选项“重定向输入”并选择要运行的脚本。这是有效的,因为它被视为脚本在此目录中以交互方式运行。但是 Python 仍然会用错误“没有名为 x 的模块”来标记模块名称:

Redirect input from:

重定向输入:

When the interpreter executes the import statement, it searches for x.py in a list of directories assembled from the following sources:

当解释器执行 import 语句时,它会在从以下来源组装的目录列表中搜索 x.py:

  1. The directory from which the input script was run or the current directory if the interpreter is being run interactively
  2. The list of directories contained in the PYTHONPATH environment variable, if it is set.
  3. An installation-dependent list of directories configured at the time Python is installed, in my case usr/lib/python3.6 on Ubuntu.
  1. 运行输入脚本的目录或当前目录(如果解释器以交互方式运行)
  2. PYTHONPATH 环境变量中包含的目录列表(如果已设置)。
  3. 在安装 Python 时配置的依赖于安装的目录列表,在我的例子中是 Ubuntu 上的 usr/lib/python3.6。