标签归档:pycharm

我怎样才能告诉PyCharm参数期望是什么类型?

问题:我怎样才能告诉PyCharm参数期望是什么类型?

当涉及到构造函数,赋值和方法调用时,PyCharm IDE非常擅长分析我的源代码并弄清楚每个变量应该是什么类型。我很喜欢它,因为它给了我很好的代码完成和参数信息,并且如果我尝试访问一个不存在的属性,它会给我警告。

但是当涉及到参数时,它一无所知。代码完成下拉列表无法显示任何内容,因为它们不知道参数的类型。代码分析无法查找警告。

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

peasant = Person("Dennis", 37)
# PyCharm knows that the "peasant" variable is of type Person
peasant.dig_filth()   # shows warning -- Person doesn't have a dig_filth method

class King:
    def repress(self, peasant):
        # PyCharm has no idea what type the "peasant" parameter should be
        peasant.knock_over()   # no warning even though knock_over doesn't exist

King().repress(peasant)
# Even if I call the method once with a Person instance, PyCharm doesn't
# consider that to mean that the "peasant" parameter should always be a Person

这在一定程度上是有意义的。其他呼叫站点可以为该参数传递任何内容。但是,如果我的方法希望参数的类型为,则pygame.Surface我希望能够以某种方式向PyCharm指出,因此它可以Surface在其代码完成下拉列表中向我显示所有的属性,并在警告时突出显示警告我调用了错误的方法,依此类推。

有没有办法给PyCharm一个提示,然后说“ psst,该参数应该是X类型”?(或者,也许是本着动态语言的精神,“这个参数应该像X一样嘎嘎叫”?对此我可以接受。)


编辑:下面的CrazyCoder的答案就可以了。对于像我这样想要快速摘要的任何新手,这里是:

class King:
    def repress(self, peasant):
        """
        Exploit the workers by hanging on to outdated imperialist dogma which
        perpetuates the economic and social differences in our society.

        @type peasant: Person
        @param peasant: Person to repress.
        """
        peasant.knock_over()   # Shows a warning. And there was much rejoicing.

相关部分是@type peasant: Person文档字符串的行。

如果还转到“文件”>“设置”>“ Python集成工具”,并将“文档字符串格式”设置为“ Epytext”,则PyCharm的“视图”>“快速文档查找”将漂亮地打印参数信息,而不是仅按原样打印所有@ -lines。

When it comes to constructors, and assignments, and method calls, the PyCharm IDE is pretty good at analyzing my source code and figuring out what type each variable should be. I like it when it’s right, because it gives me good code-completion and parameter info, and it gives me warnings if I try to access an attribute that doesn’t exist.

But when it comes to parameters, it knows nothing. The code-completion dropdowns can’t show anything, because they don’t know what type the parameter will be. The code analysis can’t look for warnings.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

peasant = Person("Dennis", 37)
# PyCharm knows that the "peasant" variable is of type Person
peasant.dig_filth()   # shows warning -- Person doesn't have a dig_filth method

class King:
    def repress(self, peasant):
        # PyCharm has no idea what type the "peasant" parameter should be
        peasant.knock_over()   # no warning even though knock_over doesn't exist

King().repress(peasant)
# Even if I call the method once with a Person instance, PyCharm doesn't
# consider that to mean that the "peasant" parameter should always be a Person

This makes a certain amount of sense. Other call sites could pass anything for that parameter. But if my method expects a parameter to be of type, say, pygame.Surface, I’d like to be able to indicate that to PyCharm somehow, so it can show me all of Surface‘s attributes in its code-completion dropdown, and highlight warnings if I call the wrong method, and so on.

Is there a way I can give PyCharm a hint, and say “psst, this parameter is supposed to be of type X”? (Or perhaps, in the spirit of dynamic languages, “this parameter is supposed to quack like an X”? I’d be fine with that.)


EDIT: CrazyCoder’s answer, below, does the trick. For any newcomers like me who want the quick summary, here it is:

class King:
    def repress(self, peasant):
        """
        Exploit the workers by hanging on to outdated imperialist dogma which
        perpetuates the economic and social differences in our society.

        @type peasant: Person
        @param peasant: Person to repress.
        """
        peasant.knock_over()   # Shows a warning. And there was much rejoicing.

The relevant part is the @type peasant: Person line of the docstring.

If you also go to File > Settings > Python Integrated Tools and set “Docstring format” to “Epytext”, then PyCharm’s View > Quick Documentation Lookup will pretty-print the parameter information instead of just printing all the @-lines as-is.


回答 0

是的,您可以对方法及其参数使用特殊的文档格式,以便PyCharm可以知道类型。最新的PyCharm版本支持大多数常见的doc格式

例如,PyCharm从@param样式注释中提取类型。

另请参见reStructuredTextdocstring约定(PEP 257)。

另一个选择是Python 3注释。

参阅PyCharm文档部分以获取更多详细信息和示例。

Yes, you can use special documentation format for methods and their parameters so that PyCharm can know the type. Recent PyCharm version supports most common doc formats.

For example, PyCharm extracts types from @param style comments.

See also reStructuredText and docstring conventions (PEP 257).

Another option is Python 3 annotations.

Please refer to the PyCharm documentation section for more details and samples.


回答 1

如果您使用的是Python 3.0或更高版本,则还可以在函数和参数上使用注释。PyCharm会将这些解释为参数或返回值应具有的类型:

class King:
    def repress(self, peasant: Person) -> bool:
        peasant.knock_over() # Shows a warning. And there was much rejoicing.

        return peasant.badly_hurt() # Lets say, its not known from here that this method will always return a bool

有时,这对于不需要文档字符串的非公共方法很有用。另外一个好处是,这些注释可以通过代码访问:

>>> King.repress.__annotations__
{'peasant': <class '__main__.Person'>, 'return': <class 'bool'>}

更新:从PEP 484(已为Python 3.5接受)开始,使用注释指定参数和返回类型也是官方约定。

If you are using Python 3.0 or later, you can also use annotations on functions and parameters. PyCharm will interpret these as the type the arguments or return values are expected to have:

class King:
    def repress(self, peasant: Person) -> bool:
        peasant.knock_over() # Shows a warning. And there was much rejoicing.

        return peasant.badly_hurt() # Lets say, its not known from here that this method will always return a bool

Sometimes this is useful for non-public methods, that do not need a docstring. As an added benefit, those annotations can be accessed by code:

>>> King.repress.__annotations__
{'peasant': <class '__main__.Person'>, 'return': <class 'bool'>}

Update: As of PEP 484, which has been accepted for Python 3.5, it is also the official convention to specify argument and return types using annotations.


回答 2

PyCharm从@type pydoc字符串中提取类型。在此处此处查看PyCharm文档,以及Epydoc文档。它位于PyCharm的“旧版”部分,也许缺少某些功能。

class King:
    def repress(self, peasant):
        """
        Exploit the workers by hanging on to outdated imperialist dogma which
        perpetuates the economic and social differences in our society.

        @type peasant: Person
        @param peasant: Person to repress.
        """
        peasant.knock_over()   # Shows a warning. And there was much rejoicing.

相关部分是@type peasant: Person文档字符串的行。

我的目的不是要从CrazyCoder或原始提问者那里窃取分数,而应尽一切可能给予分数。我只是以为简单的答案应该在“答案”栏中。

PyCharm extracts types from a @type pydoc string. See PyCharm docs here and here, and Epydoc docs. It’s in the ‘legacy’ section of PyCharm, perhaps it lacks some functionality.

class King:
    def repress(self, peasant):
        """
        Exploit the workers by hanging on to outdated imperialist dogma which
        perpetuates the economic and social differences in our society.

        @type peasant: Person
        @param peasant: Person to repress.
        """
        peasant.knock_over()   # Shows a warning. And there was much rejoicing.

The relevant part is the @type peasant: Person line of the docstring.

My intention is not to steal points from CrazyCoder or the original questioner, by all means give them their points. I just thought the simple answer should be in an ‘answer’ slot.


回答 3

我正在使用PyCharm Professional 2016.1编写py2.6-2.7代码,发现使用reStructuredText可以以更简洁的方式表达类型:

class Replicant(object):
    pass


class Hunter(object):
    def retire(self, replicant):
        """ Retire the rogue or non-functional replicant.
        :param Replicant replicant: the replicant to retire.
        """
        replicant.knock_over()  # Shows a warning.

参见:https : //www.jetbrains.com/help/pycharm/2016.1/type-hinting-in-pycharm.html#legacy

I’m using PyCharm Professional 2016.1 writing py2.6-2.7 code, and I found that using reStructuredText I can express types in a more succint way:

class Replicant(object):
    pass


class Hunter(object):
    def retire(self, replicant):
        """ Retire the rogue or non-functional replicant.
        :param Replicant replicant: the replicant to retire.
        """
        replicant.knock_over()  # Shows a warning.

See: https://www.jetbrains.com/help/pycharm/2016.1/type-hinting-in-pycharm.html#legacy


回答 4

您还可以断言一个类型,Pycharm会推断出它:

def my_function(an_int):
    assert isinstance(an_int, int)
    # Pycharm now knows that an_int is of type int
    pass

You can also assert for a type and Pycharm will infer it:

def my_function(an_int):
    assert isinstance(an_int, int)
    # Pycharm now knows that an_int is of type int
    pass

如何像使用Sublime Text一样围绕PyCharm中的选定文本

问题:如何像使用Sublime Text一样围绕PyCharm中的选定文本

有没有一种方法可以配置PyCharm,使其能够仅通过键入括号键就可以将所选代码括在括号中,就像我们使用SublimText 2一样?

Is there a way to configure PyCharm to be able to surround selected code with parenthesis by just typing on the parenthesis key, like when we use SublimText 2?


回答 0

我想你想要类似的东西

Settings | Editor | General | Smart Keys -> Surround selection on typing quote or brace

I think you want something like

Settings | Editor | General | Smart Keys -> Surround selection on typing quote or brace


回答 1

PyCharm 4.0可以选择Surround With...,选择代码段并按

ctrl+ alt+T

或在Mac上:+ +T

选项1应该为您提供所需的功能:

PyCharm 4.0 has the option to Surround With..., by selecting your code snippet and pressing

ctrl + alt + T

or on Mac: + + T

Option 1 should provide you with the functionality you are looking for:


回答 2

Windows:打开pycharm并选择文件,设置,编辑器,智能键,在列表中,您将选中“键入引号或花括号时的环绕选择”,然后应用。 在此处输入图片说明

智能钥匙的pycharm位置的图像

Windows: open pycharm and select file, settings, Editor, Smart Keys, in the list you will check “Surround selection on typing quote or brace”, then apply. enter image description here

Image of pycharm location of smart keys


“用户警告:Matplotlib当前正在使用agg,它是非GUI后端,因此无法显示该图。” 在Pycharm上用pyplot绘制图时

问题:“用户警告:Matplotlib当前正在使用agg,它是非GUI后端,因此无法显示该图。” 在Pycharm上用pyplot绘制图时

我正在尝试使用pyplot绘制一个简单的图形,例如:

import matplotlib.pyplot as plt
plt.plot([1,2,3],[5,7,4])
plt.show()

但该图未出现,并且我收到以下消息:

UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.

我在几个地方看到必须使用以下命令更改matplotlib的配置:

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

我这样做了,但是却收到一条错误消息,因为它找不到模块:

ModuleNotFoundError: No module named 'tkinter'

然后,我尝试使用安装“ tkinter” pip install tkinter(在虚拟环境中),但找不到它:

Collecting tkinter
  Could not find a version that satisfies the requirement tkinter (from versions: )
No matching distribution found for tkinter

我还应该提到,我正在使用虚拟环境在Pycharm Community Edition IDE上运行所有这些程序,并且我的操作系统是Linux / Ubuntu 18.04。

