标签归档:pycharm

如何配置PyCharm以运行py.test测试?

问题:如何配置PyCharm以运行py.test测试?

我想开始为我的Python代码编写单元测试,而py.test框架听起来比Python捆绑的unittest更好。因此,我向项目添加了“ tests”目录,并向其添加了test_sample.py。现在,我想配置PyCharm以运行“ tests”目录中的所有测试。

据称,PyCharm 在其测试运行程序支持py.test。您应该能够创建运行/调试配置来运行测试,并且PyCharm据称具有专门用于py.test“创建配置”对话框。但这是他们关于该主题的文档的完整范围,我无法在任何地方找到这个所谓的对话框。

如果在“项目”工具窗口中右键单击目录,则应该看到“创建<名称>”菜单项,但是唯一以“创建”开头的菜单项是“创建运行配置”。好的,也许文档只是错误的,“创建运行配置”听起来确实很有希望。不幸的是,其子菜单中仅有的两项是“ C:\ mypath …中的Unittests”和“ C:\ mypath …中的Doctests”,都不适用-我既未使用unittest也未使用doctest。py.test没有菜单项。

如果我打开test_sample.py并在编辑器窗口中单击鼠标右键,则会得到承诺的“创建<名称>”菜单项:有“在test_sa中创建’Unittests …’…”,然后是“运行” “ test_sa中的单元测试…”和“调试test_sa中的单元测试…”。同样,这都是单元测试框架所特有的。py.test没有。

如果我确实尝试显示“ unittest”的菜单项,则会出现一个对话框,其中包含“名称”,“类型”,带有“文件夹”,“模式”,“脚本”和“类”的“测试”组框”和“函数”等。这听起来与为Python单元测试添加配置的对话框所记录的内容完全不同,而不像应该显示的“名称”和“运行测试”以及“关键字”选项一样在py.test对话框的配置中。对话框中没有任何内容可以切换我要添加的测试框架。

我在Windows上使用Python 3.1.3和pytest 2.0.3的PyCharm 1.5.2。我可以从命令行成功运行py.test测试,所以这不是像pytest未正确安装那样的简单操作。

如何配置PyCharm以运行py.test测试?

I want to start writing unit tests for my Python code, and the py.test framework sounds like a better bet than Python’s bundled unittest. So I added a “tests” directory to my project, and added test_sample.py to it. Now I want to configure PyCharm to run all the tests in my “tests” directory.

PyCharm allegedly supports py.test in its test runner. You’re supposed to be able to create a run/debug configuration to run your tests, and PyCharm allegedly has a “create configuration” dialog box specifically for py.test. But that’s the complete extent of their documentation on the subject, and I can’t find this alleged dialog box anywhere.

If I right-click the directory in the Project tool window, I’m supposed to see a “Create <name>” menu item, but the only menu item starting with “Create” is “Create Run Configuration”. Okay, maybe the documentation is just wrong, and “Create Run Configuration” does sound promising. Unfortunately, the only two items in its submenu are “Unittests in C:\mypath…” and “Doctests in C:\mypath…”, neither of which applies — I’m using neither unittest nor doctest. There is no menu item for py.test.

If I open my test_sample.py and right-click in the editor window, I do get the promised “Create <name>” menu items: there’s “Create ‘Unittests in test_sa…’…”, followed by “Run ‘Unittests in test_sa…'” and “Debug ‘Unittests in test_sa…'”. So again, it’s all specific to the unittest framework; nothing for py.test.

If I do try the menu items that say “unittest”, I get a dialog box with options for “Name”, “Type”, a “Tests” group box with “Folder” and “Pattern” and “Script” and “Class” and “Function”, etc. This sounds exactly like what’s documented as the dialog to add a configuration for Python Unit Test, and not like the “Name” and “Test to run” and “Keywords” options that are supposed to show up in the configuration for py.test dialog. There’s nothing inside the dialog to switch which test framework I’m adding.

I’m using PyCharm 1.5.2 on Windows with Python 3.1.3 and pytest 2.0.3. I can successfully run py.test on my tests from the command line, so it’s not something simple like pytest not being installed properly.

How do I configure PyCharm to run my py.test tests?


回答 0

请转到文件| 设置| 工具| Python Integrated Tools,并将默认测试运行程序更改为py.test。然后,您将获得py.test选项来创建测试,而不是unittest。

Please go to File | Settings | Tools | Python Integrated Tools and change the default test runner to py.test. Then you’ll get the py.test option to create tests instead of the unittest one.


回答 1

PyCharm 2017.3

  1. Preference -> Tools -> Python integrated Tools-选择py.testDefault test runner
  2. 如果您使用Django- Preference -> Languages&Frameworks -> Django勾选Do not use Django Test runner
  3. 从中清除所有以前存在的测试配置Run/Debug configuration,否则将使用这些较旧的配置运行测试。
  4. 要设置一些默认的其他参数,请更新py.test默认配置。 Run/Debug Configuration -> Defaults -> Python tests -> py.test -> Additional Arguments

PyCharm 2017.3

  1. Preference -> Tools -> Python integrated Tools – Choose py.test as Default test runner.
  2. If you use Django Preference -> Languages&Frameworks -> Django – Set tick on Do not use Django Test runner
  3. Clear all previously existing test configurations from Run/Debug configuration, otherwise tests will be run with those older configurations.
  4. To set some default additional arguments update py.test default configuration. Run/Debug Configuration -> Defaults -> Python tests -> py.test -> Additional Arguments

回答 2

我认为您需要使用工具栏上的“运行/调试配置”项。单击它并单击“编辑配置”(或使用菜单项“运行”->“编辑配置”)。在左侧窗格的“默认”部分中,有一个“ py.test”项,我认为这是您想要的。

我还发现该手册与此用户界面不匹配。希望我正确理解了这个问题,对您有所帮助。

I think you need to use the Run/Debug Configuration item on the toolbar. Click it and ‘Edit Configurations’ (or alternatively use the menu item Run->Edit Configurations). In the ‘Defaults’ section in the left pane there is a ‘py.test’ item which I think is what you want.

I also found that the manual didn’t match up to the UI for this. Hope I’ve understood the problem correctly and that helps.


回答 3

这是我使它与pytest 3.7.2(通过pip安装)和pycharms一起工作的方式2017.3

  1. edit configurations

  1. 添加一个新的运行配置并选择 py.test

  1. 在运行配置详细信息中,您需要将target= python和下面的未命名字段设置为tests。看起来这是您的测试文件夹的名称。不太确定强硬。我还建议使用该-s参数,以便在调试测试时,控制台将正常运行。没有参数pytest会捕获输出,并使调试控制台出错。

  1. 我的测试文件夹如下所示。这刚好在我的项目(my_project/tests)的根目录之下。

  1. 我的foobar_test.py文件:(无需导入):
def test_foobar():
    打印(“ Hello pytest”)
    断言为真
  1. 使用常规运行命令运行它

Here is how I made it work with pytest 3.7.2 (installed via pip) and pycharms 2017.3:

  1. Go to edit configurations

  1. Add a new run config and select py.test

  1. In the run config details, you need to set target=python and the unnamed field below to tests. It looks like this is the name of your test folder. Not too sure tough. I also recommend the -s argument so that if you debug your tests, the console will behave properly. Without the argument pytest captures the output and makes the debug console buggy.

  1. My tests folder looks like that. This is just below the root of my project (my_project/tests).

  1. My foobar_test.py file: (no imports needed):
def test_foobar():
    print("hello pytest")
    assert True
  1. Run it with the normal run command


回答 4

可以肯定地说,它的文献不多。从默认设置添加新配置后,您将可以运行“ / Applications / PyCharm CE.app/Contents/helpers/pycharm/pytestrunner.py”脚本。它没有记录,并且有自己的命令行参数构想。

您可以:

  1. 尝试玩一下,反转脚本,看看是否可以使py.test接受参数。它可能会起作用;上半个小时对我来说不是。
  2. 只需从控制台运行“ py.test * .py”即可。

奇怪的是,您很难找到任何讨论,因为JetBrains擅长用自己的页面轰炸Google算法。

It’s poorly documented to be sure. Once you get add a new configuration from defaults, you will be in the realm of running the “/Applications/PyCharm CE.app/Contents/helpers/pycharm/pytestrunner.py” script. It’s not documented and has its own ideas of command line arguments.

You can:

  1. Try to play around, reverse the script, and see if you can somehow get py.test to accept arguments. It might work; it didn’t in the first half hour for me.
  2. Just run “py.test *.py” from a console.

Oddly, you will find it hard to find any discussion as JetBrains does a good job of bombing Google algorithms with its own pages.


回答 5

当我遇到相同的问题并找到解决方案pycharm版本时找到此线程:2017.1.2转到“首选项”->“工具”->“ Python集成工具”,然后从右侧面板中将默认测试运行器设置为py.test解决我的问题

find this thread when I hit the same question and found the solution pycharm version:2017.1.2 go to “Preferences” -> “Tools” -> “Python Integrated Tools” and set the default test runner from right side panel as py.test solve my problem


回答 6

在pycharm 2019.2中,您可以简单地执行以下操作以运行所有测试:

  1. 运行>编辑配置>添加pytest
  2. 设置选项,如以下屏幕截图所示
  3. 单击调试(或使用快捷键Shift + Alt + F9运行pytest)

有关pytest与pycharm的更高集成,请参阅https://www.jetbrains.com/help/pycharm/pytest.html

In pycharm 2019.2, you can simply do this to run all tests:

  1. Run > Edit Configurations > Add pytest
  2. Set options as shown in following screenshot
  3. Click on Debug (or run pytest using e.g. hotkeys Shift+Alt+F9)

For a higher integration of pytest into pycharm, see https://www.jetbrains.com/help/pycharm/pytest.html


回答 7

我正在使用2018.2

我运行->编辑配置…然后单击模式对话框左上方的+。选择“ python测试”-> py.test然后给它一个名称,例如“使用py.test进行所有测试”

我选择“目标:模块名称”,然后将测试放在其中的模块(对我来说就是“测试”),或者将测试与代码混合在一起的地方放在所有代码所在的模块中。这让我不寒而栗。

我设置了Python解释器。

我将工作目录设置为项目目录。

I’m using 2018.2

I do Run -> Edit Configurations… Then click the + in the upper left of the modal dialog. Select “python tests” -> py.test Then I give it a name like “All test with py.test”

I select Target: module name and put in the module where my tests are (that is ‘tests’ for me) or the module where all my code is if my tests are mixed in with my code. This was tripping me up.

I set the Python interpreter.

I set the working directory to the project directory.


回答 8

使用特殊的Conda python安装程序,其中包括py.test的pip安装以及Specs插件的使用(选项–spec)(对于Rspec来说,就像不错的测试摘要语言一样),我必须这样做;

1.编辑默认的py.test以包含option = –spec,这意味着使用插件:https : //github.com/pchomik/pytest-spec

2.使用py.test创建新的测试配置。更改其python解释器以使用〜/ anaconda / envs /您选择的解释器,例如py27作为我的命名。

3.删除“ unittests”测试配置。

4,现在默认的测试配置是py.test,带有我可爱的Rspec样式输出。我喜欢它!谢谢大家!

ps Jetbrains关于运行/调试配置的文档在这里:https ://www.jetbrains.com/help/pycharm/2016.1/run-debug-configuration-py-test.html?search = py.test

With a special Conda python setup which included the pip install for py.test plus usage of the Specs addin (option –spec) (for Rspec like nice test summary language), I had to do ;

1.Edit the default py.test to include option= –spec , which means use the plugin: https://github.com/pchomik/pytest-spec

2.Create new test configuration, using py.test. Change its python interpreter to use ~/anaconda/envs/ your choice of interpreters, eg py27 for my namings.

3.Delete the ‘unittests’ test configuration.

4.Now the default test config is py.test with my lovely Rspec style outputs. I love it! Thank you everyone!

p.s. Jetbrains’ doc on run/debug configs is here: https://www.jetbrains.com/help/pycharm/2016.1/run-debug-configuration-py-test.html?search=py.test


回答 9

在2018.3中,它似乎会自动检测到我正在使用pytest,这很好,但是仍然不允许从项目的顶层运行。我必须分别pytest为每个tests目录运行。

但是,我发现我可以选择一种配置,然后手动对其进行编辑以在项目的根目录下运行,并且可以正常工作。我必须在“配置”下拉列表中手动选择它-不能右键单击“项目”窗格中的根文件夹。但是至少它允许我同时运行所有测试。

With 2018.3 it appears to automatically detect that I’m using pytest, which is nice, but it still doesn’t allow running from the top level of the project. I had to run pytest for each tests directory individually.

However, I found that I could choose one of the configurations and manually edit it to run at the root of the project and that this worked. I have to manually choose it in the Configurations drop-down – can’t right click on the root folder in the Project pane. But at least it allows me to run all tests at once.


回答 10

为您的项目启用Pytest

  1. 打开设置/首选项| 工具| 如选择测试框架中所述的Python Integrated Tools设置对话框。
  2. 默认测试运行器字段中,选择pytest
  3. 单击确定以保存设置。

Enable Pytest for you project

  1. Open the Settings/Preferences | Tools | Python Integrated Tools settings dialog as described in Choosing Your Testing Framework.
  2. In the Default test runner field select pytest.
  3. Click OK to save the settings.


PyCharm错误:尝试导入自己的模块时(“ Python模块”)为“无模块”

问题:PyCharm错误:尝试导入自己的模块时(“ Python模块”)为“无模块”

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

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

from my_module import my_mod as mm

PyCharm甚至建议my_mod。到目前为止,一切都很好。

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

我觉得这很奇怪,因为

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

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

因此,为什么在尝试运行cool_script.py时出现错误?- 我想念什么?

笔记:

附录2015年2月25日

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

现在就可以了- 但是为什么呢?

出现了其他问题:

  • 什么是“内容根”和什么是“源根”?为什么在PYTHONPATH中添加一些内容却使其以某种方式中断?
  • 我是否应该一直取消选中这两个选项(在默认设置中也要取消选中这两个选项,而不是仅针对项目特定的配置(“运行/调试配置”对话框的左侧面板)?

I have written a module (a file my_mod.py file residing in the folder my_module). Currently, I am working in the file cool_script.py that 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).

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

from my_module import my_mod as mm

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

However, when I try to run cool_script.py, PyCharm tells me “No module named 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

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)

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

Notes:

Addendum 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.

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)?

回答 0

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

我希望这有帮助。

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 As and select Sources Root.

I hope this helps.


回答 1

所以如果你去

->设置->项目:My_project->项目结构,

仅提供源代码所在的目录,并将其标记为“源”(您可以在同一窗口中看到它)。带有源代码的目录应变为蓝色。现在,您可以导入位于同一目录中的模块。

So if you go to

-> Setting -> Project:My_project -> Project Structure,

Just the directory in which the source code is available and mark it as “Sources” (You can see it on the same window). The directory with source code should turn blue. Now u can import in modules residing in same directory.


回答 2

PyCharm社区/专业版2018.2.1

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

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

您还需要确保将__init__.py文件放置在资源目录中,或者实际上是要导入的任何位置,并且可以很好地工作。

我希望这个答案对某人有帮助,并希望JetBrains可以解决此烦人的错误。

PyCharm Community/Professional 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.

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 Source directory for all your Source files, or as a Resource folder for files that are strictly for importing.

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

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


回答 3

我尝试的是获取文件所在的位置。

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

我转到文件->设置->项目:My_project->项目结构,然后将内容根添加到要提到的地方 E:\git_projects\My_project

它为我工作。

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

e.g. 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

it worked for me.


回答 4

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

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

关于您的其他问题,我不知道我不使用PyCharm。

my_module is a folder not a module and you can’t import a folder, try moving my_mod.py to the same folder as the cool_script.py and 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.py unless it’s in the same directory

Or you can look here for 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.


回答 5

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

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

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/src and project/subproject2/thing/src and I had both of them marked as source root. When I renamed one of the "thing" folders to "thing1" (any unique name), it worked.

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


回答 6

当Python解释器找不到您的代码时,可能会导致这种情况。您必须向Python明确提及才能在此位置找到您的代码。

为此:

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

在您的情况下:

  • 转到您的python控制台,
  • 首先,编写以下代码:

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

    from mymodule import functions

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.

To do so:

  • Go to your python console
  • Add sys.path.extend(['your module location']) to Python console.

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
    

回答 7

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

对我而言,真正有效的方法是转到“运行/编辑配置…”,为您要在左侧运行的文件选择配置,取消选中“将源根添加到PYTHONPATH”框,保存,然后返回并选中该框并保存。然后它会工作。

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.

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.


回答 8

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

取消选中它们不会影响运行时,直到您没有在程序包中创建单独的模块(这些模块已手动连接到Django)为止。这意味着,如果您的任何文件不包含“ from django import …”或未通过django调用任何功能,则取消选中这两个选项将导致故障。

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

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.

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.


回答 9

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

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

  1. 运行输入脚本的目录或当前目录(如果解释器正在交互运行)
  2. PYTHONPATH环境变量(如果已设置)中包含的目录列表。
  3. 在安装Python时配置的与安装有关的目录列表,在我的情况下为Ubuntu上的usr / lib / python3.6。

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”:

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

  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.

回答 10

Pycharm 2017.1.1

  1. 点击View->ToolBarView->Tool Buttons
  2. 在左窗格Project上将可见,右键单击它,然后按Autoscroll to source ,然后运行您的代码。

这对我有用。

Pycharm 2017.1.1

  1. Click on View->ToolBar & View->Tool Buttons
  2. On the left pane Project would be visible, right click on it and press Autoscroll to source and then run your code.

This worked for me.


回答 11

ln -s someProject

如果您有someDirectory / someProjectDir和两个文件,则file1.py和file2.py,以及file1.py尝试使用此行导入

从someProjectDir导入file2

即使您已将someProjectDir指定为源目录,并且即使它在首选项中也将项目,项目结构菜单显示为内容根目录,它也无法使用。它将起作用的唯一方法是通过链接如上所示的项目(unix命令,在Mac中工作,不确定Windows的使用或语法)。由于软链接是由Pycharm在依赖项目中创建的,因此似乎存在某种机制,Pycharm可以在从版本控制签出或作为上下文根添加时自动执行此操作。因此,尽管复制了相同的内容,但奇怪的是目录的复制令人烦恼,而必要性却令人困惑。同样在自动创建的依赖项中,它在版本控制下也不显示为新目录。.idea文件的比较可能会发现更多。

ln -s . someProject

If you have someDirectory/someProjectDir and two files, file1.py and file2.py, and file1.py tries to import with this line

from someProjectDir import file2

It won’t work, even if you have designated the someProjectDir as a source directory, and even if it shows in preferences, project, project structure menu as a content root. The only way it will work is by linking the project as show above (unix command, works in mac, not sure of use or syntax for Windows). There seems some mechanism where Pycharm does this automatically either in checkout from version control or adding as context root, since the soft link was created by Pycharm in a dependent project. Hence, just copying the same, although the weird replication of directory is annoying and necessity is perplexing. Also in the dependency where auto created, it doesn’t show as new directory under version control. Perhaps comparison of .idea files will reveal more.


回答 12

对我有用的答案确实是OP在他的2015年更新中提到的内容:取消选中Python运行配置中的以下两个框

  • “将内容根添加到PYTHONPATH”
  • “将源根添加到PYTHONPATH”

我已经将run config设置为使用正确的venv,因此PyCharm不需要做其他工作即可向路径添加内容。相反,它导致了错误。

The answer that worked for me was indeed what OP mentions in his 2015 update: uncheck these two boxes in your Python run config:

  • “Add content roots to PYTHONPATH”
  • “Add source roots to PYTHONPATH”

I already had the run config set to use the proper venv, so PyCharm doing additional work to add things to the path was not necessary. Instead it was causing errors.


pycharm为什么建议将方法更改为静态

问题:pycharm为什么建议将方法更改为静态

新的pycharm版本(3.1.3社区版)建议将不适用于当前对象状态的方法转换为静态方法。

实际的原因是什么?某种微性能(或内存)优化?

The new pycharm release (3.1.3 community edition) proposes to convert the methods that don’t work with the current object’s state to static.

What is the practical reason for that? Some kind of micro-performance(-or-memory)-optimization?


回答 0

PyCharm认为您可能拥有一个静态方法,但是却忘记声明它是静态的(使用@staticmethod装饰器)。

PyCharm提出这一点是因为该方法未在其主体中使用 self,因此实际上并未更改类实例。因此,该方法可以是静态的,即可以在不传递类实例的情况下甚至在没有创建类实例的情况下调用。

PyCharm “thinks” that you might have wanted to have a static method, but you forgot to declare it to be static (using the @staticmethod decorator).

PyCharm proposes this because the method does not use self in its body and hence does not actually change the class instance. Hence the method could be static, i.e. callable without passing a class instance or without even having created a class instance.


回答 1

同意@ jolvi,@ ArundasR等,该警告会在不使用的成员函数上发生self

如果您确定PyCharm错误,则该函数不应为@staticmethod,并且如果您将警告设为零,则可以通过两种不同的方式使此警告消失:

解决方法#1

def bar(self):
    self.is_not_used()
    doing_something_without_self()

def is_not_used(self):
    pass

解决方法2 [感谢@DavidPärsson ]

# noinspection PyMethodMayBeStatic
def bar(self):
    doing_something_without_self()

为此,我拥有的应用程序(无法使用@staticmethod的原因)是制作用于响应协议子类型字段的处理程序功能表。当然,所有处理程序都必须具有相同的形式(静态或非静态)。但是有些实例并没有发生任何作用。如果我将其设为静态,则会得到“ TypeError:’staticmethod’对象不可调用”。