我想知道如何解决此问题才能显示图形。

I am trying to plot a simple graph using pyplot, e.g.:

import matplotlib.pyplot as plt
plt.plot([1,2,3],[5,7,4])
plt.show()

but the figure does not appear and I get the following message:

UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.

I saw in several places that one had to change the configuration of matplotlib using the following:

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

I did this, but then got an error message because it cannot find a module:

ModuleNotFoundError: No module named 'tkinter'

Then, I tried to install “tkinter” using pip install tkinter (inside the virtual environment), but it does not find it:

Collecting tkinter
  Could not find a version that satisfies the requirement tkinter (from versions: )
No matching distribution found for tkinter

I should also mention that I am running all this on Pycharm Community Edition IDE using a virtual environment, and that my operating system is Linux/Ubuntu 18.04.

I would like to know how I can solve this problem in order to be able to display the graph.


回答 0

我找到了解决问题的方法(借助于ImportanceOfBeingErnest的帮助)。

我要做的就是tkinter使用以下命令通过Linux bash终端安装:

sudo apt-get install python3-tk

而不是将其安装pip在Pycharm的虚拟环境中或直接安装在虚拟环境中。

I found a solution to my problem (thanks to the help of ImportanceOfBeingErnest).

All I had to do was to install tkinter through the Linux bash terminal using the following command:

sudo apt-get install python3-tk

instead of installing it with pip or directly in the virtual environment in Pycharm.


回答 1

就我而言,该错误消息表示我在无头控制台中工作。因此plt.show()无法正常工作。起作用的是plt.savefig

import matplotlib.pyplot as plt

plt.plot([1,2,3], [5,7,4])
plt.savefig("mygraph.png")

我在github仓库上找到了答案。

In my case, the error message was implying that I was working in a headless console. So plt.show() could not work. What worked was calling plt.savefig:

import matplotlib.pyplot as plt

plt.plot([1,2,3], [5,7,4])
plt.savefig("mygraph.png")

I found the answer on a github repository.


回答 2

如果您使用Arch Linux(分布类似ManjaroAntegros),只需键入:

sudo pacman -S tk

所有都将完美运行!

If you use Arch Linux (distributions like Manjaro or Antegros) simply type:

sudo pacman -S tk

And all will work perfectly!


回答 3

尝试一下,import tkinter因为pycharm已经为您安装了tkinter,所以我看了为Python安装tkinter

您可以尝试:

import tkinter
import matplotlib
matplotlib.use('TkAgg')
plt.plot([1,2,3],[5,7,4])
plt.show()

作为tkinter的安装方式

我已经尝试过,在计算机上运行似乎没有错误,它成功显示了该图。也许是因为pycharm将tkinter作为系统软件包,所以您不需要安装它。但是,如果您在内部找不到tkinter,则可以去Tkdocs看看安装tkinter的方法,正如它所提到的,tkinter是python的核心软件包。

Try import tkinter because pycharm already installed tkinter for you, I looked Install tkinter for Python

You can maybe try:

import tkinter
import matplotlib
matplotlib.use('TkAgg')
plt.plot([1,2,3],[5,7,4])
plt.show()

as a tkinter-installing way

I’ve tried your way, it seems no error to run at my computer, it successfully shows the figure. maybe because pycharm have tkinter as a system package, so u don’t need to install it. But if u can’t find tkinter inside, you can go to Tkdocs to see the way of installing tkinter, as it mentions, tkinter is a core package for python.


回答 4

我在PyCharm中也遇到了这个问题。此问题是因为您的计算机中没有tkinter模块。

要安装,请遵循以下步骤(选择合适的操作系统)

对于ubuntu用户

 sudo apt-get install python-tk

要么

 sudo apt-get install python3-tk

对于Centos用户

 sudo yum install python-tkinter

要么

 sudo yum install python3-tkinter

对于Windows,请使用pip安装tk

安装tkinter后,重新启动Pycharm并运行您的代码,它将起作用

I too had this issue in PyCharm. This issue is because you don’t have tkinter module in your machine.

To install follow the steps given below (select your appropriate os)

For ubuntu users

 sudo apt-get install python-tk

or

 sudo apt-get install python3-tk

For Centos users

 sudo yum install python-tkinter

or

 sudo yum install python3-tkinter

For Windows, use pip to install tk

After installing tkinter restart your Pycharm and run your code, it will work


回答 5

安装简单

pip3 install PyQt5==5.9.2

这个对我有用。

Simple install

pip3 install PyQt5==5.9.2

It works for me.


回答 6

您可以使用fromagg到Tkinter TKAggusing命令将后端使用的matplotlib更改为

matplotlib.use('TKAgg',warn=False, force=True)

You can change the matplotlib using backend using the from agg to Tkinter TKAgg using command

matplotlib.use('TKAgg',warn=False, force=True)

回答 7

Linux Mint 19.对我有帮助:

sudo apt install tk-dev

PS软件包安装后重新编译python解释器。

Linux Mint 19. Helped for me:

sudo apt install tk-dev

P.S. Recompile python interpreter after package install.


回答 8

以防万一这对任何人都有帮助。

Python版本:3.7.7平台:Ubuntu 18.04.4 LTS

这带有默认的python 3.6.9版本,但是我已经在上面安装了自己的3.7.7版本python(已从源代码安装了它)

即使当 help('module')列表中显示了tkinter,。

以下步骤对我有用:

  1. sudo apt-get install tk-dev.

重建python:1.导航到您的python文件夹并运行检查:

cd Python-3.7.7
sudo ./configure --enable-optimizations
  1. 使用make命令进行构建: sudo make -j 8 —这是8个处理器的数量,请使用nproc命令。
  2. 使用以下方式安装:

    sudo make altinstall
    

不要使用sudo make install,它将覆盖默认的3.6.9版本,以后可能会很混乱。

  1. 立即检查tkinter
    python3.7 -m tkinter
    

将弹出一个窗口框,您的Tkinter现在已准备就绪。

Just in case if this helps anybody.

Python version: 3.7.7 platform: Ubuntu 18.04.4 LTS

This came with default python version 3.6.9, however I had installed my own 3.7.7 version python on it (installed building it from source)

tkinter was not working even when the help('module') shows tkinter in the list.

The following steps worked for me:

  1. sudo apt-get install tk-dev.

rebuild the python: 1. Navigate to your python folder and run the checks:

cd Python-3.7.7
sudo ./configure --enable-optimizations
  1. Build using make command: sudo make -j 8 — here 8 are the number of processors, check yours using nproc command.
  2. Installing using:

    sudo make altinstall
    

Don’t use sudo make install, it will overwrite default 3.6.9 version, which might be messy later.

  1. Check tkinter now
    python3.7 -m tkinter
    

A windows box will pop up, your tkinter is ready now.


回答 9