为了支持OP的复杂性,建议您在可能的情况下随时添加staticmethod ,这与后来使代码的限制性降低而不是使其变得更加限制性的原理背道而驰-使方法变为静态使其现在的约束性降低,因为您可以调用class.f()而不是instance.f()。

猜测为何存在此警告:

  • 发布staticmethod。它使开发人员意识到他们可能想要的东西。
  • 正如@JohnWorrall指出的那样,当self被无意中遗漏在函数之外时,它会引起您的注意。
  • 重新思考对象模型是一个提示。函数可能根本不属于此类。

Agreed with @jolvi, @ArundasR, and others, the warning happens on a member function that doesn’t use self.

If you’re sure PyCharm is wrong, that the function should not be a @staticmethod, and if you value zero warnings, you can make this one go away two different ways:

Workaround #1

def bar(self):
    self.is_not_used()
    doing_something_without_self()

def is_not_used(self):
    pass

Workaround #2 [Thanks @DavidPärsson]

# noinspection PyMethodMayBeStatic
def bar(self):
    doing_something_without_self()

The application I had for this (the reason I could not use @staticmethod) was in making a table of handler functions for responding to a protocol subtype field. All handlers had to be the same form of course (static or nonstatic). But some didn’t happen to do anything with the instance. If I made those static I’d get “TypeError: ‘staticmethod’ object is not callable”.

In support of the OP’s consternation, suggesting you add staticmethod whenever you can, goes against the principle that it’s easier to make code less restrictive later, than to make it more — making a method static makes it less restrictive now, in that you can call class.f() instead of instance.f().

Guesses as to why this warning exists:

  • It advertises staticmethod. It makes developers aware of something they may well have intended.
  • As @JohnWorrall’s points out, it gets your attention when self was inadvertently left out of the function.
  • It’s a cue to rethink the object model; maybe the function does not belong in this class at all.

回答 2

我认为此警告的原因是在Pycharm中进行配置。您可以在编辑器->检查中取消选中选择方法可能是静态的

I think that the reason for this warning is config in Pycharm. You can uncheck the selection Method may be static in Editor->Inspection


回答 3

我同意此处给出的答案(该方法未使用self,因此可以用修饰@staticmethod)。

我想补充一点,您可能想将方法移至顶级函数,而不是将类中的静态方法移至该函数。有关详细信息,请参见此问题和可接受的答案:python-我应该使用静态方法还是顶层函数

将方法移至顶层函数也将修复PyCharm警告。

I agree with the answers given here (method does not use self and therefore could be decorated with @staticmethod).

I’d like to add that you maybe want to move the method to a top-level function instead of a static method inside a class. For details see this question and the accepted answer: python – should I use static methods or top-level functions

Moving the method to a top-level function will fix the PyCharm warning, too.


回答 4

我可以想象将类方法定义为静态方法的以下优点:

  • 您可以只使用类名调用该方法,而无需实例化它。

如果存在的话,其余的优势可能是微不足道的:

  • 可能会跑得更快
  • 节省一点内存

I can imagine following advantages of having a class method defined as static one:

  • you can call the method just using class name, no need to instantiate it.

remaining advantages are probably marginal if present at all:

  • might run a bit faster
  • save a bit of memory

回答 5

由于您未selfbar方法主体中进行引用,因此PyCharm会询问您是否要使其bar静态。在其他编程语言(如Java)中,显然有理由声明静态方法。在Python中,静态方法(AFIK)的唯一真正好处是无需类的实例即可调用它。但是,如果这是您的唯一原因,那么最好使用顶级功能-如此处所述

简而言之,我不确定它为什么会在那里。我猜他们可能会在即将发布的版本中将其删除。

Since you didn’t refer to self in the bar method body, PyCharm is asking if you might have wanted to make bar static. In other programming languages, like Java, there are obvious reasons for declaring a static method. In Python, the only real benefit to a static method (AFIK) is being able to call it without an instance of the class. However, if that’s your only reason, you’re probably better off going with a top-level function – as note here.

In short, I’m not one hundred percent sure why it’s there. I’m guessing they’ll probably remove it in an upcoming release.


回答 6

此错误消息对我有很多帮助,因为我还没有意识到我不小心使用测试示例播放器来编写函数

my_player.attributes[item] 

而不是正确的方法

self.attributes[item]

This error message just helped me a bunch, as I hadn’t realized that I’d accidentally written my function using my testing example player

my_player.attributes[item] 

instead of the correct way

self.attributes[item]

回答 7

可能有点混乱,但是有时候您不需要访问self,但是您希望将方法保留在类中而不是使其静态。或者,您只想避免添加一堆难看的装饰器。以下是针对这种情况的一些可能的解决方法。

如果您的方法仅具有副作用,并且您不关心它返回的结果:

def bar(self):
    doing_something_without_self()
    return self

如果确实需要返回值:

def bar(self):
    result = doing_something_without_self()
    if self:
        return result

现在您的方法正在使用self,警告消失了!

It might be a bit messy, but sometimes you just don’t need to access self, but you would prefer to keep the method in the class and not make it static. Or you just want to avoid adding a bunch of unsightly decorators. Here are some potential workarounds for that situation.

If your method only has side effects and you don’t care about what it returns:

def bar(self):
    doing_something_without_self()
    return self

If you do need the return value:

def bar(self):
    result = doing_something_without_self()
    if self:
        return result

Now your method is using self, and the warning goes away!


回答 8

Pycharm之所以作为警告,是因为Python在调用none静态方法(不添加@staticmethod)时会将self作为第一个参数传递。皮查姆知道这一点。

例:

class T:
    def test():
        print "i am a normal method!"

t = T()
t.test()
output:
Traceback (most recent call last):
  File "F:/Workspace/test_script/test.py", line 28, in <module>
    T().test()
TypeError: test() takes no arguments (1 given)

我来自Java,在Java中,“ self”被称为“ this”,您无需在类方法中将self(或this)写为参数。您可以根据需要在方法内部调用self。但是Python“必须”将self作为方法参数传递。

通过了解这一点,您不需要任何变通方法作为@BobStein答案。

The reason why Pycharm make it as a warning because Python will pass self as the first argument when calling a none static method (not add @staticmethod). Pycharm knows it.

Example:

class T:
    def test():
        print "i am a normal method!"

t = T()
t.test()
output:
Traceback (most recent call last):
  File "F:/Workspace/test_script/test.py", line 28, in <module>
    T().test()
TypeError: test() takes no arguments (1 given)

I’m from Java, in Java “self” is called “this”, you don’t need write self(or this) as argument in class method. You can just call self as you need inside the method. But Python “has to” pass self as a method argument.

By understanding this you don’t need any Workaround as @BobStein answer.


在外部作用域中定义阴影名称有多糟糕?

问题:在外部作用域中定义阴影名称有多糟糕?

我刚刚切换到Pycharm,对所有警告和提示它为我提供了改进我的代码感到非常高兴。除了我不了解的那一项:

This inspection detects shadowing names defined in outer scopes.

我知道从外部作用域访问变量是一种不好的做法,但是隐藏外部作用域有什么问题呢?

这是一个示例,其中Pycharm给我警告消息:

data = [4, 5, 6]

def print_data(data): # <-- Warning: "Shadows 'data' from outer scope
    print data

print_data(data)

I just switched to Pycharm and I am very happy about all the warnings and hints it provides me to improve my code. Except for this one which I don’t understand:

This inspection detects shadowing names defined in outer scopes.

I know it is bad practice to access variable from the outer scope but what is the problem with shadowing the outer scope?

Here is one example, where Pycharm gives me the warning message:

data = [4, 5, 6]

def print_data(data): # <-- Warning: "Shadows 'data' from outer scope
    print data

print_data(data)

回答 0

在上面的代码片段中没什么大不了的,但是请想象一个具有更多参数和更多代码行的函数。然后,您决定将data参数重命名为,yadda但错过了函数主体中使用该参数的位置之一…现在data是指全局变量,您开始有怪异的行为- NameError如果不这样做,您将拥有更明显的表现有一个全球的名字data

还要记住,在Python中,所有东西都是对象(包括模块,类和函数),因此对于函数,模块或类没有明显的命名空间。另一种情况是将函数导入foo到模块顶部,然后在函数主体中的某个位置使用它。然后,在函数中添加一个新参数,并将其命名为-bad lucky- foo

最后,内置函数和类型也位于相同的命名空间中,并且可以以相同的方式进行阴影处理。

如果您的功能短,命名合理且单元测试范围广,那么这些都不是什么大问题,但是好吧,有时您必须维护的代码不够完美,并且被警告可能存在的问题。

No big deal in your above snippet, but imagine a function with a few more arguments and quite a few more lines of code. Then you decide to rename your data argument as yadda but miss one of the places it is used in the function’s body… Now data refers to the global, and you start having weird behaviour – where you would have a much more obvious NameError if you didn’t have a global name data.

Also remember that in Python everything is an object (including modules, classes and functions) so there’s no distinct namespaces for functions, modules or classes. Another scenario is that you import function foo at the top of your module, and use it somewhere in your function body. Then you add a new argument to your function and named it – bad luck – foo.

Finally, built-in functions and types also live in the same namespace and can be shadowed the same way.

None of this is much of a problem if you have short functions, good naming and a decent unittest coverage, but well, sometimes you have to maintain less than perfect code and being warned about such possible issues might help.


回答 1

当前最受投票和接受的答案以及此处的大多数答案都没有抓住重点。

函数有多长,或描述性地命名变量(希望将潜在的名称冲突机会降到最低)都没有关系。

函数的局部变量或其参数恰好在全局范围内共享名称这一事实是完全不相关的。实际上,无论您多么仔细地选择本地变量名称,您的函数都无法预见到“ yadda将来我的好名字是否也将用作全局变量?”。解决方案?根本不用担心!正确的心态是将函数设计为仅使用签名中参数的输入,而无需使用全局范围内的(或将要)什么,然后阴影根本就不是问题。

换句话说,仅当函数需要使用相同名称的局部变量和全局变量时,阴影问题才重要。但是您首先应该避免这种设计。OP的代码实际上并没有这样的设计问题。仅仅是PyCharm不够聪明,它会发出警告以防万一。因此,只是为了使PyCharm满意,并使我们的代码整洁,请参见silyevsk的回答中引用的此解决方案以完全删除全局变量。

def print_data(data):
    print data

def main():
    data = [4, 5, 6]
    print_data(data)

main()

这是解决问题的正确方法,方法是修复/删除全局对象,而不调整当前的局部函数。

The currently most up-voted and accepted answer and most answers here miss the point.

It doesn’t matter how long your function is, or how you name your variable descriptively (to hopefully minimize the chance of potential name collision).

The fact that your function’s local variable or its parameter happens to share a name in the global scope is completely irrelevant. And in fact, no matter how carefully you choose you local variable name, your function can never foresee “whether my cool name yadda will also be used as a global variable in future?”. The solution? Simply don’t worry about that! The correct mindset is to design your function to consume input from and only from its parameters in signature, that way you don’t need to care what is (or will be) in global scope, and then shadowing becomes not an issue at all.