在升级了很多软件包(Spyder3到4,Keras以及Tensorflow很多依赖)之后,我今天遇到了同样的问题!我不知道发生了什么事。但是继续使用Spyder3的(基于conda的)虚拟环境没有问题。尽管如上所示安装tkinter或更改了后端,via matplotlib.use('TkAgg)或者这篇有关如何更改后端的不错的帖子 可能很好地解决了问题,但我不认为这些是严格的解决方案。对我来说,卸载matplotlib并重新安装它是不可思议的,问题已解决。

pip uninstall matplotlib

…然后,安装

pip install matplotlib

综上所述,这可能是一个程序包管理问题,顺便说一句,在可行的情况下,我会同时使用condapip

After upgrading lots of packages (Spyder 3 to 4, Keras and Tensorflow and lots of their dependencies), I had the same problem today! I cannot figure out what happened; but the (conda-based) virtual environment that kept using Spyder 3 did not have the problem. Although installing tkinter or changing the backend, via matplotlib.use('TkAgg) as shown above, or this nice post on how to change the backend, might well resolve the problem, I don’t see these as rigid solutions. For me, uninstalling matplotlib and reinstalling it was magic and the problem was solved.

pip uninstall matplotlib

… then, install

pip install matplotlib

From all the above, this could be a package management problem, and BTW, I use both conda and pip, whenever feasible.


回答 10

当我在Spyder上遇到此错误时,我从逐行运行代码变为突出显示绘图代码块并立即运行所有代码。瞧,图像出现了。

When I ran into this error on Spyder, I changed from running my code line by line to highlighting my block of plotting code and running that all at once. Voila, the image appeared.


回答 11

内联添加了%matplotlib, 并且我的情节出现在Jupyter Notebook中。

I added %matplotlib inline and my plot showed up in Jupyter Notebook.


回答 12

@xicocaio的评论应突出显示。

从某种意义上说,tkinter是特定于python版本的,sudo apt-get install python3-tk它将专门为您的默认python版本安装tkinter。假设您在各种虚拟环境中具有不同的python版本,则必须为该虚拟环境中使用的所需python版本安装tkinter。例如,sudo apt-get install python3.7-tkNo module named ' tkinter'即使不为全局python版本安装它,这样做仍然会导致错误。

The comment by @xicocaio should be highlighted.

tkinter is python version-specific in the sense that sudo apt-get install python3-tk will install tkinter exclusively for your default version of python. Suppose you have different python versions within various virtual environments, you will have to install tkinter for the desired python version used in that virtual environment. For example, sudo apt-get install python3.7-tk. Not doing this will still lead to No module named ' tkinter' errors, even after installing it for the global python version.


如何在PyCharm中选择Python版本?

问题:如何在PyCharm中选择Python版本?

我拥有PyCharm 1.5.4,并使用“打开目录”选项在IDE中打开文件夹的内容。

我选择了Python 3.2版(它显示在“外部库”节点下)。

如何选择其他版本的Python(已经安装在计算机上),以便PyCharm改用该版本?

I have PyCharm 1.5.4 and have used the “Open Directory” option to open the contents of a folder in the IDE.

I have Python version 3.2 selected (it shows up under the “External Libraries” node).

How can I select another version of Python (that I already have installed on my machine) so that PyCharm uses that version instead?


回答 0

文件->设置

首选项->项目解释器-> Python解释器

如果未列出,则添加它。

File -> Settings

Preferences->Project Interpreter->Python Interpreters

If it’s not listed add it.


回答 1

我认为您是说您已经安装了python2和python3,并在Pycharm>设置>项目解释器下添加了对每个版本的引用

我想您要问的是如何在Python 2上运行某些项目,在Python 3上运行某些项目。

如果是这样,您可以在“运行”>“编辑配置”下查看

I think you are saying that you have python2 and python3 installed and have added a reference to each version under Pycharm > Settings > Project Interpreter

What I think you are asking is how do you have some projects run with Python 2 and some projects running with Python 3.

If so, you can look under Run > Edit Configurations


回答 2

PyCharm 2019.1+

状态栏中有一项名为“ 解释器”的新功能(向下滚动一点)。这使得在python解释器之间切换和查看所使用的版本更加容易。

启用状态栏

如果看不到状态栏,则可以通过运行“查找操作”命令(在Mac上为Ctrl+ Shift+ A+ + A)轻松激活它。然后输入状态栏并选择查看:状态栏以查看它。

PyCharm 2019.1+

There is a new feature called Interpreter in status bar (scroll down a little bit). This makes switching between python interpreters and seeing which version you’re using easier.

Enable status bar

In case you cannot see the status bar, you can easily activate it by running the Find Action command (Ctrl+Shift+A or + +A on mac). Then type status bar and choose View: Status Bar to see it.


回答 3

在集成了PyCharm的Intellij Ultimate中也可能发生这种情况。问题如上所述,您选择了错误的解释器。

要针对任何给定项目修复此问题的确切方法是转到“ 项目设置项目”,然后调整Project SDK。如果您没有添加Python 3,则可以通过导航到python3二进制文件来添加New Project SDK。这将修复上面列出的错误。“项目设置”的快捷方式是蓝色棋盘式图标。

您还可以将Python 3添加为Python项目的默认解释器。在OSX上,它位于文件中其他设置默认项目结构。您可以在此处设置Project SDK,该SDK现在将应用于每个新项目。它在其他平台上可以有所不同,但仍然相似。

This can also happen in Intellij Ultimate, which has PyCharm integrated. The issue is as diagnosed above, you have the wrong interpreter selected.

The exact method to fix this for any given project is to go to Project SettingsProject and adjust the Project SDK. You can add a New Project SDK if you don’t have Python 3 added by navigating to the python3 binary. This will fix the errors listed above. A shortcut to Project Settings is the blue checkerboard-type icon.

You can also add Python 3 as the default interpreter for Python projects. On OSX this is in File..Other SettingsDefault Project Structure. There you can set the Project SDK which will now apply on each new project. It can be different on other platforms, but still similar.


回答 4

去:

Files -> Settings -> Project -> *"Your Project Name"* -> Project Interpreter

在这里,您可以查看已为python2安装了哪些外部库以及为python3安装了哪些外部库。

根据您的要求选择所需的python版本。

Go to:

Files -> Settings -> Project -> *"Your Project Name"* -> Project Interpreter

There you can see which external libraries you have installed for python2 and which for python3.

Select the required python version according to your requirements.


回答 5

快速回答:

  • File -> Setting
  • project部分的左侧->Project interpreter
  • 选择所需 Project interpreter
  • Apply + OK

[ 注意 ]:

在Pycharm 2018和2017上测试。


Quick Answer:

  • File –> Setting
  • In left side in project section –> Project interpreter
  • Select desired Project interpreter
  • Apply + OK

[NOTE]:

Tested on Pycharm 2018 and 2017.



如何使用PyCharm调试Scrapy项目

问题:如何使用PyCharm调试Scrapy项目

我正在使用Python 2.7开发Scrapy 0.20。我发现PyCharm具有良好的Python调试器。我想使用它测试我的Scrapy蜘蛛。有人知道该怎么做吗?

我尝试过的

实际上,我尝试将Spider作为脚本运行。结果,我构建了该脚本。然后,我尝试将Scrapy项目添加到PyCharm中,如下所示:
File->Setting->Project structure->Add content root.

但是我不知道我还要做什么

I am working on Scrapy 0.20 with Python 2.7. I found PyCharm has a good Python debugger. I want to test my Scrapy spiders using it. Anyone knows how to do that please?

What I have tried

Actually I tried to run the spider as a script. As a result, I built that script. Then, I tried to add my Scrapy project to PyCharm as a model like this:
File->Setting->Project structure->Add content root.

But I don’t know what else I have to do


回答 0

scrapy命令是python脚本,这意味着您可以从PyCharm内部启动它。

当检查scrapy二进制文件(which scrapy)时,您会注意到这实际上是一个python脚本:

#!/usr/bin/python

from scrapy.cmdline import execute
execute()

这意味着scrapy crawl IcecatCrawler还可以像这样执行命令 :python /Library/Python/2.7/site-packages/scrapy/cmdline.py crawl IcecatCrawler

尝试找到scrapy.cmdline软件包。就我而言,位置在这里:/Library/Python/2.7/site-packages/scrapy/cmdline.py

使用该脚本作为脚本在PyCharm中创建运行/调试配置。用scrapy命令和Spider填充脚本参数。在这种情况下crawl IcecatCrawler

像这样:

将断点放在爬网代码中的任何位置,它应该可以正常工作。

The scrapy command is a python script which means you can start it from inside PyCharm.

When you examine the scrapy binary (which scrapy) you will notice that this is actually a python script:

#!/usr/bin/python

from scrapy.cmdline import execute
execute()

This means that a command like scrapy crawl IcecatCrawler can also be executed like this: python /Library/Python/2.7/site-packages/scrapy/cmdline.py crawl IcecatCrawler

Try to find the scrapy.cmdline package. In my case the location was here: /Library/Python/2.7/site-packages/scrapy/cmdline.py

Create a run/debug configuration inside PyCharm with that script as script. Fill the script parameters with the scrapy command and spider. In this case crawl IcecatCrawler.

Like this:

Put your breakpoints anywhere in your crawling code and it should work™.


回答 1

您只需要这样做。

在项目的搜寻器文件夹上创建一个Python文件。我使用了main.py。

  • 项目
    • 履带式
      • 履带式
        • 蜘蛛网
      • main.py
      • scrapy.cfg

在您的main.py内部,将下面的代码。

from scrapy import cmdline    
cmdline.execute("scrapy crawl spider".split())

并且您需要创建一个“运行配置”以运行您的main.py。

这样做,如果在代码上放置断点,它将在此处停止。

You just need to do this.

Create a Python file on crawler folder on your project. I used main.py.

  • Project
    • Crawler
      • Crawler
        • Spiders
      • main.py
      • scrapy.cfg

Inside your main.py put this code below.

from scrapy import cmdline    
cmdline.execute("scrapy crawl spider".split())

And you need to create a “Run Configuration” to run your main.py.

Doing this, if you put a breakpoint at your code it will stop there.


回答 2

截至2018.1,这变得容易得多。现在Module name,您可以在项目的中进行选择Run/Debug Configuration。将此设置为,scrapy.cmdline并将其设置Working directory为scrapy项目的根目录(其中有一个目录settings.py)。

像这样:

现在,您可以添加断点来调试代码。

As of 2018.1 this became a lot easier. You can now select Module name in your project’s Run/Debug Configuration. Set this to scrapy.cmdline and the Working directory to the root dir of the scrapy project (the one with settings.py in it).

Like so:

Now you can add breakpoints to debug your code.


回答 3

我正在使用Python 3.5.0在virtualenv中运行scrapy,并设置“ script”参数/path_to_project_env/env/bin/scrapy为我解决了该问题。

I am running scrapy in a virtualenv with Python 3.5.0 and setting the “script” parameter to /path_to_project_env/env/bin/scrapy solved the issue for me.


回答 4

intellij的想法也可以。

创建main.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#coding=utf-8
import sys
from scrapy import cmdline
def main(name):
    if name:
        cmdline.execute(name.split())



if __name__ == '__main__':
    print('[*] beginning main thread')
    name = "scrapy crawl stack"
    #name = "scrapy crawl spa"
    main(name)
    print('[*] main thread exited')
    print('main stop====================================================')

显示如下:

intellij idea also work.

create main.py:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#coding=utf-8
import sys
from scrapy import cmdline
def main(name):
    if name:
        cmdline.execute(name.split())



if __name__ == '__main__':
    print('[*] beginning main thread')
    name = "scrapy crawl stack"
    #name = "scrapy crawl spa"
    main(name)
    print('[*] main thread exited')
    print('main stop====================================================')

show below:


回答 5

要在可接受的答案中添加一点点,将近一个小时后,我发现必须从下拉列表(图标工具栏中央附近)中选择正确的“运行配置”,然后单击“调试”按钮才能使其正常工作。希望这可以帮助!

To add a bit to the accepted answer, after almost an hour I found I had to select the correct Run Configuration from the dropdown list (near the center of the icon toolbar), then click the Debug button in order to get it to work. Hope this helps!


回答 6

我也在使用PyCharm,但没有使用其内置的调试功能。

为了调试,我使用ipdb。我设置了键盘快捷键,可以import ipdb; ipdb.set_trace()在希望断点发生的任何行上插入。

然后,我可以键入n执行下s一条语句,以进入函数,键入任何对象名称以查看其值,更改执行环境,键入c以继续执行…

这非常灵活,可以在PyCharm之外的其他环境中使用,在这些环境中您无法控制执行环境。

只需输入您的虚拟环境,pip install ipdb然后放在import ipdb; ipdb.set_trace()您要暂停执行的行上即可。

I am also using PyCharm, but I am not using its built-in debugging features.

For debugging I am using ipdb. I set up a keyboard shortcut to insert import ipdb; ipdb.set_trace() on any line I want the break point to happen.

Then I can type n to execute the next statement, s to step into a function, type any object name to see its value, alter execution environment, type c to continue execution…

This is very flexible, works in environments other than PyCharm, where you don’t control the execution environment.

Just type in your virtual environment pip install ipdb and place import ipdb; ipdb.set_trace() on a line where you want the execution to pause.

UPDATE

You can also pip install pdbpp and use the standard import pdb; pdb.set_trace instead of ipdb. PDB++ is nicer in my opinion.


回答 7

根据该文件https://doc.scrapy.org/en/latest/topics/practices.html

import scrapy
from scrapy.crawler import CrawlerProcess

class MySpider(scrapy.Spider):
    # Your spider definition
    ...

process = CrawlerProcess({
    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
})

process.crawl(MySpider)
process.start() # the script will block here until the crawling is finished

According to the documentation https://doc.scrapy.org/en/latest/topics/practices.html

import scrapy
from scrapy.crawler import CrawlerProcess

class MySpider(scrapy.Spider):
    # Your spider definition
    ...

process = CrawlerProcess({
    'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
})

process.crawl(MySpider)
process.start() # the script will block here until the crawling is finished

回答 8

我使用以下简单脚本:

from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings

process = CrawlerProcess(get_project_settings())

process.crawl('your_spider_name')
process.start()

I use this simple script:

from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings

process = CrawlerProcess(get_project_settings())

process.crawl('your_spider_name')
process.start()

回答 9

扩展了@Rodrigo的答案版本,我添加了此脚本,现在我可以从配置中设置蜘蛛网名称,而不用更改字符串。

import sys
from scrapy import cmdline

cmdline.execute(f"scrapy crawl {sys.argv[1]}".split())

Extending @Rodrigo’s version of the answer I added this script and now I can set spider name from configuration instead of changing in the string.

import sys
from scrapy import cmdline

cmdline.execute(f"scrapy crawl {sys.argv[1]}".split())

pycharm自动将制表符转换为空格

问题:pycharm自动将制表符转换为空格

我正在使用pycharm IDE进行python开发,它对Django代码非常完美,因此怀疑将制表符转换为空格是默认行为,但是在python IDE中到处都有错误,因为它无法自动将制表符转换为空格,有没有一种方法可以实现这个。

I am using pycharm IDE for python development it works perfectly fine for django code so suspected that converting tabs to spaces is default behaviour, however in python IDE is giving errors everywhere because it can’t convert tabs to spaces automatically is there a way to achieve this.


回答 0

更改代码样式以使用空格而不是制表符:

然后在项目视图中选择要转换的文件夹并使用Code| 重新格式化代码

Change the code style to use spaces instead of tabs:

Then select a folder you want to convert in the Project View and use Code | Reformat Code.


回答 1

对于选择,还可以使用“到空格”功能转换选择。我通常只通过ctrl-shift-A使用它,然后从那里找到“到空格”。

For selections, you can also convert the selection using the “To spaces” function. I usually just use it via the ctrl-shift-A then find “To Spaces” from there.


回答 2

这只会转换选项卡,而不会更改其他任何内容:

Edit -> Convert Indents -> To Spaces

This only converts the tabs without changing anything else:

Edit -> Convert Indents -> To Spaces

回答 3

CTRL + SHIFT + A =>打开弹出窗口来选择选项,选择为空格到所有标签转换为空间,或以标签的所有空间转换为制表。

ctrl + shift + A => open pop window to select options, select to spaces to convert all tabs as space, or to tab to convert all spaces as tab.


回答 4

PyCharm 2019.1

如果要更改常规设置:

开放的喜好,在MacOS上;或在Windows / Linux的Ctrl+ Alt+S

转到“编辑器”->“代码样式”->“ Python”,如果要遵循PEP-8,请选择“ 制表符大小:4”,“ 缩进:4 ”和“ 继续缩进:8”,如下所示:

应用更改,然后单击“确定”。

如果要仅将更改应用于当前文件

选项1:您可以在导航栏中选择:编辑->转换缩进->转换为空格。(见下图)

选项2:您可以通过在macOS或Windows / Linux 上运行“ 查找操作”快捷方式来执行“到空间”操作。然后键入“ To Spaces”,然后如下图所示运行操作。ActrlA

PyCharm 2019.1

If you want to change the general settings:

Open preferences, in macOS ; or in Windows/Linux Ctrl + Alt + S.

Go to Editor -> Code Style -> Python, and if you want to follow PEP-8, choose Tab size: 4, Indent: 4, and Continuation indent: 8 as shown below:

Apply the changes, and click on OK.

If you want to apply the changes just to the current file

Option 1: You can choose in the navigation bar: Edit -> Convert Indent -> To Spaces. (see image below)

Option 2: You can execute “To Spaces” action by running the Find Action shortcut: A on macOS or ctrlA on Windows/Linux. Then type “To Spaces”, and run the action as shown in the image below.


回答 5

ctr + alt + shift + L->重新格式化整个文件:)

ctr+alt+shift+L -> reformat whole file :)


回答 6

对我来说,它有一个名为〜/ .editorconfig的文件,它将覆盖我的标签设置。我删除了它(肯定有一天会再次咬我),但是它解决了我的pycharm问题

For me it was having a file called ~/.editorconfig that was overriding my tab settings. I removed that (surely that will bite me again someday) but it fixed my pycharm issue


如何在PyCharm终端中激活virtualenv?

问题:如何在PyCharm终端中激活virtualenv?

我已经设置了PyCharm,创建了我的virtualenv(通过virtual env命令,或者直接在PyCharm中),并将那个环境激活为我的解释器。一切正常。

但是,如果我使用“工具,打开终端”打开终端,则提供的shell提示使用虚拟环境。我仍然必须source ~/envs/someenv/bin/activate在该终端内使用才能激活它。

另一种方法是在外壳中激活环境,然后从该环境运行PyCharm。这是“可行的”但很丑陋,这意味着如果我从PyCharm切换环境或项目,我会遇到重大问题:我现在使用的是完全错误的环境。

还有其他更简便的方法来使“工具,打开终端”自动激活虚拟环境吗?

I’ve set up PyCharm, created my virtualenv (either through the virtual env command, or directly in PyCharm) and activated that environment as my Interpreter. Everything is working just fine.

However, if I open a terminal using “Tools, Open Terminal”, the shell prompt supplied is not using the virtual env; I still have to use source ~/envs/someenv/bin/activate within that Terminal to activate it.

Another method is to activate the environment in a shell, and run PyCharm from that environment. This is “workable” but pretty ugly, and means I have major problems if I switch environments or projects from PyCharm: I’m now using the totally-wrong environment.

Is there some other, much-easier way to have “Tools, Open Terminal” automatically activate the virtual environment?


回答 0

编辑:

根据https://www.jetbrains.com/pycharm/whatsnew/#v2016-3-venv-in-terminal的介绍,PyCharm 2016.3(于2016年11月发布)具有开箱即用的virutalenv支持

bash,zsh,fish和Windows cmd支持自动virtualenv。您可以在“设置”(“首选项”)|“自定义”中自定义外壳首选项。工具| 终奌站。


旧方法:

.pycharmrc在主文件夹中创建一个包含以下内容的文件

source ~/.bashrc
source ~/pycharmvenv/bin/activate

使用您的virtualenv路径作为最后一个参数。

然后将Shell Preferences-> Project Settings-> Shell path设置为

/bin/bash --rcfile ~/.pycharmrc

Edit:

According to https://www.jetbrains.com/pycharm/whatsnew/#v2016-3-venv-in-terminal, PyCharm 2016.3 (released Nov 2016) has virutalenv support for terminals out of the box

Auto virtualenv is supported for bash, zsh, fish, and Windows cmd. You can customize your shell preference in Settings (Preferences) | Tools | Terminal.


Old Method:

Create a file .pycharmrc in your home folder with the following contents

source ~/.bashrc
source ~/pycharmvenv/bin/activate

Using your virtualenv path as the last parameter.

Then set the shell Preferences->Project Settings->Shell path to

/bin/bash --rcfile ~/.pycharmrc

回答 1

更新:

设置(首选项)|首选项中的首选项 工具| 终端是全球性的。
如果为每个项目使用venv,请记住使用当前路径变量和默认venv名称:

"cmd.exe" /k ""%CD%\venv\Scripts\activate"" 

对于Windows用户:在虚拟环境中使用PyCharm时,可以使用该/K参数cmd.exe自动设置虚拟环境。

PyCharm 3或4: ,,Settings 和添加。TerminalDefault shell/K <path-to-your-activate.bat>

PyCharm 5: ,SettingsToolsTerminal并添加/K <path-to-your-activate.bat>Shell path

PyCharm 2016.1或2016.2: ,SettingsToolsTerminal并添加""/K <path-to-your-activate.bat>""Shell path,并添加(介意引号)。还要在cmd.exe周围加上引号,导致:

"cmd.exe" /k ""C:\mypath\my-venv\Scripts\activate.bat""

Update:

The preferences in Settings (Preferences) | Tools | Terminal are global.
If you use a venv for each project, remember to use current path variable and a default venv name:

"cmd.exe" /k ""%CD%\venv\Scripts\activate"" 

For Windows users: when using PyCharm with a virtual environment, you can use the /K parameter to cmd.exe to set the virtual environment automatically.

PyCharm 3 or 4: Settings, Terminal, Default shell and add /K <path-to-your-activate.bat>.

PyCharm 5: Settings, Tools, Terminal, and add /K <path-to-your-activate.bat> to Shell path.

PyCharm 2016.1 or 2016.2: Settings, Tools, Terminal, and add ""/K <path-to-your-activate.bat>"" to Shell path and add (mind the quotes). Also add quotes around cmd.exe, resulting in:

"cmd.exe" /k ""C:\mypath\my-venv\Scripts\activate.bat""


回答 2

对于Windows用户,在Windows下使用PyCharm和虚拟环境时,可以使用/ k参数cmd.exe来自动设置虚拟环境。

转到“设置”,“终端”,“默认外壳”并添加/K <path-to-your-activate.bat>

我没有对早期回复发表评论的声誉,因此请发布此更正版本。这确实节省了很多时间。

更新:

注意:Pycharm现在直接支持虚拟环境,对我来说似乎很好用-因此不再需要我的解决方法。

For Windows users when using PyCharm and a virtual environment under Windows, you can use the /k parameter to cmd.exe to set the virtual environment automatically.

Go to Settings, Terminal, Default shell and add /K <path-to-your-activate.bat>.

I don’t have the reputation to comment on the earlier response so posting this corrected version. This really saves a LOT of time.

Update:

Note: Pycharm now supports virtual environments directly and it seems to work well for me – so my workaround not needed anymore.


回答 3

根据彼得的回答和实验,我提出了一个很好的“一般解决方案”,可以解决以下问题:

  • 恢复登录外壳程序的行为。PyCharm通常运行登录外壳程序,但是–rcfile阻止了这种情况的发生。脚本仍然使用–rcfile,但是尝试模拟登录shell的INVOCATION行为。
  • 无需为每个环境创建rcfile
  • 如果您更改环境,则无需更新项目设置。

将此脚本放入bin目录中的某个位置。例如〜/ bin / pycharmactivate

if [ -r "/etc/profile" ] ; then . /etc/profile ; fi
if [ -r "~/.bash_profile" ] ; then
    . ~/.bash_profile
elif [ -r "~/.bash_login" ] ; then
    . ~/.bash_login
elif [ -r "~/.profile" ] ; then
    . ~/.profile