In other words, shadowing problem only matters when your function need to use the same name local variable AND the global variable. But you should avoid such design in the first place. The OP’s code does NOT really have such design problem. It is just that PyCharm is not smart enough and it gives out a warning just in case. So, just to make PyCharm happy, and also make our code clean, see this solution quoting from silyevsk ‘s answer to remove the global variable completely.

def print_data(data):
    print data

def main():
    data = [4, 5, 6]
    print_data(data)

main()

This is the proper way to “solve” this problem, by fixing/removing your global thing, not adjusting your current local function.


回答 2

在某些情况下,一个好的解决方法是将vars +代码移至另一个函数:

def print_data(data):
    print data

def main():
    data = [4, 5, 6]
    print_data(data)

main()

A good workaround in some cases may be to move the vars + code to another function:

def print_data(data):
    print data

def main():
    data = [4, 5, 6]
    print_data(data)

main()

回答 3

这取决于功能的持续时间。功能越长,将来有人对其进行修改的机会就越多,data以为它意味着全局。实际上,这意味着本地,但是由于功能太长了,因此对于他们来说并不明显存在具有该名称的本地。

对于您的示例函数,我认为遮盖全局一点也不差。

It depends how long the function is. The longer the function, the more chance that someone modifying it in future will write data thinking that it means the global. In fact it means the local but because the function is so long it’s not obvious to them that there exists a local with that name.

For your example function, I think that shadowing the global is not bad at all.


回答 4

做这个:

data = [4, 5, 6]

def print_data():
    global data
    print(data)

print_data()

Do this:

data = [4, 5, 6]

def print_data():
    global data
    print(data)

print_data()

回答 5

data = [4, 5, 6] #your global variable

def print_data(data): # <-- Pass in a parameter called "data"
    print data  # <-- Note: You can access global variable inside your function, BUT for now, which is which? the parameter or the global variable? Confused, huh?

print_data(data)
data = [4, 5, 6] #your global variable

def print_data(data): # <-- Pass in a parameter called "data"
    print data  # <-- Note: You can access global variable inside your function, BUT for now, which is which? the parameter or the global variable? Confused, huh?

print_data(data)

回答 6

我喜欢在pycharm的右上角看到一个绿色的勾号。我为变量名加上下划线只是为了清除此警告,因此我可以将重点放在重要警告上。

data = [4, 5, 6]

def print_data(data_): 
    print(data_)

print_data(data)

I like to see a green tick in the top right corner in pycharm. I append the variable names with an underscore just to clear this warning so I can focus on the important warnings.

data = [4, 5, 6]

def print_data(data_): 
    print(data_)

print_data(data)

回答 7

看起来像是100%pytest代码模式

看到:

https://docs.pytest.org/en/latest/fixture.html#conftest-py-sharing-fixture-functions

我也有同样的问题,这就是为什么我找到这篇文章的原因;)

# ./tests/test_twitter1.py
import os
import pytest

from mylib import db
# ...

@pytest.fixture
def twitter():
    twitter_ = db.Twitter()
    twitter_._debug = True
    return twitter_

@pytest.mark.parametrize("query,expected", [
    ("BANCO PROVINCIAL", 8),
    ("name", 6),
    ("castlabs", 42),
])
def test_search(twitter: db.Twitter, query: str, expected: int):

    for query in queries:
        res = twitter.search(query)
        print(res)
        assert res

它会警告 This inspection detects shadowing names defined in outer scopes.

要解决此问题,只需将twitter灯具移入./tests/conftest.py

# ./tests/conftest.py
import pytest

from syntropy import db


@pytest.fixture
def twitter():
    twitter_ = db.Twitter()
    twitter_._debug = True
    return twitter_

然后移除twitter固定装置./tests/test_twitter2.py

# ./tests/test_twitter2.py
import os
import pytest

from mylib import db
# ...

@pytest.mark.parametrize("query,expected", [
    ("BANCO PROVINCIAL", 8),
    ("name", 6),
    ("castlabs", 42),
])
def test_search(twitter: db.Twitter, query: str, expected: int):

    for query in queries:
        res = twitter.search(query)
        print(res)
        assert res

这会让QA,Pycharm和所有人感到高兴

It looks like it 100% pytest code pattern

see:

https://docs.pytest.org/en/latest/fixture.html#conftest-py-sharing-fixture-functions

I had the same problem with, this is why I found this post ;)

# ./tests/test_twitter1.py
import os
import pytest

from mylib import db
# ...

@pytest.fixture
def twitter():
    twitter_ = db.Twitter()
    twitter_._debug = True
    return twitter_

@pytest.mark.parametrize("query,expected", [
    ("BANCO PROVINCIAL", 8),
    ("name", 6),
    ("castlabs", 42),
])
def test_search(twitter: db.Twitter, query: str, expected: int):

    for query in queries:
        res = twitter.search(query)
        print(res)
        assert res

And it will warn with This inspection detects shadowing names defined in outer scopes.

To fix that just move your twitter fixture into ./tests/conftest.py

# ./tests/conftest.py
import pytest

from syntropy import db


@pytest.fixture
def twitter():
    twitter_ = db.Twitter()
    twitter_._debug = True
    return twitter_

And remove twitter fixture like in ./tests/test_twitter2.py

# ./tests/test_twitter2.py
import os
import pytest

from mylib import db
# ...

@pytest.mark.parametrize("query,expected", [
    ("BANCO PROVINCIAL", 8),
    ("name", 6),
    ("castlabs", 42),
])
def test_search(twitter: db.Twitter, query: str, expected: int):

    for query in queries:
        res = twitter.search(query)
        print(res)
        assert res

This will be make happy QA, Pycharm and everyone


使用dict文字和dict构造函数之间有区别吗?

问题:使用dict文字和dict构造函数之间有区别吗?

我注意到使用PyCharm可以转换字典文字

d = {
    'one': '1',
    'two': '2',
}

dict构造函数中

d = dict(one='1', two='2')

这些不同的方法是否在某些重要方面有所不同?

(在写这个问题时,我注意到使用dict()数字键..似乎d = {1: 'one', 2: 'two'}是不可能的,但是,显然dict(1='one' ...)不可能。

Using PyCharm, I noticed it offers to convert a dict literal:

d = {
    'one': '1',
    'two': '2',
}

into a dict constructor:

d = dict(one='1', two='2')

Do these different approaches differ in some significant way?

(While writing this question I noticed that using dict() it seems impossible to specify a numeric key .. d = {1: 'one', 2: 'two'} is possible, but, obviously, dict(1='one' ...) is not. Anything else?)


回答 0

我认为您已经指出了最明显的区别。除此之外,

第一个不需要查找dict,这会使它更快一点

第二查找dictlocals(),然后globals()和出土文物内置的,所以你可以通过定义一个本地被叫交换机的行为dict,例如,虽然我想不出任何地方,这将是一个好主意,除了也许当调试

I think you have pointed out the most obvious difference. Apart from that,

the first doesn’t need to lookup dict which should make it a tiny bit faster

the second looks up dict in locals() and then globals() and the finds the builtin, so you can switch the behaviour by defining a local called dict for example although I can’t think of anywhere this would be a good idea apart from maybe when debugging


回答 1

文字速度要快得多,因为它使用优化的BUILD_MAP和STORE_MAP操作码,而不是通用的CALL_FUNCTION:

> python2.7 -m timeit "d = dict(a=1, b=2, c=3, d=4, e=5)"
1000000 loops, best of 3: 0.958 usec per loop

> python2.7 -m timeit "d = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}"
1000000 loops, best of 3: 0.479 usec per loop

> python3.2 -m timeit "d = dict(a=1, b=2, c=3, d=4, e=5)"
1000000 loops, best of 3: 0.975 usec per loop

> python3.2 -m timeit "d = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}"
1000000 loops, best of 3: 0.409 usec per loop

Literal is much faster, since it uses optimized BUILD_MAP and STORE_MAP opcodes rather than generic CALL_FUNCTION:

> python2.7 -m timeit "d = dict(a=1, b=2, c=3, d=4, e=5)"
1000000 loops, best of 3: 0.958 usec per loop

> python2.7 -m timeit "d = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}"
1000000 loops, best of 3: 0.479 usec per loop

> python3.2 -m timeit "d = dict(a=1, b=2, c=3, d=4, e=5)"
1000000 loops, best of 3: 0.975 usec per loop

> python3.2 -m timeit "d = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}"
1000000 loops, best of 3: 0.409 usec per loop

回答 2

它们在Python 3.2上看起来几乎一样。

正如gnibbler指出的那样,第一个不需要查找dict,这应该使它快一点。

>>> def literal():
...   d = {'one': 1, 'two': 2}
...
>>> def constructor():
...   d = dict(one='1', two='2')
...
>>> import dis
>>> dis.dis(literal)
  2           0 BUILD_MAP                2
              3 LOAD_CONST               1 (1)
              6 LOAD_CONST               2 ('one')
              9 STORE_MAP
             10 LOAD_CONST               3 (2)
             13 LOAD_CONST               4 ('two')
             16 STORE_MAP
             17 STORE_FAST               0 (d)
             20 LOAD_CONST               0 (None)
             23 RETURN_VALUE
>>> dis.dis(constructor)
  2           0 LOAD_GLOBAL              0 (dict)
              3 LOAD_CONST               1 ('one')
              6 LOAD_CONST               2 ('1')
              9 LOAD_CONST               3 ('two')
             12 LOAD_CONST               4 ('2')
             15 CALL_FUNCTION          512
             18 STORE_FAST               0 (d)
             21 LOAD_CONST               0 (None)
             24 RETURN_VALUE

They look pretty much the same on Python 3.2.

As gnibbler pointed out, the first doesn’t need to lookup dict, which should make it a tiny bit faster.

>>> def literal():
...   d = {'one': 1, 'two': 2}
...
>>> def constructor():
...   d = dict(one='1', two='2')
...
>>> import dis
>>> dis.dis(literal)
  2           0 BUILD_MAP                2
              3 LOAD_CONST               1 (1)
              6 LOAD_CONST               2 ('one')
              9 STORE_MAP
             10 LOAD_CONST               3 (2)
             13 LOAD_CONST               4 ('two')
             16 STORE_MAP
             17 STORE_FAST               0 (d)
             20 LOAD_CONST               0 (None)
             23 RETURN_VALUE
>>> dis.dis(constructor)
  2           0 LOAD_GLOBAL              0 (dict)
              3 LOAD_CONST               1 ('one')
              6 LOAD_CONST               2 ('1')
              9 LOAD_CONST               3 ('two')
             12 LOAD_CONST               4 ('2')
             15 CALL_FUNCTION          512
             18 STORE_FAST               0 (d)
             21 LOAD_CONST               0 (None)
             24 RETURN_VALUE

回答 3

除了您已经指出的,Python的词汇规则会干扰之外,这两种方法产生的字典相同。

字典文字显然是字典,您可以创建任何类型的键,但需要引用键名称。另一方面,由于某些原因,您可以将变量用于键:

a = "hello"
d = {
    a: 'hi'
    }

dict()构造给你因为各种输入的形式它需要更多的灵活性。例如,您可以为其提供一个成对的迭代器,并将其视为键/值对。

我不知道为什么PyCharm会提议将一种形式转换为另一种形式。

These two approaches produce identical dictionaries, except, as you’ve noted, where the lexical rules of Python interfere.

Dictionary literals are a little more obviously dictionaries, and you can create any kind of key, but you need to quote the key names. On the other hand, you can use variables for keys if you need to for some reason:

a = "hello"
d = {
    a: 'hi'
    }

The dict() constructor gives you more flexibility because of the variety of forms of input it takes. For example, you can provide it with an iterator of pairs, and it will treat them as key/value pairs.

I have no idea why PyCharm would offer to convert one form to the other.


回答 4

与python 3.4 + pycharm的一大不同是,如果键数超过256,则dict()构造函数会生成“语法错误”消息。

我现在更喜欢使用dict文字。

One big difference with python 3.4 + pycharm is that the dict() constructor produces a “syntax error” message if the number of keys exceeds 256.

I prefer using the dict literal now.


回答 5

从python 2.7教程开始:

一对大括号创建一个空字典:{}。将以逗号分隔的key:value对列表放在大括号内会为字典添加初始的key:value对;这也是将字典写在输出上的方式。

tel = {'jack': 4098, 'sape': 4139}
data = {k:v for k,v in zip(xrange(10), xrange(10,20))}

而:

dict()构造函数直接从存储为元组的键值对列表中构建字典。当这些对形成一个模式时,列表推导可以紧凑地指定键值列表。

tel = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127}
data = dict((k,v) for k,v in zip(xrange(10), xrange(10,20)))