fi
ACTIVATERC=`cat .idea/workspace.xml | perl -n -e 'print "\$1/bin/activate" if m:option name="SDK_HOME" value="\\\$USER_HOME\\\$(.*)/bin/python":'`
if [ -n "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; else echo "Could not find virtualenv from PyCharm" ; fi

然后将PyCharm的Shell路径设置为:

/bin/bash --rcfile ~/bin/pycharmactivate

Based on answers from Peter and experimentation, I’ve come up with a good “general solution”, which solves the following:

  • Restores the behaviour of a login shell. PyCharm normally runs a login shell, but –rcfile stopped this happening. Script still uses –rcfile, but attempts to emulate the INVOCATION behaviour of a login shell.
  • Removes the need to create an rcfile for each environment
  • Removes the need to update the project settings if you change the environment.

Drop this script into a bin directory somewhere. E.g. ~/bin/pycharmactivate

if [ -r "/etc/profile" ] ; then . /etc/profile ; fi
if [ -r "~/.bash_profile" ] ; then
    . ~/.bash_profile
elif [ -r "~/.bash_login" ] ; then
    . ~/.bash_login
elif [ -r "~/.profile" ] ; then
    . ~/.profile
fi
ACTIVATERC=`cat .idea/workspace.xml | perl -n -e 'print "\$1/bin/activate" if m:option name="SDK_HOME" value="\\\$USER_HOME\\\$(.*)/bin/python":'`
if [ -n "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; else echo "Could not find virtualenv from PyCharm" ; fi

Then set PyCharm’s Shell path to:

/bin/bash --rcfile ~/bin/pycharmactivate

回答 4

PyCharm 4现在在IDE中集成了virtualenvs。选择项目解释器时,可以创建,添加或选择一个virtualenv。他们添加了一个在配置的项目解释器中运行的“ Python控制台”。

更多信息在这里。

PyCharm 4 now has virtualenvs integrated in the IDE. When selecting your project interpreter, you can create, add, or select a virtualenv. They’ve added a “Python Console” that runs in the configured project interpreter.

More info here.


回答 5

谢谢克里斯,您的脚本适用于某些项目,但不是我的机器上的全部。这是我编写的脚本,希望任何人都觉得它有用。

#Stored in ~/.pycharmrc 

ACTIVATERC=$(python -c 'import re
import os
from glob import glob

try:
  #sets Current Working Directory to _the_projects .idea folder
  os.chdir(os.getcwd()+"/.idea") 

  #gets every file in the cwd and sets _the_projects iml file
  for file in glob("*"): 
    if re.match("(.*).iml", file):
      project_iml_file = file

  #gets _the_virtual_env for _the_project
  for line in open(project_iml_file):
    env_name = re.findall("~/(.*)\" jdkType", line.strip())
    # created or changed a virtual_env after project creation? this will be true
    if env_name:
      print env_name[0] + "/bin/activate"
      break

    inherited = re.findall("type=\"inheritedJdk\"", line.strip())
    # set a virtual_env during project creation? this will be true
    if inherited:
      break

  # find _the_virtual_env in misc.xml
  if inherited:
    for line in open("misc.xml").readlines():
      env_at_project_creation = re.findall("\~/(.*)\" project-jdk", line.strip())
      if env_at_project_creation:
        print env_at_project_creation[0] + "/bin/activate"
        break
finally:
  pass
')

if [ "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; fi

Thanks Chris, your script worked for some projects but not all on my machine. Here is a script that I wrote and I hope anyone finds it useful.

#Stored in ~/.pycharmrc 

ACTIVATERC=$(python -c 'import re
import os
from glob import glob

try:
  #sets Current Working Directory to _the_projects .idea folder
  os.chdir(os.getcwd()+"/.idea") 

  #gets every file in the cwd and sets _the_projects iml file
  for file in glob("*"): 
    if re.match("(.*).iml", file):
      project_iml_file = file

  #gets _the_virtual_env for _the_project
  for line in open(project_iml_file):
    env_name = re.findall("~/(.*)\" jdkType", line.strip())
    # created or changed a virtual_env after project creation? this will be true
    if env_name:
      print env_name[0] + "/bin/activate"
      break

    inherited = re.findall("type=\"inheritedJdk\"", line.strip())
    # set a virtual_env during project creation? this will be true
    if inherited:
      break

  # find _the_virtual_env in misc.xml
  if inherited:
    for line in open("misc.xml").readlines():
      env_at_project_creation = re.findall("\~/(.*)\" project-jdk", line.strip())
      if env_at_project_creation:
        print env_at_project_creation[0] + "/bin/activate"
        break
finally:
  pass
')

if [ "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; fi

回答 6

我已经查看了上面所有的答案,但是没有一个对我来说足够优雅。在Pycharm 2017.1.3(在我的计算机中)中,最简单的方法是打开Settings->Tools->Terminal并检查Shell integrationActivate virtualenv选项。

I have viewed all of the answers above but none of them is elegant enough for me. In Pycharm 2017.1.3(in my computer), the easiest way is to open Settings->Tools->Terminal and check Shell integration and Activate virtualenv options.


回答 7

如果您使用的是Windows版本,则非常简单。如果您已经拥有虚拟环境,则只需导航至其文件夹,然后在文件夹activate.bat内找到即可Scripts。复制它的完整路径,并将其粘贴到pycharm的终端中,然后按Enter完成。

如果您需要创建新的虚拟环境:

转到“文件”>“设置”,然后搜索project interpreter,打开,单击齿轮按钮并在所需的位置创建环境,然后按照第一段进行操作。

If You are using windows version it is quite easy. If you already have the virtual environment just navigate to its folder, find activate.bat inside Scripts folder. copy it’s full path and paste it in pycharm’s terminal then press Enter and you’re done!

If you need to create new virtual environment :

Go to files > settings then search for project interpreter, open it, click on gear button and create the environment wherever you want and then follow first paragraph.


回答 8

在Mac上,它是PyCharm => Preferences … => Tools => Terminal => Activate virtualenv,默认情况下应启用。

On Mac it’s PyCharm => Preferences… => Tools => Terminal => Activate virtualenv, which should be enabled by default.


回答 9

我刚刚在主目录中添加了一个名为pycharmactivate的脚本。设置PyCharm(4.0.1)文件>设置>工具>终端> / bin / bash –rcfile〜/ pycharmactivate的Shell路径的值。如果您有不同的项目和virtualenv目录/名称,也许不是最好的解决方案,但是它对我有用。该脚本包含以下3行,并假定您的virtualenv与项目目录具有相同的名称。

source ~/.bashrc
projectdir=${PWD##*/}
source ~/.virtualenvs/$projectdir/bin/activate

I just added a script named pycharmactivate to my home directory. Set value of PyCharm (4.0.1) File > Settings > Tools > Terminal > Shell path to /bin/bash –rcfile ~/pycharmactivate. Maybe not the best solution incase you have different project and virtualenv directories/names but it works for me. This script contains the following 3 lines and assumes your virtualenv has the same name as your project dir.

source ~/.bashrc
projectdir=${PWD##*/}
source ~/.virtualenvs/$projectdir/bin/activate

回答 10

跟进Peter的回答,这里是.pycharmrc文件的Mac版本:

source /etc/profile
source ~/.bash_profile
source  <venv_dir>/bin/activate

母鸡

Following up on Peter’s answer, here the Mac version of the .pycharmrc file:

source /etc/profile
source ~/.bash_profile
source  <venv_dir>/bin/activate

Hen


回答 11

我有一个可以在Windows 7计算机上使用的解决方案。

我相信PyCharm的终端是它运行的结果,它将cmd.exe加载Windows PATH变量,并使用在其中首先找到的Python版本PATH。要编辑此变量,请右键单击我的电脑 -> 属性 -> 高级系统设置 -> 高级选项卡-> 环境变量…按钮。在“ 系统变量”部分中,选择并编辑PATH变量。

这是我编辑PATH 之前的相关部分:

C:\ Python27 \;
C:\ Python27 \ Lib \ site-packages \ pip \;
C:\ Python27 \ Scripts;
C:\ Python27 \ Lib \ site-packages \ django \ bin;

…并且编辑PATH(现在仅3行):

C:[project_path] \ virtualenv-Py2.7_Dj1.7 \ Lib \ site-packages \ pip;
C:[project_path] \ virtualenvs \ virtualenv-Py2.7_Dj1.7 \ Scripts;
C:[project_path] \ virtualenvs \ virtualenv-Py2.7_Dj1.7 \ Lib \ site-packages \ django \ bin;

要测试这一点,请打开一个新的 Windows终端(开始 ->键入cmd并点击Enter),看看它是否正在使用您的虚拟环境。如果可行,请重新启动PyCharm,然后在PyCharm的终端中对其进行测试。

I have a solution that worked on my Windows 7 machine.

I believe PyCharm’s terminal is a result of it running cmd.exe, which will load the Windows PATH variable, and use the version of Python that it finds first within that PATH. To edit this variable, right click My Computer –> Properties –> Advanced System Settings –> Advanced tab –> Environment Variables… button. Within the System variables section, select and edit the PATH variable.

Here is the relevant part of my PATH before editing:

C:\Python27\;
C:\Python27\Lib\site-packages\pip\;
C:\Python27\Scripts;
C:\Python27\Lib\site-packages\django\bin;

…and after editing PATH (only 3 lines now):

C:[project_path]\virtualenv-Py2.7_Dj1.7\Lib\site-packages\pip;
C:[project_path]\virtualenvs\virtualenv-Py2.7_Dj1.7\Scripts;
C:[project_path]\virtualenvs\virtualenv-Py2.7_Dj1.7\Lib\site-packages\django\bin;

To test this, open a new windows terminal (Start –> type in cmd and hit Enter) and see if it’s using your virtual environment. If that works, restart PyCharm and then test it out in PyCharm’s terminal.


回答 12

这就是我在做什么:在源代码文件夹中创建一个activate_env.bat(在Linux中为Windows,也许是.sh)文件:

/env_yourenvlocate/scripts/activate.bat

和另一个文件deactivate_env.bat:

/env_yourenvlocate/scripts/deactivate.bat

每次打开终端窗口时,只需执行bat文件来激活/停用virtualenv,您将停留在源代码路径中,而无需更改路径。

E:\Projects\django_study\src>active_env.bat

E:\Projects\django_study\src>../env_django_study/scripts/activate.bat
(env_django_study) E:\Projects\django_study\src>



(env_django_study) E:\Projects\django_study\src>deactive_env.bat

(env_django_study)E:\Projects\django_study\src>../env_django_study/scripts/deactivate.bat
E:\Projects\django_study\src>

this is what i am doing: create a activate_env.bat(windows,maybe .sh in linux) file in the source code folde:

/env_yourenvlocate/scripts/activate.bat

and another file deactivate_env.bat:

/env_yourenvlocate/scripts/deactivate.bat

everytime open the terminal window, just execute the bat file to activate/deactivate the virtualenv, you will stay in source code path, no need to change path to and back.

E:\Projects\django_study\src>active_env.bat

E:\Projects\django_study\src>../env_django_study/scripts/activate.bat
(env_django_study) E:\Projects\django_study\src>



(env_django_study) E:\Projects\django_study\src>deactive_env.bat

(env_django_study)E:\Projects\django_study\src>../env_django_study/scripts/deactivate.bat
E:\Projects\django_study\src>

回答 13

如果您的Pycharm 2016.1.4v及更高版本应使用 "default path" /K "<path-to-your-activate.bat>" 不要忘记引号

If your Pycharm 2016.1.4v and higher you should use "default path" /K "<path-to-your-activate.bat>" don’t forget quotes


回答 14

如果您已将项目移动到另一个目录,则可以通过“设置”对话框设置新路径。然后,您需要在“编辑配置”对话框中设置此项目解释器。

If you have moved your project to another directory, you can set the new path via Settings dialog. And then you need to set this Project Interpreter in the Edit Configuration dialog.


回答 15

另一种选择是使用virtualenvwrapper来管理您的虚拟环境。看来,一旦virtualenvwrapper 脚本被激活,pycharm就可以使用它,然后workon从pycharm控制台可以使用简单的命令,并为您提供可用的虚拟环境:

kevin@debian:~/Development/django-tutorial$ workon
django-tutorial
FlaskHF
SQLAlchemy
themarkdownapp
kevin@debian:~/Development/django-tutorial$ workon django-tutorial
(django-tutorial)kevin@debian:~/Development/django-tutorial$ 

Another alternative is to use virtualenvwrapper to manage your virtual environments. It appears that once the virtualenvwrapper script is activated, pycharm can use that and then the simple workon command will be available from the pycharm console and present you with the available virtual environments:

kevin@debian:~/Development/django-tutorial$ workon
django-tutorial
FlaskHF
SQLAlchemy
themarkdownapp
kevin@debian:~/Development/django-tutorial$ workon django-tutorial
(django-tutorial)kevin@debian:~/Development/django-tutorial$ 

回答 16

该方法应该在每个项目的任意虚拟环境下都可以使用,并且由于使用创建的钩子,因此不会对您的环境做任何假设。

你写:

  • 调用钩子的全局脚本
  • 每个PyCharm项目的挂钩脚本(不是必需的)

鉴于当前最新的PyCharm(社区2016.1)不允许每个项目的终端设置都调用项目特定挂钩的脚本开头。这是我的~/.pycharmrc

if [ -r ".pycharm/term-activate" ]; then
   echo "Terminal activation hook detected."
   echo "Loading Bash profile..."
   source ~/.bash_profile
   echo "Activating terminal hook..."
   source ".pycharm/term-activate"
   source activate $PYCHARM_VENV
fi

如果您使用的不是Bash,.bash_profile则应调用自己的等效项。

现在,将PyCharm设置为“工具->终端->外壳路径”以调用此脚本,例如: /bin/bash --rcfile ~/.pycharmrc

最后,对于每个PyCharm项目,您都需要激活特定的虚拟环境,请在PyCharm项目root内创建一个文件.pycharm/term-activate。这是您的钩子,它将仅为您的PyCharm项目定义所需的虚拟环境的名称:

export PYCHARM_VENV=<your-virtual-env-name>

当然,您可以使用在您的特定PyCharm项目的终端环境中发现有用的任何东西来扩展自己的功能。

This method should work with arbitrary virtual environments per project and it doesn’t make assumptions on your environment as it is using hooks you create.

You write:

  • A global script that invokes the hook
  • A hook script per PyCharm project (not mandatory)

Given that the current latest PyCharm (Community 2016.1) does not allow for Terminal settings per project start with the script that invokes the project specific hook. This is my ~/.pycharmrc:

if [ -r ".pycharm/term-activate" ]; then
   echo "Terminal activation hook detected."
   echo "Loading Bash profile..."
   source ~/.bash_profile
   echo "Activating terminal hook..."
   source ".pycharm/term-activate"
   source activate $PYCHARM_VENV
fi

If you are using something other than Bash, invoke your own .bash_profile equivalent should you wish to.

Now set your PyCharm “Tools -> Terminal -> Shell Path” to invoke this script, e.g.: /bin/bash --rcfile ~/.pycharmrc

Finally, for every PyCharm project you need a specific virtual environment activated, create a file within the PyCharm project root .pycharm/term-activate. This is your hook and it will simply define the name of the desired virtual environment for your PyCharm project:

export PYCHARM_VENV=<your-virtual-env-name>

You can of course extend your hooks with anything you find useful in the terminal environment of your particular PyCharm project.


回答 17

对于Windows上的conda虚拟环境,请确保未命名您的批处理文件,activate.bat因为这将导致与conda activate命令冲突,从而导致对该批处理文件的递归调用。

下面的Shell路径对我有用:

"cmd.exe" /k ""C:\FullPathToYourProject\activate-env.bat""

并在activate-env.bat文件中:

call activate myenvname

For conda virtual environments on Windows, make sure your batch file is NOT named activate.bat as this will cause a conflict with the conda activate command, resulting in a recursive calling of the batch file.

What works for me is the following Shell path:

"cmd.exe" /k ""C:\FullPathToYourProject\activate-env.bat""

And in the activate-env.bat file:

call activate myenvname

回答 18

我希望为每个项目提供一个单独的虚拟环境,并且不太在乎是否需要其他文件来简化此工作。您只需执行一次即可用于所有项目的解决方案,然后将以下内容添加到您的.bashrc或中.bash_profile

if [ -d "./venv" ]; then
    source ./venv/bin/activate
fi

这将检查是否存在打开终端的虚拟环境,是否激活了终端(当然可以使用其他相对路径)。PyCharm的终端设置可以保留为默认设置。

I wanted a separate virtual environment for each project, and didn’t care much for having additional files to facilitate this. A solution which you only need to do once and works for all projects is then adding the following to your .bashrc or .bash_profile:

if [ -d "./venv" ]; then
    source ./venv/bin/activate
fi

This checks if there is a virtual environment where the terminal is being opened, and if so activates it (and of course other relative paths could be used). PyCharm’s terminal settings can be left as their default.


回答 19

PyCharm 4.5.4

使用以下内容在主文件夹中创建文件.pycharmrc

source ~/.bashrc
source ~/pycharmvenv/bin/activate

使用您的virtualenv路径作为最后一个参数。

然后将Shell Preferences-> Project Settings-> Shell path设置为

/bin/bash --rcfile ~/.pycharmrc

我不知道为什么,但这对我不起作用。PyCharm打印错误。

cmd.exe /K "<path-to-your-activate.bat>" 它可以工作,但是即使没有必要,它也会为每个项目创建相同的virtualenv。

收据有效!但是字符串/env_yourenvlocate/scripts/activate.bat必须包含引号,像这样"Full_path_to_your_env_locate\scripts\activate.bat"

禁用virtualenv非常容易-在终端中输入’deactivate’

(virt_env) D:\Projects\src>deactivate
D:\Projects\src>

PyCharm 4.5.4

Create a file .pycharmrc in your home folder with the following contents

source ~/.bashrc
source ~/pycharmvenv/bin/activate

Using your virtualenv path as the last parameter.

Then set the shell Preferences->Project Settings->Shell path to

/bin/bash --rcfile ~/.pycharmrc

I don’t why, but it doesn’t work for me. PyCharm prints an error.

cmd.exe /K "<path-to-your-activate.bat>" It works, but it creates the same virtualenv for each project, and even if this is not necessary.

This receipt is working! But the string /env_yourenvlocate/scripts/activate.bat must contain quotes, like this "Full_path_to_your_env_locate\scripts\activate.bat"!

Deactivate the virtualenv is very easy – type in the terminal ‘deactivate’

(virt_env) D:\Projects\src>deactivate
D:\Projects\src>

回答 20

WSL解决方案(Windows上的Ubuntu)

如果您使用的是WSL(在Windows上为Ubuntu),则还可以在pycharm中将bash作为终端打开,并激活linux virtualenv。

使用.pycharmrc类似于Peter Gibson答案中所述的文件;将.pycharmrc文件添加到您的主目录,其中包含以下内容:

source ~/.bashrc
source ~/path_to_virtualenv/bin/activate

在Pycharm 文件>设置>工具>终端中,添加以下“外壳路径”:

"C:/Windows/system32/bash.exe" -c "bash --rcfile ~/.pycharmrc"


项目特定的virtualenv

您的virtualenv的路径.pycharmrc不必是绝对的。您可以通过在项目目录中设置相对路径来设置特定于项目的virtualenv。我的virtualenv始终位于项目目录下的“ venv”文件夹中,因此.pycharmrc文件如下所示:

来源〜/ .bashrc
源〜/ pycharmvenv / bin / activate#绝对路径
源./venv/bin/activate#相对路径


奖励:自动打开ssh隧道以将virtualenv连接为项目解释器

将以下内容添加到您的.pycharmrc文件中:

if [ $(ps -aux | grep -c 'ssh') -lt 2 ]; then
    sudo service ssh start 
fi

这将检查ssh隧道是否已经打开,否则打开一个。在 Pycharm的“文件”->“设置”->“项目”->“项目解释器”中,添加具有以下配置的新远程解释器:

+ -------------------------- + ---------------------- ----------- + ------- + ---- +
| 名称:<口译员名称> | | |
| 选择| “ SSH凭证” | | |
| 主持人:127.0.0.1 | 端口:| 22 |
| 用户:| <Linux用户名> | | |
| 验证类型:| “密码” | | |
| 密码:<Linux密码> | | |
| Python解释器路径:<Linux到您的virtualenv的路径> | | |
| Python帮助程序路径:| <自动设置> | | |
+ -------------------------- + ---------------------- ----------- + ------- + ---- +

现在,当您打开项目时,bash会自动在virtualenv中启动,打开ssh隧道,并且pycharm将virtualenv连接为远程解释器。

警告:Windows中的最新更新将在启动时自动启动SshBroker和SshProxy服务。这些阻止了从Linux到Windows的ssh隧道。您可以在“任务管理器”->“服务”中停止这些服务,然后所有内容将再次运行。

Solution for WSL (Ubuntu on Windows)

If you’re using WSL (Ubuntu on Windows), you can also open bash as terminal in pycharm and activate a linux virtualenv.

Use a .pycharmrc file like described in Peter Gibson’s answer; Add the .pycharmrc file to your home directory with following content:

source ~/.bashrc
source ~/path_to_virtualenv/bin/activate

In Pycharm File > Settings > Tools > Terminal add the following ‘Shell path’:

"C:/Windows/system32/bash.exe" -c "bash --rcfile ~/.pycharmrc"


Project specific virtualenv

The path to your virtualenv in .pycharmrc does not have to be absolute. You can set a project specific virtualenv by setting a relative path from your project directory. My virtualenv is always located in a ‘venv’ folder under my project directory, so my .pycharmrc file looks like this:

source ~/.bashrc
source ~/pycharmvenv/bin/activate #absolute path
source ./venv/bin/activate #relative path


BONUS: automatically open ssh tunnel to connect virtualenv as project interpreter

Add the following to your .pycharmrc file:

if [ $(ps -aux | grep -c 'ssh') -lt 2 ]; then
    sudo service ssh start 
fi

This checks if a ssh tunnel is already opened, and opens one otherwise. In File -> Settings -> Project -> Project Interpreter in Pycharm, add a new remote interpreter with following configuration:

+--------------------------+---------------------------------+-------+----+
| Name:                    | <Interpreter name>              |       |    |
| Select                   | 'SSH Credentials'               |       |    |
| Host:                    | 127.0.0.1                       | Port: | 22 |
| User:                    | <Linux username>                |       |    |
| Auth type:               | 'Password'                      |       |    |
| Password:                | <Linux password>                |       |    |
| Python interpreter path: | <Linux path to your virtualenv> |       |    |
| Python helpers path:     | <Set automatically>             |       |    |
+--------------------------+---------------------------------+-------+----+

Now when you open your project, your bash automatically starts in your virtualenv, opens a ssh tunnel, and pycharm connects the virtualenv as remote interpreter.

warning: the last update in Windows automatically starts a SshBroker and SshProxy service on startup. These block the ssh tunnel from linux to windows. You can stop these services in Task Manager -> Services, after which everything will work again.


回答 21

输入终端>运行>调试>编辑配置时,您有一个选择

选择合适的conda环境。。同样,在创建新项目时-它要求配置该位置。

One option you have when you enter the terminal > Run > Debug > Edit Configurations

select the appropriate conda environmnent.. Also when you create a new project – it asks to configure this location.


没有循环导入的Python类型提示

问题:没有循环导入的Python类型提示

我正试图将我的大班分成两部分;好吧,基本上是进入“主”类和具有其他功能的mixin的,就像这样:

main.py 文件:

import mymixin.py

class Main(object, MyMixin):
    def func1(self, xxx):
        ...

mymixin.py 文件:

class MyMixin(object):
    def func2(self: Main, xxx):  # <--- note the type hint
        ...

现在,尽管这很好用,但是类型提示MyMixin.func2当然不起作用。我无法导入main.py,因为会进行周期性导入,并且没有提示,我的编辑器(PyCharm)无法分辨出什么self

我使用的是Python 3.4,如果在那里有解决方案,我愿意移至3.5。

有什么办法可以将我的Class分成两个文件并保留所有“连接”,以便我的IDE仍然可以自动完成以及知道类型的所有其他优点。

I’m trying to split my huge class into two; well, basically into the “main” class and a mixin with additional functions, like so:

main.py file:

import mymixin.py

class Main(object, MyMixin):
    def func1(self, xxx):
        ...

mymixin.py file:

class MyMixin(object):
    def func2(self: Main, xxx):  # <--- note the type hint
        ...

Now, while this works just fine, the type hint in MyMixin.func2 of course can’t work. I can’t import main.py, because I’d get a cyclic import and without the hint, my editor (PyCharm) can’t tell what self is.

I’m using Python 3.4, willing to move to 3.5 if a solution is available there.

Is there any way I can split my class into two files and keep all the “connections” so that my IDE still offers me auto completion & all the other goodies that come from it knowing the types?


回答 0

恐怕通常没有一种非常优雅的方式来处理导入周期。您的选择是重新设计代码以消除循环依赖性,或者如果不可行,请执行以下操作:

# some_file.py

from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from main import Main

class MyObject(object):
    def func2(self, some_param: 'Main'):
        ...

TYPE_CHECKING常量始终False在运行时运行,因此不会评估导入,但是mypy(和其他类型检查工具)将评估该块的内容。

我们还需要将Main类型注释放入字符串中,以有效地向前声明它,因为该Main符号在运行时不可用。

如果您使用的是Python 3.7+,我们至少可以通过利用PEP 563来跳过必须提供显式字符串注释的情况:

# some_file.py

from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from main import Main

class MyObject(object):
    # Hooray, cleaner annotations!
    def func2(self, some_param: Main):
        ...

from __future__ import annotations进口将使所有类型提示弦而跳过评估他们。这可以使我们的代码更符合人体工程学。

综上所述,与mypy一起使用mixins可能需要比您现在拥有的结构更多的结构。Mypy 建议一种基本上就是deceze所描述的方法-创建一个ABC,您的类MainMyMixin类都继承。如果您最终需要做一些类似的事情以使Pycharm的检查器满意,我不会感到惊讶。

There isn’t a hugely elegant way to handle import cycles in general, I’m afraid. Your choices are to either redesign your code to remove the cyclic dependency, or if it isn’t feasible, do something like this:

# some_file.py

from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from main import Main

class MyObject(object):
    def func2(self, some_param: 'Main'):
        ...

The TYPE_CHECKING constant is always False at runtime, so the import won’t be evaluated, but mypy (and other type-checking tools) will evaluate the contents of that block.

We also need to make the Main type annotation into a string, effectively forward declaring it since the Main symbol isn’t available at runtime.

If you are using Python 3.7+, we can at least skip having to provide an explicit string annotation by taking advantage of PEP 563:

# some_file.py

from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from main import Main

class MyObject(object):
    # Hooray, cleaner annotations!
    def func2(self, some_param: Main):
        ...

The from __future__ import annotations import will make all type hints be strings and skip evaluating them. This can help make our code here mildly more ergonomic.

All that said, using mixins with mypy will likely require a bit more structure then you currently have. Mypy recommends an approach that’s basically what deceze is describing — to create an ABC that both your Main and MyMixin classes inherit. I wouldn’t be surprised if you ended up needing to do something similar in order to make Pycharm’s checker happy.


回答 1

对于仅在导入类以进行类型检查时陷入困境的人们:您可能希望使用前向引用(PEP 484-类型提示):

当类型提示包含尚未定义的名称时,该定义可以表示为字符串文字,以便稍后解析。

所以代替:

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

你做:

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

For people struggling with cyclic imports when importing class only for Type checking: you will likely want to use a Forward Reference (PEP 484 – Type Hints):

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

So instead of:

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

you do:

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

回答 2

更大的问题是,您的类型一开始并不理智。MyMixin进行硬编码的假设是将其混合到中Main,而可以将其混合到任何其他数量的类中,在这种情况下,它可能会损坏。如果将mixin硬编码为混合到一个特定的类中,则不妨将方法直接写入该类中,而不用将它们分开。

要使用合理的输入方式正确执行此操作,MyMixin应使用Python的说法对interface或abstract class 进行编码:

import abc


class MixinDependencyInterface(abc.ABC):
    @abc.abstractmethod
    def foo(self):
        pass


class MyMixin:
    def func2(self: MixinDependencyInterface, xxx):
        self.foo()  # ← mixin only depends on the interface


class Main(MixinDependencyInterface, MyMixin):
    def foo(self):
        print('bar')

The bigger issue is that your types aren’t sane to begin with. MyMixin makes a hardcoded assumption that it will be mixed into Main, whereas it could be mixed into any number of other classes, in which case it would probably break. If your mixin is hardcoded to be mixed into one specific class, you may as well write the methods directly into that class instead of separating them out.

To properly do this with sane typing, MyMixin should be coded against an interface, or abstract class in Python parlance:

import abc


class MixinDependencyInterface(abc.ABC):
    @abc.abstractmethod
    def foo(self):
        pass


class MyMixin:
    def func2(self: MixinDependencyInterface, xxx):
        self.foo()  # ← mixin only depends on the interface


class Main(MixinDependencyInterface, MyMixin):
    def foo(self):
        print('bar')

回答 3

事实证明,我最初的尝试也非常接近解决方案。这是我目前正在使用的:

# main.py
import mymixin.py

class Main(object, MyMixin):
    def func1(self, xxx):
        ...


# mymixin.py
if False:
    from main import Main

class MyMixin(object):
    def func2(self: 'Main', xxx):  # <--- note the type hint
        ...

请注意,import inside if False语句永远不会被导入(但IDE仍然知道它),并且将该Main类用作字符串,因为在运行时不知道。

Turns out my original attempt was quite close to the solution as well. This is what I’m currently using:

# main.py
import mymixin.py

class Main(object, MyMixin):
    def func1(self, xxx):
        ...


# mymixin.py
if False:
    from main import Main

class MyMixin(object):
    def func2(self: 'Main', xxx):  # <--- note the type hint
        ...

Note the import within if False statement that never gets imported (but IDE knows about it anyway) and using the Main class as string because it’s not known at runtime.


回答 4

我认为,完美的方法应该是将所有类和依赖项导入文件(如__init__.py),然后再导入所有from __init__ import *其他文件。

在这种情况下

  1. 避免对这些文件和类的多次引用,并且
  2. 也只需在其他每个文件中添加一行
  3. 第三个是知道您可能使用的所有类的pycharm。

I think the perfect way should be to import all the classes and dependencies in a file (like __init__.py) and then from __init__ import * in all the other files.

In this case you are

  1. avoiding multiple references to those files and classes and
  2. also only have to add one line in each of the other files and
  3. the third would be the pycharm knowing about all of the classes that you might use.

皮查姆不显示情节

问题:皮查姆不显示情节

Pycharm不显示以下代码中的图:

import pandas as pd
import numpy as np
import matplotlib as plt

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))

ts = ts.cumsum()    
ts.plot()

发生的是,一个窗口出现了不到一秒钟,然后又消失了。

在图表显示的相同代码上使用Pyzo IEP IDE(使用相同的解释程序)。

…所以问题一定出在Pycharm上。我试过使用python.exe和pythonw.exe作为解释器,两者的结果相同。

这是我的sys_info:

C:\pyzo2014a\pythonw.exe -u C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pydev\pydevconsole.py 57315 57316
PyDev console: using IPython 2.1.0import sys; print('Python %s on %s' % (sys.version, sys.platform))
Python 3.4.1 |Continuum Analytics, Inc.| (default, May 19 2014, 13:02:30) [MSC v.1600 64 bit (AMD64)] on win32
sys.path.extend(['C:\\Users\\Rasmus\\PycharmProjects\\untitled2'])
In[3]: import IPython
print(IPython.sys_info())
{'commit_hash': '681fd77',
 'commit_source': 'installation',
 'default_encoding': 'UTF-8',
 'ipython_path': 'C:\\pyzo2014a\\lib\\site-packages\\IPython',
 'ipython_version': '2.1.0',
 'os_name': 'nt',
 'platform': 'Windows-8-6.2.9200',
 'sys_executable': 'C:\\pyzo2014a\\pythonw.exe',
 'sys_platform': 'win32',
 'sys_version': '3.4.1 |Continuum Analytics, Inc.| (default, May 19 2014, '
                '13:02:30) [MSC v.1600 64 bit (AMD64)]'}

Pycharm does not show plot from the following code:

import pandas as pd
import numpy as np
import matplotlib as plt

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))

ts = ts.cumsum()    
ts.plot()

What happens is that a window appears for less than a second, and then disappears again.

Using the Pyzo IEP IDE (using same interpreter) on the same code the plot shows as expected.

…So the problem must be with some setting on Pycharm. I’ve tried using both python.exe and pythonw.exe as interpreter both with same results.

This is my sys_info:

C:\pyzo2014a\pythonw.exe -u C:\Program Files (x86)\JetBrains\PyCharm Community Edition 3.4.1\helpers\pydev\pydevconsole.py 57315 57316
PyDev console: using IPython 2.1.0import sys; print('Python %s on %s' % (sys.version, sys.platform))
Python 3.4.1 |Continuum Analytics, Inc.| (default, May 19 2014, 13:02:30) [MSC v.1600 64 bit (AMD64)] on win32
sys.path.extend(['C:\\Users\\Rasmus\\PycharmProjects\\untitled2'])
In[3]: import IPython
print(IPython.sys_info())
{'commit_hash': '681fd77',
 'commit_source': 'installation',
 'default_encoding': 'UTF-8',
 'ipython_path': 'C:\\pyzo2014a\\lib\\site-packages\\IPython',
 'ipython_version': '2.1.0',
 'os_name': 'nt',
 'platform': 'Windows-8-6.2.9200',
 'sys_executable': 'C:\\pyzo2014a\\pythonw.exe',
 'sys_platform': 'win32',
 'sys_version': '3.4.1 |Continuum Analytics, Inc.| (default, May 19 2014, '
                '13:02:30) [MSC v.1600 64 bit (AMD64)]'}

回答 0

只需使用

plt.show()

此命令告诉系统在Pycharm中绘制图。

例:

plt.imshow(img.reshape((28, 28)))
plt.show()

Just use

plt.show()

This command tells the system to draw the plot in Pycharm.

Example:

plt.imshow(img.reshape((28, 28)))
plt.show()

回答 1

我意识到这很古老,但我想我会为其他旅客消除误解。设置plt.pyplot.isinteractive()False意味着将在特定绘制命令(即plt.pyplot.show())上绘制该图。设置plt.pyplot.isinteractive()True意味着每个pyplotplt)命令将触发绘制命令(即plt.pyplot.show())。因此,您最有可能要寻找的是plt.pyplot.show()在程序结尾处显示图形。

另外,您可以使用以下import命令(import matplotlib.pyplot as plt而不是)来缩短这些语句matplotlib as plt

I realize this is old but I figured I’d clear up a misconception for other travelers. Setting plt.pyplot.isinteractive() to False means that the plot will on be drawn on specific commands to draw (i.e. plt.pyplot.show()). Setting plt.pyplot.isinteractive() to True means that every pyplot (plt) command will trigger a draw command (i.e. plt.pyplot.show()). So what you were more than likely looking for is plt.pyplot.show() at the end of your program to display the graph.

As a side note you can shorten these statements a bit by using the following import command import matplotlib.pyplot as plt rather than matplotlib as plt.


回答 2

我有同样的问题。检查是否plt.isinteractive()为真。将其设置为“ False”对我有所帮助。

plt.interactive(False)

I had the same problem. Check wether plt.isinteractive() is True. Setting it to ‘False’ helped for me.

plt.interactive(False)

回答 3

我尝试了不同的解决方案,但最终对我有用的是plt.show(block=True)。您需要在命令之后添加此命令,此myDataFrame.plot()命令才能生效。如果您有多个绘图,只需在代码末尾添加命令。它将允许您查看正在绘制的每个数据。

I tried different solutions but what finally worked for me was plt.show(block=True). You need to add this command after the myDataFrame.plot() command for this to take effect. If you have multiple plot just add the command at the end of your code. It will allow you to see every data you are plotting.


回答 4

import matplotlib
matplotlib.use('TkAgg')

为我工作。(PyCharm / OSX)

import matplotlib
matplotlib.use('TkAgg')

Works for me. (PyCharm/OSX)


回答 5

我在Pycharm版本(社区版2017.2.2)中进行了测试,您可能需要同时声明plt.interactive(False)和plt.show(block = True),如下所示:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 6.28, 100)

plt.plot(x, x**0.5, label='square root')
plt.plot(x, np.sin(x), label='sinc')

plt.xlabel('x label')
plt.ylabel('y label')

plt.title("test plot")

plt.legend()

plt.show(block=True)
plt.interactive(False)

I test in my version of Pycharm (Community Edition 2017.2.2), you may need to announce both plt.interactive(False) and plt.show(block=True) as following:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 6.28, 100)

plt.plot(x, x**0.5, label='square root')
plt.plot(x, np.sin(x), label='sinc')

plt.xlabel('x label')
plt.ylabel('y label')

plt.title("test plot")

plt.legend()

plt.show(block=True)
plt.interactive(False)

回答 6

我找到了解决方案。这对我有用:

import numpy as np
import matplotlib.pyplot as plt

points = np.arange(-5, 5, 0.01)
dx, dy = np.meshgrid(points, points)
z = (np.sin(dx)+np.sin(dy))
plt.imshow(z)
plt.colorbar()
plt.title('plot for sin(x)+sin(y)')
plt.show()

I have found a solution. This worked for me:

import numpy as np
import matplotlib.pyplot as plt

points = np.arange(-5, 5, 0.01)
dx, dy = np.meshgrid(points, points)
z = (np.sin(dx)+np.sin(dy))
plt.imshow(z)
plt.colorbar()
plt.title('plot for sin(x)+sin(y)')
plt.show()

回答 7

调用后不久

plt.imshow() 

呼叫

plt.show(block = True)

您将获得带有图像的matplotlib弹出窗口。

这是一种阻止方式。在弹出窗口关闭之前,其他脚本将无法运行。

Soon after calling

plt.imshow() 

call

plt.show(block = True)

You will get the matplotlib popup with the image.

This is a blocking way. Further script will not run until the pop is closed.


回答 8

对于我来说,问题是matplotlib使用了错误的后端。我正在使用Debian Jessie。

在控制台中,我执行了以下操作:

import matplotlib
matplotlib.get_backend()

结果是:“ agg”,而应该是“ TkAgg”。

解决方案很简单:

  1. 通过pip卸载matplotlib
  2. 安装适当的库:sudo apt-get install tcl-dev tk-dev python-tk python3-tk
  3. 再次通过pip安装matplotlib。

With me the problem was the fact that matplotlib was using the wrong backend. I am using Debian Jessie.

In a console I did the following:

import matplotlib
matplotlib.get_backend()

The result was: ‘agg’, while this should be ‘TkAgg’.

The solution was simple:

  1. Uninstall matplotlib via pip
  2. Install the appropriate libraries: sudo apt-get install tcl-dev tk-dev python-tk python3-tk
  3. Install matplotlib via pip again.

回答 9

只需添加 plt.pyplot.show(),就可以了。

最好的解决方案是禁用SciView。

Just add plt.pyplot.show(), that would be fine.

The best solution is disabling SciView.


回答 10

我在PyCharm 2017.1.2上的版本中进行了测试。我使用交互式(True)和显示(block = True)。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1//2000',periods=1000))
ts = ts.cumsum()
plt.interactive(True)
ts.plot()
plt.show(block=True)

I tested in my version on PyCharm 2017.1.2. I used interactive (True) and show (block=True).

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1//2000',periods=1000))
ts = ts.cumsum()
plt.interactive(True)
ts.plot()
plt.show(block=True)

回答 11

以上都不对我有用,但以下内容对我有用:

  1. 禁用pycharm中的复选框(在工具窗口中显示图)settings > Tools > Python Scientific

  2. 我收到了错误消息No PyQt5 module found。继续使用以下内容的安装PyQt5

    sudo apt-get install python3-pyqt5

请注意,仅第一步就足够了并且可以工作。

None of the above worked for me but the following did:

  1. Disable the checkbox (Show plots in tool window) in pycharm settings > Tools > Python Scientific.

  2. I received the error No PyQt5 module found. Went ahead with the installation of PyQt5 using :

    sudo apt-get install python3-pyqt5
    

Beware that for some only first step is enough and works.


回答 12

我的环境:macOS和anaconda3

这对我有用:

matplotlib.use('macosx')

或互动模式:

matplotlib.use('TkAgg')

My env: macOS & anaconda3

This works for me:

matplotlib.use('macosx')

or interactive mode:

matplotlib.use('TkAgg')

回答 13

我有这个问题,我可以解决,您可以测试一下自己的方法..从设置->工具-> python科学中禁用“在工具窗口中显示图”

i had this problem and i could solve it , you can test my way.. disable “show plots in tool window” from setting–>tools–>python scientific


回答 14

DanT的评论为我解决了这个问题,在带有GTKagg后端的linux上用pycharm修复了matplotlib。导入matplotlib时,我将得到以下错误:

>>> import matplotlib as mpl

Backend GTKAgg is interactive backend. Turning interactive mode on.
Failed to enable GUI event loop integration for 'gtk'

当绘制这样的东西时:

from matplotlib import pyplot as plt
plt.figure()
plt.plot(1,2)
plt.show()

将弹出一个图形屏幕,但没有图表出现。使用:

plt.show(block=True)

正确显示图形。

Comment from DanT fixed this for me, matplotlib with pycharm on linux with the GTKagg backend. Upon importing matplotlib I would get the following error:

>>> import matplotlib as mpl

Backend GTKAgg is interactive backend. Turning interactive mode on.
Failed to enable GUI event loop integration for 'gtk'

When plotting something like so:

from matplotlib import pyplot as plt
plt.figure()
plt.plot(1,2)
plt.show()

A figure screen would pop up but no charts appear. using:

plt.show(block=True)

displays the graphic correctly.


回答 15

就我而言,我想执行以下操作:

    plt.bar(range(len(predictors)), scores)
    plt.xticks(range(len(predictors)), predictors, rotation='vertical')
    plt.show()

在这里混合了各种解决方案之后,我的解决方案是在此之前添加以下命令:

    matplotlib.get_backend()
    plt.interactive(False)
    plt.figure()

以下两种进口

   import matplotlib
   import matplotlib.pyplot as plt

在我的情况下,似乎所有命令都是必需的,带有ElCapitan和PyCharm 2016.2.3的MBP。问候!

In my case, I wanted to do the following:

    plt.bar(range(len(predictors)), scores)
    plt.xticks(range(len(predictors)), predictors, rotation='vertical')
    plt.show()

Following a mix of the solutions here, my solution was to add before that the following commands:

    matplotlib.get_backend()
    plt.interactive(False)
    plt.figure()

with the following two imports

   import matplotlib
   import matplotlib.pyplot as plt

It seems that all the commands are necessary in my case, with a MBP with ElCapitan and PyCharm 2016.2.3. Greetings!


回答 16

对于初学者,您可能还需要确保正在控制台运行脚本,而不是常规Python代码。突出显示一段代码并运行它是很容易的。

For beginners, you might also want to make sure you are running your script in the console, and not as regular Python code. It is fairly easy to highlight a piece of code and run it.


回答 17

在非交互式环境中,我们必须使用plt.show(block = True)

In non-interactive env, we have to use plt.show(block=True)


回答 18

对于那些在IDE内运行脚本(并且不能在python控制台或笔记本之类的交互式环境中工作)的人,我发现这是最直观,最简单的解决方案:

plt.imshow(img)
plt.waitforbuttonpress()

它显示了该图,并一直等到用户单击新窗口。只有这样,它才能恢复脚本并运行其余代码。

For those who are running a script inside an IDE (and not working in an interactive environment such as a python console or a notebook), I found this to be the most intuitive and the simplest solution:

plt.imshow(img)
plt.waitforbuttonpress()

It shows the figure and waits until the user clicks on the new window. Only then it resume the script and run the rest of the code.


回答 19

我能够得到这里的一些其他建议为我工作的组合,但只有当拨动plt.interactive(False)True,然后再返回。

plt.interactive(True)
plt.pyplot.show()

这将刷新我的情节。然后设置为False允许查看。

plt.interactive(False)
plt.pyplot.show()

如前所述,在关闭所有窗口之前,我的程序也不会退出。以下是有关当前运行环境的一些详细信息:

Python version 2.7.6
Anaconda 1.9.2 (x86_64)
(default, Jan 10 2014, 11:23:15) 
[GCC 4.0.1 (Apple Inc. build 5493)]
Pandas version: 0.13.1

I was able to get a combination of some of the other suggestions here working for me, but only while toggling the plt.interactive(False) to True and back again.

plt.interactive(True)
plt.pyplot.show()

This will flash up the my plots. Then setting to False allowed for viewing.

plt.interactive(False)
plt.pyplot.show()

As noted also my program would not exit until all the windows were closed. Here are some details on my current run environment:

Python version 2.7.6
Anaconda 1.9.2 (x86_64)
(default, Jan 10 2014, 11:23:15) 
[GCC 4.0.1 (Apple Inc. build 5493)]
Pandas version: 0.13.1

回答 20

需要为pycharm设置一个属性。

import matplotlib.pyplot as plt

plt.interactive(False)  #need to set to False

dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)