当键是简单字符串时,有时使用关键字参数指定对更容易:

dict(sape=4139, guido=4127, jack=4098)
>>>  {'sape': 4139, 'jack':4098, 'guido': 4127}

因此{}和dict()都产生字典,但是提供了一些不同的字典数据初始化方式。

From python 2.7 tutorial:

A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

tel = {'jack': 4098, 'sape': 4139}
data = {k:v for k,v in zip(xrange(10), xrange(10,20))}

While:

The dict() constructor builds dictionaries directly from lists of key-value pairs stored as tuples. When the pairs form a pattern, list comprehensions can compactly specify the key-value list.

tel = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127}
data = dict((k,v) for k,v in zip(xrange(10), xrange(10,20)))

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

dict(sape=4139, guido=4127, jack=4098)
>>>  {'sape': 4139, 'jack':4098, 'guido': 4127}

So both {} and dict() produce dictionary but provide a bit different ways of dictionary data initialization.


回答 6

我发现dict文字d = {'one': '1'}更具可读性,可以定义数据,而不是分配事物值并将它们发送给dict()构造函数。

另一方面,我看到人们错误地输入了dict文字,d = {'one', '1'}因为在现代python 2.7+中它将创建一个set。

尽管如此,我仍然更喜欢始终使用set字面量,因为我认为它应该更具可读性和个人喜好。

I find the dict literal d = {'one': '1'} to be much more readable, your defining data, rather than assigning things values and sending them to the dict() constructor.

On the other hand i have seen people mistype the dict literal as d = {'one', '1'} which in modern python 2.7+ will create a set.

Despite this i still prefer to all-ways use the set literal because i think its more readable, personal preference i suppose.


回答 7

当您从其他对象(无python)复制粘贴值时,dict()文字很不错(例如,环境变量列表)。如果您有bash文件,请说

FOO='bar'
CABBAGE='good'

您可以轻松地将其粘贴到dict()文字中并添加注释。这也使相反的操作变得容易,将其复制到其他内容中。而{'FOO': 'bar'}语法是非常独特的Python和JSON。因此,如果您经常使用json,则可能需要使用{}带双引号的文字。

the dict() literal is nice when you are copy pasting values from something else (none python) For example a list of environment variables. if you had a bash file, say

FOO='bar'
CABBAGE='good'

you can easily paste then into a dict() literal and add comments. It also makes it easier to do the opposite, copy into something else. Whereas the {'FOO': 'bar'} syntax is pretty unique to python and json. So if you use json a lot, you might want to use {} literals with double quotes.


回答 8

没有dict文字可以创建dict继承的类,具有其他方法的自定义dict类。在这种情况下,应使用自定义dict类构造函数,例如:

class NestedDict(dict):

    # ... skipped

state_type_map = NestedDict(**{
    'owns': 'Another',
    'uses': 'Another',
})

There is no dict literal to create dict-inherited classes, custom dict classes with additional methods. In such case custom dict class constructor should be used, for example:

class NestedDict(dict):

    # ... skipped

state_type_map = NestedDict(**{
    'owns': 'Another',
    'uses': 'Another',
})

回答 9

还请考虑以下事实:与运算符匹配的标记不能在构造函数语法中使用,即,破折号。

>>> dict(foo-bar=1)
File "<stdin>", line 1
SyntaxError: keyword can't be an expression

>>> {'foo-bar': 1}
{'foo-bar': 1}

Also consider the fact that tokens that match for operators can’t be used in the constructor syntax, i.e. dasherized keys.

>>> dict(foo-bar=1)
File "<stdin>", line 1
SyntaxError: keyword can't be an expression

>>> {'foo-bar': 1}
{'foo-bar': 1}

如何在pycharm中导入模块?

问题:如何在pycharm中导入模块?

PyCharm中,我添加了Python环境/usr/bin/python。然而,

from gnuradio import gr

失败作为未定义的引用。但是,它在命令行的Python解释器中工作正常。

GNURadio可以在Pycharm外部使用python正常工作。一切都已安装并配置为我想要的方式。

格努拉迪奥位于 /usr/local/lib/python2.7/site-packages/gnuradio

也:

PYTHONPATH = / usr / local / lib / python2.7 / site-packages:/usr/local/lib/python2.7/site-packages/gnuradio

In PyCharm, I’ve added the Python environment /usr/bin/python. However,

from gnuradio import gr

fails as an undefined reference. However, it works fine in the Python interpreter from the command line.

GNURadio works fine with python outside of Pycharm. Everything is installed and configured how I want it.

Gnuradio is located at /usr/local/lib/python2.7/site-packages/gnuradio

Also:

PYTHONPATH=/usr/local/lib/python2.7/site-packages:/usr/local/lib/python2.7/site-packages/gnuradio


回答 0

添加路径

进入文件→设置→项目设置→项目解释器。

然后按配置解释器,并导航到“路径”选项卡。

在路径区域中按+按钮。您可以将路径放入想要识别的模块。

但我不知道路..

打开python解释器,您可以在其中导入模块。

>> import gnuradio
>> gnuradio.__file__
"path/to/gnuradio"

最常见的是,您将具有以下文件夹结构:

foobarbaz/
  gnuradio/
    __init__.py
    other_file.py

您要在此处将foobarbaz添加到路径。

Adding a Path

Go into File → Settings → Project Settings → Project Interpreter.

Then press configure interpreter, and navigate to the “Paths” tab.

Press the + button in the Paths area. You can put the path to the module you’d like it to recognize.

But I don’t know the path..

Open the python interpreter where you can import the module.

>> import gnuradio
>> gnuradio.__file__
"path/to/gnuradio"

Most commonly you’ll have a folder structure like this:

foobarbaz/
  gnuradio/
    __init__.py
    other_file.py

You want to add foobarbaz to the path here.


回答 1

您永远不需要通过环境变量或直接修改路径sys.path。无论您使用的是os(例如apt-get)还是pip在virtualenv中,软件包都将安装到该路径上已经存在的位置。

在您的示例中,GNU Radio已安装到系统Python 2的标准site-packages位置,该位置已在路径中。将PyCharm指向正确的解释器就足够了;如果不是,那是其他不明显的错误。可能/usr/bin/python与安装GNU Radio的解释器不同。尝试专门指向python2.7二进制文件。或者,PyCharm过去在检测包裹方面有些不好;File > Invalidate Caches > Invalidate and Restart会告诉它重新扫描。

该答案将涵盖如何设置项目环境,在不同情况下安装软件包以及配置PyCharm。我多次提到《Python打包用户指南》,该手册由维护官方Python打包工具的同一小组编写。


开发Python应用程序的正确方法是使用virtualenv。 安装软件包和版本不会影响系统或其他项目。 PyCharm具有内置的界面来创建virtualenv并安装软件包。 或者,您可以从命令行创建它,然后将PyCharm指向它。

$ cd MyProject
$ python2 -m virtualenv env
$ . env/bin/activate
$ pip install -U pip setuptools  # get the latest versions
$ pip install flask  # install other packages

在您的PyCharm项目中,转到File > Settings > Project > Project Interpreter。如果您使用virtualenvwrapper或PyCharm创建环境,那么它应该显示在菜单中。如果不是,请单击齿轮,选择Add Local,然后在环境中找到Python二进制文件。PyCharm将显示​​所选环境中的所有软件包。


在某些情况下,例如对于GNU Radio,没有要安装pip的软件包,当您安装GNU Radio的其余部分(例如apt-get install gnuradio)时,该软件包是在系统范围内安装的。在这种情况下,您仍然应该使用virtualenv,但是您需要使它知道此系统软件包。

$ python2 -m virtualenv --system-site-packages env

不幸的是,它看起来有些混乱,因为所有系统软件包现在都将出现在您的环境中,但是它们只是链接,您仍然可以安全地安装或升级软件包,而不会影响系统。


在某些情况下,您将要开发多个本地软件包,并且希望一个项目使用另一个软件包。在这种情况下,您可能会认为必须将本地包添加到另一个项目的路径中,但事实并非如此。您应该以开发模式安装软件包。所需要做的就是setup.py您的包中添加一个文件,无论如何以后要正确分发和部署该包都将需要文件

最小setup.py的第一个项目:

from setuptools import setup, find_packages

setup(
    name='mypackage',
    version='0.1',
    packages=find_packages(),
)

然后将其安装在第二个项目的环境中:

$ pip install -e /path/to/first/project

You should never need to modify the path directly, either through environment variables or sys.path. Whether you use the os (ex. apt-get), or pip in a virtualenv, packages will be installed to a location already on the path.

In your example, GNU Radio is installed to the system Python 2’s standard site-packages location, which is already in the path. Pointing PyCharm at the correct interpreter is enough; if it isn’t there is something else wrong that isn’t apparent. It may be that /usr/bin/python does not point to the same interpreter that GNU Radio was installed in; try pointing specifically at the python2.7 binary. Or, PyCharm used to be somewhat bad at detecting packages; File > Invalidate Caches > Invalidate and Restart would tell it to rescan.