plt.show()

One property need to set for pycharm.

import matplotlib.pyplot as plt

plt.interactive(False)  #need to set to False

dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)

plt.show()

回答 21

将导入更改为:

import matplotlib.pyplot as plt

或使用此行:

plt.pyplot.show()

Change import to:

import matplotlib.pyplot as plt

or use this line:

plt.pyplot.show()

回答 22

我正在使用Ubuntu,并且按上面的@Arie所述尝试过,但是仅在终端中使用以下行:

sudo apt-get install tcl-dev tk-dev python-tk python3-tk

而且有效!

I’m using Ubuntu and I tried as @Arie said above but with this line only in terminal:

sudo apt-get install tcl-dev tk-dev python-tk python3-tk

And it worked!


回答 23

在Pycharm中,有时Matplotlib.plot不会显示。

因此,调用后plt.show(),在右侧工具栏中检查SciView。在SciView内部,将存储每个生成的图。

In Pycharm , at times the Matplotlib.plot won’t show up.

So after calling plt.show() check in the right side toolbar for SciView. Inside SciView every generated plots will be stored.


回答 24

我在尝试绘制直方图时遇到上面的错误,而下面的点对我有用。

操作系统:Mac Catalina 10.15.5

Pycharm版本:社区版本2019.2.3

Python版本:3.7

  1. 我将导入语句更改如下(从-到)