This answer will cover how you should set up a project environment, install packages in different scenarios, and configure PyCharm. I refer multiple times to the Python Packaging User Guide, written by the same group that maintains the official Python packaging tools.


The correct way to develop a Python application is with a virtualenv. Packages and version are installed without effecting the system or other projects. PyCharm has a built-in interface to create a virtualenv and install packages. Or you can create it from the command line and then point PyCharm at it.

$ cd MyProject
$ python2 -m virtualenv env
$ . env/bin/activate
$ pip install -U pip setuptools  # get the latest versions
$ pip install flask  # install other packages

In your PyCharm project, go to File > Settings > Project > Project Interpreter. If you used virtualenvwrapper or PyCharm to create the env, then it should show up in the menu. If not, click the gear, choose Add Local, and locate the Python binary in the env. PyCharm will display all the packages in the selected env.


In some cases, such as with GNU Radio, there is no package to install with pip, the package was installed system-wide when you install the rest of GNU Radio (ex. apt-get install gnuradio). In this case, you should still use a virtualenv, but you’ll need to make it aware of this system package.

$ python2 -m virtualenv --system-site-packages env

Unfortunately it looks a little messy, because all system packages will now appear in your env, but they are just links, you can still safely install or upgrade packages without effecting the system.


In some cases, you will have multiple local packages you’re developing, and will want one project to use the other package. In this case you might think you have to add the local package to the other project’s path, but this is not the case. You should install your package in development mode. All this requires is adding a setup.py file to your package, which will be required anyway to properly distribute and deploy the package later.

Minimal setup.py for your first project:

from setuptools import setup, find_packages

setup(
    name='mypackage',
    version='0.1',
    packages=find_packages(),
)

Then install it in your second project’s env:

$ pip install -e /path/to/first/project

回答 2

对我而言,只需将目录标记为源根即可。

For me, it was just a matter of marking the directory as a source root.


回答 3

我的版本是PyCharm Professional版本3.4,并且“ 添加路径”部分有所不同。

您可以转到“首选项”->“项目解释器”。选择右上角的工具按钮。

然后选择“更多…”->“显示所选解释器的路径”->“添加”。然后,您可以添加路径。

My version is PyCharm Professional edition 3.4, and the Adding a Path part is different.

You can go to “Preferences” –> “Project Interpreter”. Choose the tool button at the right top corner.

Then choose “More…” –> “Show path for the selected interpreter” –> “Add”. Then you can add a path.


回答 4

在PyCharm 2017中添加路径

文件->设置(或Ctrl + Alt + S)->项目->项目解释器

显示所有

选择右侧的底部图标

单击加号按钮将新路径添加到您的模块

Add path in PyCharm 2017

File -> Settings (or Ctrl+Alt+S) -> Project -> Project Interpreter

Show all

Select bottom icon on the right side

Click on the plus button to add new path to your module


回答 5

不要更改解释器的路径。

改为更改项目结构:

文件->设置->项目->项目结构->添加内容根

DON’T change the interpreter path.

Change the project structure instead:

File -> Settings -> Project -> Project structure -> Add content root


回答 6

对于PyCharm Community Edition 2016.3.2,它是:

“项目解释器”->右上角的设置图标->“更多”。

然后在右侧应该有一个包装图标。将鼠标悬停在它上面时,应该说“显示所选解释程序的路径”。点击它。

然后单击“添加”按钮或按“ alt +插入”以添加新路径。

For PyCharm Community Edition 2016.3.2 it is:

“Project Interpreter” -> Top right settings icon -> “More”.

Then on the right side there should be a packages icon. When hovering over it it should say “Show paths for selected interpreter”. Click it.

Then click the “Add” button or press “alt+insert” to add a new path.


回答 7

在项目资源管理器上,您可以右键单击包含模块的文件夹并将其设置为“源”。

它将在索引中解析代码完成以及其他项目。

On Project Explorer, you can right click on the folder where the module is contained and set as ‘Source’.

It will be parsed in the Index for code completion as well as other items.


回答 8

作为快速的n修复,这对我有用:在有问题的导入之前添加以下两行:

import sys
sys.path.append('C:\\Python27\\Lib\site-packages')

As quick n dirty fix, this worked for me: Adding this 2 lines before the problematic import:

import sys
sys.path.append('C:\\Python27\\Lib\site-packages')

回答 9

我是PyCharm(使用2018.3.4 CE)和Python的新手,所以我僵硬地尝试遵循上述每个建议来访问我知道在系统站点软件包中的PIL(Pillow)软件包。没有工作。当我碰巧注意到“项目浏览器”窗口中项目下的venv / pyvenv.cfg文件时,我打算放弃过夜。我在该文件中找到了“ include-system-site-packages = false”行,因此将其更改为“ true”。问题解决了。

I’m new to PyCharm (using 2018.3.4 CE) and Python so I rotely tried to follow each of the above suggestions to access the PIL (Pillow) package which I knew was in system-site-packages. None worked. I was about to give up for the night when I happened to notice the venv/pyvenv.cfg file under my project in the Project Explorer window. I found the line “include-system-site-packages = false” in that file and so I changed it to “true”. Problem solved.


回答 10

在PyCharm 2020.1 CE和Professional中,您可以通过执行以下操作为项目的Python解释器添加路径:

1)单击项目右下角的解释器,然后选择“解释器设置”

2)点击口译员名称右侧的设置按钮,然后选择“显示全部”:

3)确保选择了项目的解释器,然后单击底部工具栏中的第五个按钮,“显示选定解释器的路径”:

4)单击底部工具栏中的“ +”按钮,然后将路径添加到包含您的模块的文件夹中:

In PyCharm 2020.1 CE and Professional, you can add a path to your project’s Python interpreter by doing the following:

1) Click the interpreter in the bottom right corner of the project and select ‘Interpreter Settings’

2) Click the settings button to the right of the interpreter name and select ‘Show All’:

3) Make sure your project’s interpreter is selected and click the fifth button in the bottom toolbar, ‘show paths for the selected interpreter’:

4) Click the ‘+’ button in the bottom toolbar and add a path to the folder containing your module:


回答 11

下载anaconda https://anaconda.org/

完成安装Python…

进入设置->项目设置->项目解释器。

然后导航到“路径”标签并搜索/ anaconda / bin / python

点击申请

Download anaconda https://anaconda.org/

once done installing anaconda…

Go into Settings -> Project Settings -> Project Interpreter.

Then navigate to the “Paths” tab and search for /anaconda/bin/python

click apply


Pycharm的检查员为何抱怨“ d = {}”?

问题:Pycharm的检查员为何抱怨“ d = {}”?

d = {}Pycharm的代码检查器初始化字典时,会产生警告,说

这个字典的创建可以重写为字典文字。

如果我重写它d = dict(),警告就会消失。由于{}已经字典文字,因此我很确定该消息是错误的。此外,似乎都d = {}d = dict()有效,Python化。

这个相关的问题似乎可以得出结论,选择只取决于样式/偏好: “ d = dict()”和“ d = {}”之间的差异

皮查姆为什么会抱怨d = {}

更新:

Mac钉了它。该警告实际上适用于多行,而不仅仅是标记的行。

Pycharm似乎在寻找一系列连续语句,在这些语句中您初始化字典,然后在字典中设置值。例如,这将触发警告:

d = {}
d['a'] = 1

但是此代码不会:

d = {}
pass
d['a'] = 1

When initializing a dictionary with d = {} Pycharm’s code inspector generates a warning, saying

This dictionary creation could be rewritten as a dictionary literal.

If I rewrite it d = dict() the warning goes away. Since {} already is a dictionary literal, I’m pretty sure the message is erroneous. Furthermore, it seems like both d = {} and d = dict() are valid and Pythonic.

This related question seems to conclude that the choice is just a matter of style/preference: differences between “d = dict()” and “d = {}”

Why would Pycharm complain about d = {}?

UPDATE:

Mac nailed it. The warning actually applied to multiple lines, not just the one that was flagged.

Pycharm seems to look for a sequence of consecutive statements where you initialize a dictionary and then set values in the dictionary. For example, this will trigger the warning:

d = {}
d['a'] = 1

But this code will not:

d = {}
pass
d['a'] = 1

回答 0

字典声明中的以下代码是什么?

我认为pycharm将在出现以下情况时触发错误:

dic = {}
dic['aaa'] = 5

如你所写

dic = {'aaa': 5}

顺便说一句:如果您使用该函数,错误就会消失,但这并不一定意味着pycharm认为这dict()是文字。这可能只是意味着它不会抱怨:

dic = dict()
dic['aaa'] = 5

HTH!

What is the following code to your dictionary declaration?

I think pycharm will trigger the error if you have something like:

dic = {}
dic['aaa'] = 5

as you could have written

dic = {'aaa': 5}

BTW: The fact that the error goes away if you use the function doesn’t necessarily mean that pycharm believes dict() is a literal. It could just mean that it doesn’t complain for:

dic = dict()
dic['aaa'] = 5

HTH!


回答 1

可以在项目设置或默认设置中禁用它。

  • 导航到设置->检查-> Python
  • 取消选中“字典创建可以用字典文字重写”

This can be disabled in the Project Settings or Default Settings.

  • Navigate to Settings -> Inspections -> Python
  • Uncheck “Dictionary creation could be rewritten by dictionary literal”

回答 2

对于那些喜欢(就像我一样)通过单个操作初始化字典的人

d = {
  'a': 12,
  'b': 'foo',
  'c': 'bar'
}

而不是像

d = dict()
d['a'] = 12
d['b'] = ....

最后,我得出以下结论:

d = dict()
d.update({
  'a': 12,
  'b': 'foo',
  'c': 'bar'
})

Pycharm没有对此抱怨

for those who like (just like me) to initialize dictionaries with single operation

d = {
  'a': 12,
  'b': 'foo',
  'c': 'bar'
}

instead of many lines like

d = dict()
d['a'] = 12
d['b'] = ....

in the end I ended up with this:

d = dict()
d.update({
  'a': 12,
  'b': 'foo',
  'c': 'bar'
})

Pycharm is not complaining on this


回答 3

mydict = {
  a: 5,
  b:z+c/2
}

可以直接创建字典而无需先初始化字典,然后重新分配新值。

mydict = {
  a: 5,
  b:z+c/2
}

The dictionary could have been created directly without initialising them first and then reassigning new values.


回答 4

我遇到这样的情况,该警告使我烦恼不已。就我而言,我将字典部分填充为文字,并部分地从函数的元组输出中填充,如下所示:

def get_other_values():
    return 3, 4

foo = {
    "a": 1,
    "b": 2
}
foo["c"], foo["d"] = get_other_values()

因此,除非我为get_other_values的输出创建临时var,否则即使我使用文字创建dict,PEP8也会生成此警告。而且我无法在文字中分配c和d键,因为这些值以元组形式输出。

I have a situation where this warning is bugging the hell out of me. In my case, I’m populating my dict partially as literals and partially from a tuple output by a function, like so:

def get_other_values():
    return 3, 4

foo = {
    "a": 1,
    "b": 2
}
foo["c"], foo["d"] = get_other_values()

So, unless I create interim vars for the output of get_other_values, PEP8 generates this warning even though I’m creating the dict with literals. And I can’t assign the c and d keys in the literal, since the values are output as a tuple.


简化链式比较

问题:简化链式比较

我有一个整数值x,我需要检查它是否在startend值之间,因此我编写了以下语句:

if x >= start and x <= end:
    # do stuff

该声明带有下划线,并且工具提示告诉我必须

简化链式比较

据我所知,这种比较就和它们来的一样简单。我在这里错过了什么?

I have an integer value x, and I need to check if it is between a start and end values, so I write the following statements:

if x >= start and x <= end:
    # do stuff

This statement gets underlined, and the tooltip tells me that I must

simplify chained comparison

As far as I can tell, that comparison is about as simple as they come. What have I missed here?


回答 0

在Python中,您可以“链接”比较操作,这仅意味着它们“并”在一起。在您的情况下,将是这样的:

if start <= x <= end:

参考:https : //docs.python.org/3/reference/expressions.html#comparisons

In Python you can “chain” comparison operations which just means they are “and”ed together. In your case, it’d be like this:

if start <= x <= end:

Reference: https://docs.python.org/3/reference/expressions.html#comparisons


回答 1

可以重写为:

start <= x <= end:

要么:

r = range(start, end + 1) # (!) if integers
if x in r:
    ....

It can be rewritten as:

start <= x <= end:

Or:

r = range(start, end + 1) # (!) if integers
if x in r:
    ....

回答 2

简化代码

if start <= x <= end: # start x is between start and end 
# do stuff

Simplification of the code

if start <= x <= end: # start x is between start and end 
# do stuff

PyCharm显示有效代码的未解析引用错误

问题:PyCharm显示有效代码的未解析引用错误

我正在使用PyCharm进行项目。该项目将打开并使用解释器进行配置,并且可以成功运行。远程解释器路径已正确映射。这似乎是正确的配置,但是PyCharm突出显示了我的有效代码,并带有“未解决的引用”错误,即使对于内置Python函数也是如此。为什么即使代码运行也似乎没有检测到这些?有没有办法让PyCharm正确识别这些?


该问题的特定实例与远程解释器有关,但该问题也出现在本地解释器上。

I am using PyCharm to work on a project. The project is opened and configured with an interpreter, and can run successfully. The remote interpreter paths are mapped properly. This seems to be the correct configuration, but PyCharm is highlighting my valid code with “unresolved reference” errors, even for built-in Python functions. Why don’t these seem to be detected, even though the code runs? Is there any way to get PyCharm to recognize these correctly?


This specific instance of the problem is with a remote interpreter, but the problem appears on local interpreters as well.


回答 0

档案| 无效的缓存…并重新启动PyCharm会有所帮助。

File | Invalidate Caches… and restarting PyCharm helps.


回答 1

德米特里的回应对我没有用。

我可以通过以下方法来工作:转到项目解释器,选择“路径”选项卡,然后单击该子菜单中的刷新按钮。它会自动填充“ python-skeletons”。

编辑:使用PyCharm 3.4.1的屏幕截图(隐藏得很好)

Dmitry’s response didn’t work for me.

I got mine working by going to Project Interpreters, Selecting the “Paths” tab, and hitting the refresh button in that submenu. It auto-populated with something called “python-skeletons”.

edit: screenshot using PyCharm 3.4.1 (it’s quite well hidden)


回答 2

有许多解决方案,其中一些比其他解决方案更方便,而且它们并不总是有效。

这是您可以尝试的所有方法,从“快速”变为“烦人”:

  • 执行File-> Invalidate Caches / Restart然后重新启动PyCharm。
    • 可以肯定的是,您也可以使用以下任何一种方法进行此操作。
  • 首先,检查您正在运行的解释器:Run-> Edit Configurations-> Configuration-> Python Interpreter
  • 刷新解释器的路径:
    • File -> Settings
    • Project: [name]-> Project Interpreter->“项目解释器”:齿轮图标->More...
    • 点击“显示路径”按钮(下一个)
    • 点击“刷新”按钮(下一个)
  • 删除解释器并再次添加:
    • File -> Settings
    • Project: [name]-> Project Interpreter->“项目解释器”:齿轮图标->More...
    • 点击“删除”按钮
    • 点击“添加”按钮,然后重新添加您的信息
  • 删除项目首选项
    • 删除项目的.idea文件夹
    • 关闭并重新打开PyCharm
    • 从头开始打开项目
  • 删除您的PyCharm用户首选项(但先备份它们)。
    • ~/.PyCharm50 在Mac上
    • %homepath%/.PyCharm50 在Windows上
  • 切换到另一个解释器,然后再次返回到您想要的解释器。
  • 创建一个新的虚拟环境,然后切换到该环境的解释器。
  • 完全切换到另一个口译员,不要切换回去。

There are many solutions to this, some more convenient than others, and they don’t always work.

Here’s all you can try, going from ‘quick’ to ‘annoying’:

  • Do File -> Invalidate Caches / Restart and restart PyCharm.
    • You could also do this after any of the below methods, just to be sure.
  • First, check which interpreter you’re running: Run -> Edit Configurations -> Configuration -> Python Interpreter.
  • Refresh the paths of your interpreter:
    • File -> Settings
    • Project: [name] -> Project Interpreter -> ‘Project Interpreter’: Gear icon -> More...
    • Click the ‘Show paths’ button (bottom one)
    • Click the ‘Refresh’ button (bottom one)
  • Remove the interpreter and add it again:
    • File -> Settings
    • Project: [name] -> Project Interpreter -> ‘Project Interpreter’: Gear icon -> More...
    • Click the ‘Remove’ button
    • Click the ‘Add’ button and re-add your interpeter
  • Delete your project preferences
    • Delete your project’s .idea folder
    • Close and re-open PyCharm
    • Open your project from scratch
  • Delete your PyCharm user preferences (but back them up first).
    • ~/.PyCharm50 on Mac
    • %homepath%/.PyCharm50 on Windows
  • Switch to another interpreter, then back again to the one you want.
  • Create a new virtual environment, and switch to that environments’ interpreter.
  • Switch to another interpreter altogether, don’t switch back.

回答 3

就我而言,这是目录结构。我的项目如下所示:

+---dir_A
    +---dir_B
        +app
        |
        \-run.py

因此,右键单击dir_b>“将目录标记为”>“项目根目录”

In my case it was the directories structure. My project looks like this:

+---dir_A
    +---dir_B
        +app
        |
        \-run.py

So right click on dir_b > “mark directory as” > “project root”


回答 4

当无效缓存或刷新路径不起作用时,我发现自己删除并重新添加了远程解释器以解决此问题。

如果将新虚拟机添加到多虚拟机设置中,我会不时地使用vagrant,并且转发的端口会发生更改,这在PyCharm尝试为SSH使用错误的端口时会感到困惑。更改端口似乎无济于事。

I find myself removing and re-adding the remote interpreter to fix this problem when Invalidating Caches or Refreshing Paths does not work.

I use vagrant and every once and awhile if I add a new VM to my multi-vm setup, the forwarded port changes and this seems to confuse PyCharm when it tries to use the wrong port for SSH. Changing the port doesn’t seem to help the broken references.


回答 5

如果没有其他解决方案适合您,请尝试(备份)并删除〜/ .PyCharm40文件夹,然后重新打开PyCharm。这也会杀死您的所有偏好。

在Mac上,您要删除〜/ Library / Caches / Pycharm40和〜/ Library / Preferences / PyCharm40。

在Windows上:C:\ Users \ $ USER.PyCharm40。

If none of the other solutions work for you, try (backing up) and deleting your ~/.PyCharm40 folder, then reopening PyCharm. This will kill all your preferences as well.

On Mac you want to delete ~/Library/Caches/Pycharm40 and ~/Library/Preferences/PyCharm40.

And on Windows: C:\Users\$USER.PyCharm40.


回答 6

按照以下步骤在PyCharm 4.0.6(OSX 10.10.3)中进行了测试:

  1. 点击PyCharm菜单。
  2. 选择项目解释器。
  3. 选择齿轮图标。
  4. 选择更多按钮。
  5. 选择您所在的项目口译员。
  6. 选择目录树按钮。
  7. 选择重新加载路径列表。

问题解决了!

Tested with PyCharm 4.0.6 (OSX 10.10.3) following this steps:

  1. Click PyCharm menu.
  2. Select Project Interpreter.
  3. Select Gear icon.
  4. Select More button.
  5. Select Project Interpreter you are in.
  6. Select Directory Tree button.
  7. Select Reload list of paths.

Problem solved!


回答 7

好简单

您只需将根目录标记为:SOURCE ROOT(红色),并将您的应用程序标记为EXCLUDED ROOT(蓝色),

那么未解决的参考将消失。

  • 如果您使用PyChram pro,它将自动为您执行此操作。

very easy

you just have to mark your root directory as: SOURCE ROOT (red), and your applications: EXCLUDED ROOT (blue),

then the unresolved reference will disappear.

  • if you use PyChram pro it do this for you automaticlly.

回答 8

很抱歉碰到这个问题,但是我有一个重要的更新。

如果您使用的是其他版本,则可能还需要将项目解释器恢复为Python 2.7.6。在没有其他建议解决了我的问题之后,这对我的Ubuntu安装PyCharm 4.04 Professional很有用。

Sorry to bump this question, however I have an important update to make.

You may also want to revert your project interpreter to to Python 2.7.6 if you’re using any other version than that This worked for me on my Ubuntu installation of PyCharm 4.04 professional after none of the other recommendations solved my problem.


回答 9

您可以尝试关闭Pycharm,.idea从项目中删除文件夹,然后再次启动Pycharm并重新创建项目。这对我有用,而使缓存无效却没有。

You might try closing Pycharm, deleting the .idea folder from your project, then starting Pycharm again and recreating the project. This worked for me whereas invalidating cache did not.


回答 10

在没有任何建议的解决方案对我起作用之后,我终于使这项工作奏效了。我正在玩django rest框架项目,并且正在使用我已为其设置的virtualenv。我可以通过将根文件夹标记为源根来修复Pycharm,但是django的服务器会抛出解决异常。因此,一个将在另一个不起作用时起作用,反之亦然。

最终,我只需要将子文件夹标记为pycharm中的源即可。所以我的结构是这样的

-playground
     -env
     -playground

第二个Playground文件夹是我必须将其标记为源根目录的文件夹,以便一切正常工作。对于我的情况,这没有任何问题,因此这是一个可行的解决方案。

只是以为我愿意与他人分享,以防其他人可以使用它。

I finally got this working after none of the proposed solutions worked for me. I was playing with a django rest framework project and was using a virtualenv I had setup with it. I was able to get Pycharm fixed by marking the root folder as the sources root, but then django’s server would throw resolve exceptions. So one would work when the other wouldn’t and vice versa.