来自:

import matplotlib.pylab as plt

至:

import matplotlib.pyplot as plt

  1. 和下面的绘图语句(将我的命令表pyplot更改为plt)

从:

plt.pyplot.hist(df["horsepower"])

# set x/y labels and plot title
plt.pyplot.xlabel("horsepower")
plt.pyplot.ylabel("count")
plt.pyplot.title("horsepower bins") 

至 :

plt.hist(df["horsepower"])

# set x/y labels and plot title
plt.xlabel("horsepower")
plt.ylabel("count")
plt.title("horsepower bins")
  1. 使用plt.show显示直方图

plt.show()

I was facing above error when i am trying to plot histogram and below points worked for me.

OS : Mac Catalina 10.15.5

Pycharm Version : Community version 2019.2.3

Python version : 3.7

  1. I changed import statement as below (from – to)

from :

import matplotlib.pylab as plt

to:

import matplotlib.pyplot as plt

  1. and plot statement to below (changed my command form pyplot to plt)

from:

plt.pyplot.hist(df["horsepower"])

# set x/y labels and plot title
plt.pyplot.xlabel("horsepower")
plt.pyplot.ylabel("count")
plt.pyplot.title("horsepower bins") 

to :

plt.hist(df["horsepower"])

# set x/y labels and plot title
plt.xlabel("horsepower")
plt.ylabel("count")
plt.title("horsepower bins")
  1. use plt.show to display histogram