Ultimately I just had to mark the subfolder as the sources root in pycharm. So my structure was like this

-playground
     -env
     -playground

That second playground folder is the one I had to mark as the sources root for everything to work as expected. That didn’t present any issues for my scenario so it was a workable solution.

Just thought I’d share in case someone else can use it.


回答 11

这也可能是python版本问题。我必须选择合适的设备才能使其正常工作。

It could also be a python version issue. I had to pick the right one to make it work.


回答 12

如果您只想忽略一些“未解决的引用”错误,也可以通过将其放在类/方法/函数的前面来明确地告诉它PyCharm:

# noinspection PyUnresolvedReferences

If you want to ignore only some “unresolved reference” errors, you can also tell it PyCharm explicitly by placing this in front of your class/method/function:

# noinspection PyUnresolvedReferences

回答 13

我关闭了所有其他项目,并在Pycharm中独立运行所需的项目。我从pycharm创建了一个单独的virtualenv,并使用pip在其中添加了所有必需的模块。我在项目的解释器中添加了此虚拟环境。这解决了我的问题。

I closed all the other projects and run my required project in isolation in Pycharm. I created a separate virtualenv from pycharm and added all the required modules in it by using pip. I added this virtual environment in project’s interpreter. This solved my problem.


回答 14

Geeze真是一场噩梦,我将不同的StackOVerflow合并在一起回答:

  1. 切换到本地解释器/usr/bin/pythonX.X并应用
  2. 查看以上答案的路径
  3. 查找骨骼路径。我的是(/home/tim/Desktop/pycharm-community-2016.2.3/helpers/python-skeletons)
  4. 切换回virt解释器并手动添加骨骼路径(如果该路径未自动显示)。

Geeze what a nightmare, my amalgamation of different StackOVerflow answers:

  1. Switch to local interpreter /usr/bin/pythonX.X and apply
  2. View paths like above answer
  3. Find skeletons path. Mine was (/home/tim/Desktop/pycharm-community-2016.2.3/helpers/python-skeletons)
  4. Switch back to virt interpreter and add the skeletons path manually if it didn’t automatically show up.

回答 15

以上解决方案都不适合我!
如果您在项目中使用虚拟环境,请确保将python.exe虚拟环境目录中的文件用作项目的解释器,(Alt + Ctrl + Shift + S) 这为我解决了这个问题。

None of the above solutions worked for me!
If you are using virtual environment for your project make sure to apply the python.exe file that is inside your virtual environment directory as interpreter for the project (Alt + Ctrl + Shift + S) this solved the issue for me.


回答 16

在我的情况下,由于python代码非常特殊的情况而出现了检查错误。一个包含两个numpy函数和两个列表访问权的min函数使我的代码检查出现这种错误。

在下面的示例中,删除’d = 0’行会产生未解决的参考错误,但是,读操作并不能使代码检查程序消除该错误。之后,我仍然可以执行代码而不会出现问题。

import numpy as np
def strange(S, T, U, V):
    d = 0
    print min(np.abs(S[d]), np.abs(T[d]), U[d], V[d])

清除缓存和重新加载路径列表不起作用。仅使用以下示例补丁之一更改代码才有效:

  • “ min”参数的另一排序:示意性显示SUTV,但不显示STUV或TSUV
  • 使用方法代替函数:S [d] .abs()代替np.abs(S [d])
  • 使用内置的abs()函数
  • 在选择的参数上加上数字:U [d] + 0。

In my case the inspection error shows up due to a very specific case of python code. A min function that contains two numpy functions and two list accesses makes my code inspection give this kind of errors.

Removing the ‘d=0’ line in the following example gives an unresolved reference error as expected, but readding doesn’t make the error go away for the code inspector. I can still execute the code without problems afterwards.

import numpy as np
def strange(S, T, U, V):
    d = 0
    print min(np.abs(S[d]), np.abs(T[d]), U[d], V[d])

Clearing caches and reloading list of paths doesn’t work. Only altering the code with one of the following example patches does work:

  • Another ordering of the ‘min’ parameters: schematically S U T V but not S T U V or T S U V
  • Using a method instead of the function: S[d].abs() instead of np.abs(S[d])
  • Using the built-in abs() function
  • Adding a number to a parameter of choice: U[d] + 0.

回答 17

没有答案能解决我的问题。

对我来说,这是切换环境并回到相同的环境。 File->Settings->Project interpreter

我正在使用conda环境。

None of the answers solved my problem.

What did it for me was switching environments and going back to the same environment. File->Settings->Project interpreter

I am using conda environments.


回答 18

为我工作了很多简单的动作


File > Settings > Project > Project Interpreter 
> Select "No interpreter" in the "Project interpreter" list 
> Apply > Set your python interpreter again > Click Apply

利润-Pycharm正在更新骨骼,一切都很好。

Worked for me with much simplier action:


File > Settings > Project > Project Interpreter 
> Select "No interpreter" in the "Project interpreter" list 
> Apply > Set your python interpreter again > Click Apply

Profit – Pycharm is updating skeletons and everything is fine.


回答 19

如果使用vagrant错误,则可能是错误的python解释器引起的。在我们vagrant使用的过程中pyenv,我不得不将Python Interpreter path路径从更改/usr/bin/python/home/vagrant/.pyenv/versions/vagrant/bin/python

If you are using vagrant the error can be caused by wrong python interpreter. In our vagrant we are using pyenv so I had to change Python Interpreter path path from /usr/bin/python to /home/vagrant/.pyenv/versions/vagrant/bin/python


回答 20

我有一个项目,其中一个文件src/导入同一目录中的另一个文件。为了让PyCharm能够识别我必须去File> Settings> Project> Project Structure> selectsrc文件夹,然后单击“标记为:源”

来自https://www.jetbrains.com/help/pycharm/configuring-folders-within-a-content-root.html

源根目录包含实际的源文件和资源。PyCharm使用源根作为解决导入的起点

I have a project where one file in src/ imports another file in the same directory. To get PyCharm to recognize I had to to go to File > Settings > Project > Project Structure > select src folder and click “Mark as: Sources”

From https://www.jetbrains.com/help/pycharm/configuring-folders-within-a-content-root.html

Source roots contain the actual source files and resources. PyCharm uses the source roots as the starting point for resolving imports


回答 21

我的问题是Flask-WTF无法由PyCharm解决。我试图重新安装,然后安装或使缓存无效并重新启动 PyCharm,但仍然无法正常工作。

然后我想出了这个解决方案,它对我来说非常合适。

  1. 通过Ctrl + Alt + S(Windows)打开项目解释器,然后单击“ 安装”(+)新包装。

  1. 键入PyCharm无法解析的软件包,然后单击“ 安装软件包”。然后单击“ 确定”

现在,您将看到库已解决。

My problem is that Flask-WTF is not resolved by PyCharm. I have tried to re-install and then install or Invalidate Cache and Restart PyCharm, but it’s still not working.

Then I came up with this solution and it works perfectly for me.

  1. Open Project Interpreter by Ctrl+Alt+S (Windows) and then click Install (+) a new packgage.

  1. Type the package which is not resolved by PyCharm and then click Install Package. Then click OK.

Now, you’ll see your library has been resolved.


回答 22

您在使用virtualenv吗?

如果是这样,则您需要在所需python.exe的位置上发生的每次更改都通知PyCharm(仅./activate不足以实现PyCharm)

确保Pycharm指向正确的干预者和程序包:文件->设置->项目->项目解释器。单击齿轮,然后在virtualenv的Scripts文件夹下选择python.exe

Are you using virtualenv?

if so, you need to notify PyCharm for every change in the location of the the desired python.exe (merely ./activate is not enough for PyCharm)

Make sure Pycharm points to the correct interpetor and packages: File -> Settings -> Project -> Project Interpreter. Click the gear and choose python.exe under virtualenv’s Scripts folder


如何在PyCharm中设置最大行长?

问题:如何在PyCharm中设置最大行长?

我在Windows上使用PyCharm,并且想要更改设置以将最大行长限制为79字符,而不是默认的120字符限制。

我在哪里可以更改PyCharm中每行的最大字符数?

I am using PyCharm on Windows and want to change the settings to limit the maximum line length to 79 characters, as opposed to the default limit of 120 characters.

Where can I change the maximum amount of characters per line in PyCharm?


回答 0

这是我的Pycharm的屏幕截图。所需设置在以下路径中:File -> Settings -> Editor -> Code Style -> General: Right margin (columns)

Here is screenshot of my Pycharm. Required settings is in following path: File -> Settings -> Editor -> Code Style -> General: Right margin (columns)


回答 1

对于Mac上的PyCharm 2018.1:

首选项(+ ,),然后Editor -> Code Style

对于Windows上的PyCharm 2018.3:

文件->设置(Ctrl+ Alt+ S),然后Editor -> Code Style

要遵循PEP-8,请将其设置Hard wrap at为80。

For PyCharm 2018.1 on Mac:

Preferences (+,), then Editor -> Code Style:

For PyCharm 2018.3 on Windows:

File -> Settings (Ctrl+Alt+S), then Editor -> Code Style:

To follow PEP-8 set Hard wrap at to 80.


回答 2

对于PyCharm 4

文件>>设置>>编辑器>>代码样式:右边距(列)

建议:查看该标签中的其他选项,它们非常有帮助

For PyCharm 4

File >> Settings >> Editor >> Code Style: Right margin (columns)

suggestion: Take a look at other options in that tab, they’re very helpful


回答 3

您甚至可以为HTML 设置单独的右边距。在指定路径下:

文件>>设置>>编辑器>>代码样式>> HTML >>其他选项卡>>右页边距(列)

这非常有用,因为通常HTML和JS的一行通常比Python长。:)

You can even set a separate right margin for HTML. Under the specified path:

File >> Settings >> Editor >> Code Style >> HTML >> Other Tab >> Right margin (columns)

This is very useful because generally HTML and JS may be usually long in one line than Python. :)


回答 4

对于任何人,或者对于我自己,如果我重新加载计算机,在进行代码重新格式化时这对谁都不起作用,那么还有一个附加选项可在editor-> code style-> python下检查:确保未超出正确的边距。选择此选项后,格式将生效。

For anyone, or myself if I reload my machine, who this is not working for when you do a code reformat there is an additional option to check under editor->code style->python : ensure right margin is not exceeded. Once this was selected the reformat would work.


回答 5

对于PyCharm 2017

我们可以按照以下步骤进行操作:文件>>设置>>编辑器>>代码样式。

然后在键入时为Hard Wrap&提供值Visual Guides for wrapping,勾选复选框。

注意:也请查看其他标签。Python,HTML,JSON等

For PyCharm 2017

We can follow below: File >> Settings >> Editor >> Code Style.

Then provide values for Hard Wrap & Visual Guides for wrapping while typing, tick the checkbox.

NB: look at other tabs as well, viz. Python, HTML, JSON etc.