plt.show()


如何在for循环中注释类型

问题:如何在for循环中注释类型

我想在for-loop中注释变量的类型。我尝试了这个:

for i: int in range(5):
    pass

但这显然没有用。

我期望在PyCharm 2016.3.2中能够自动完成工作。像这样的预注释:

i: int
for i in range(5):
    pass

没有帮助。

适用于PyCharm> = 2017.1的PS预注释作品

I want to annotate a type of a variable in a for-loop. I tried this:

for i: int in range(5):
    pass

But it didn’t work, obviously.

What I expect is working autocomplete in PyCharm 2016.3.2. Pre-annotation like this:

i: int
for i in range(5):
    pass

doesn’t help.

P.S. Pre-annotation works for PyCharm >= 2017.1


回答 0

根据PEP 526,这是不允许的:

另外,不能注释forwith 语句中使用的变量。可以像元组拆包一样提前注释它们

在循环之前对其进行注释:

i: int
for i in range(5):
    pass

PyCharm 2018.1及更高版本现在可以识别循环内变量的类型。较早的PyCharm版本不支持此功能。

According to PEP 526, this is not allowed:

In addition, one cannot annotate variables used in a for or with statement; they can be annotated ahead of time, in a similar manner to tuple unpacking

Annotate it before the loop:

i: int
for i in range(5):
    pass

PyCharm 2018.1 and up now recognizes the type of the variable inside the loop. This was not supported in older PyCharm versions.


回答 1

我不知道此解决方案是否与PEP兼容,或者仅仅是PyCharm的功能,但我使它像这样工作

for i in range(5): #type: int
  pass

我正在使用Pycharm Community Edition 2016.2.1

I don’t know if this solution is PEP compatible or just a feature of PyCharm but I made it work like this

for i in range(5): #type: int
  pass

and I’m using Pycharm Community Edition 2016.2.1


回答 2

这对我在PyCharm(使用Python 3.6)中的效果很好

for i in range(5):
    i: int = i
    pass

This works well for my in PyCharm (using Python 3.6)

for i in range(5):
    i: int = i
    pass

回答 3

这里的回答都没有用,只是说不能。甚至接受的答案也使用PEP 526文档中的语法,这不是有效的python语法。如果您尝试输入

x: int

您会看到这是一个语法错误。

这是一个有用的解决方法:

for __x in range(5):
    x = __x  # type: int
    print(x)

做您的工作x。PyCharm可以识别其类型,并且可以自动完成。

None of the responses here were useful, except to say that you can’t. Even the accepted answer uses syntax from the PEP 526 document, which isn’t valid python syntax. If you try to type in

x: int

You’ll see it’s a syntax error.

Here is a useful workaround:

for __x in range(5):
    x = __x  # type: int
    print(x)

Do your work with x. PyCharm recognizes its type, and autocomplete works.