标签归档:python-3.x

我应该在Python 3中使用编码声明吗?

问题:我应该在Python 3中使用编码声明吗?

默认情况下,Python 3对源代码文件使用UTF-8编码。我还应该在每个源文件的开头使用编码声明吗?喜欢# -*- coding: utf-8 -*-

Python 3 uses UTF-8 encoding for source-code files by default. Should I still use the encoding declaration at the beginning of every source file? Like # -*- coding: utf-8 -*-


回答 0

因为默认值为 UTF-8,所以仅在偏离默认值时或者在依赖其他工具(例如IDE或文本编辑器)来使用该信息时,才需要使用该声明。

换句话说,就Python而言,仅当您要使用不同的编码时,才需要使用该声明。

其他工具(例如您的编辑器)也可以支持类似的语法,这就是PEP 263规范在语法上具有相当大的灵活性的原因(它必须是注释,文本coding必须在其中,后跟a :=字符以及可选的空白,然后是公认的编解码器)。

请注意,它仅适用于Python如何读取源代码。它不适用于执行该代码,因此不适用于打印,打开文件或字节与Unicode之间的任何其他I / O操作转换。有关Python,Unicode和编码的更多详细信息,强烈建议您阅读Python Unicode HOWTO或Ned Batchelder撰写的非常详尽的Pragmatic Unicode演讲

Because the default is UTF-8, you only need to use that declaration when you deviate from the default, or if you rely on other tools (like your IDE or text editor) to make use of that information.

In other words, as far as Python is concerned, only when you want to use an encoding that differs do you have to use that declaration.

Other tools, such as your editor, can support similar syntax, which is why the PEP 263 specification allows for considerable flexibility in the syntax (it must be a comment, the text coding must be there, followed by either a : or = character and optional whitespace, followed by a recognised codec).

Note that it only applies to how Python reads the source code. It doesn’t apply to executing that code, so not to how printing, opening files, or any other I/O operations translate between bytes and Unicode. For more details on Python, Unicode, and encodings, I strongly urge you to read the Python Unicode HOWTO, or the very thorough Pragmatic Unicode talk by Ned Batchelder.


回答 1

不,如果:

  • 整个项目仅使用UTF-8,这是默认设置。
  • 并且您确定您的IDE工具不需要每个文件中的编码声明。

是的,如果

  • 您的项目依赖于不同的编码
  • 或依赖于许多编码。

对于多编码项目:

如果某些文件在中进行了编码non-utf-8,那么即使对于这些文件,UTF-8您也应该添加编码声明,因为黄金法则是Explicit is better than implicit.

参考:

  • PyCharm不需要该声明:

在pycharm中为特定文件配置编码

  • vim不需要该声明,但是:
# vim: set fileencoding=<encoding name> :

No, if:

  • entire project use only the UTF-8, which is a default.
  • and you’re sure your IDE tool doesn’t need that encoding declaration in each file.

Yes, if

  • your project relies on different encoding
  • or relies on many encodings.

For multi-encodings projects:

If some files are encoded in the non-utf-8, then even for these encoded in UTF-8 you should add encoding declaration too, because the golden rule is Explicit is better than implicit.

Reference:

  • PyCharm doesn’t need that declaration:

configuring encoding for specific file in pycharm

  • vim doesn’t need that declaration, but:
# vim: set fileencoding=<encoding name> :

在括号之间返回文本的正则表达式

问题:在括号之间返回文本的正则表达式

u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'

我需要的只是括号内的内容。

u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'

All I need is the contents inside the parenthesis.


回答 0

如果您的问题确实如此简单,则不需要正则表达式:

s[s.find("(")+1:s.find(")")]

If your problem is really just this simple, you don’t need regex:

s[s.find("(")+1:s.find(")")]

回答 1

用途re.search(r'\((.*?)\)',s).group(1)

>>> import re
>>> s = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
>>> re.search(r'\((.*?)\)',s).group(1)
u"date='2/xc2/xb2',time='/case/test.png'"

Use re.search(r'\((.*?)\)',s).group(1):

>>> import re
>>> s = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'
>>> re.search(r'\((.*?)\)',s).group(1)
u"date='2/xc2/xb2',time='/case/test.png'"

回答 2

如果要查找所有事件:

>>> re.findall('\(.*?\)',s)
[u"(date='2/xc2/xb2',time='/case/test.png')", u'(eee)']

>>> re.findall('\((.*?)\)',s)
[u"date='2/xc2/xb2',time='/case/test.png'", u'eee']

If you want to find all occurences:

>>> re.findall('\(.*?\)',s)
[u"(date='2/xc2/xb2',time='/case/test.png')", u'(eee)']

>>> re.findall('\((.*?)\)',s)
[u"date='2/xc2/xb2',time='/case/test.png'", u'eee']

回答 3

如果您碰巧像这样嵌套嵌套括号,请以tkerwin的答案为基础

st = "sum((a+b)/(c+d))"

如果您需要将第一个开括号最后一个闭括号之间的所有内容都取成get (a+b)/(c+d),他的答案将不起作用,因为find从字符串的左侧开始搜索,并且会在第一个闭括号处停止。

要解决此问题,您需要使用rfind该操作的第二部分,因此它将变成

st[st.find("(")+1:st.rfind(")")]

Building on tkerwin’s answer, if you happen to have nested parentheses like in

st = "sum((a+b)/(c+d))"

his answer will not work if you need to take everything between the first opening parenthesis and the last closing parenthesis to get (a+b)/(c+d), because find searches from the left of the string, and would stop at the first closing parenthesis.

To fix that, you need to use rfind for the second part of the operation, so it would become

st[st.find("(")+1:st.rfind(")")]

回答 4

import re

fancy = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'

print re.compile( "\((.*)\)" ).search( fancy ).group( 1 )
import re

fancy = u'abcde(date=\'2/xc2/xb2\',time=\'/case/test.png\')'

print re.compile( "\((.*)\)" ).search( fancy ).group( 1 )

回答 5

contents_re = re.match(r'[^\(]*\((?P<contents>[^\(]+)\)', data)
if contents_re:
    print(contents_re.groupdict()['contents'])
contents_re = re.match(r'[^\(]*\((?P<contents>[^\(]+)\)', data)
if contents_re:
    print(contents_re.groupdict()['contents'])

如何使用pip在Windows上安装PyQt4?

问题:如何使用pip在Windows上安装PyQt4?

我在Windows上使用Python 3.4。当我运行脚本时,它抱怨

ImportError: No Module named 'PyQt4'

所以我尝试安装它,但是pip install PyQt4

找不到符合要求PyQt4的下载

尽管我跑步时确实会出现pip search PyQt4。我尝试pip install python-qt安装成功,但这并不能解决问题。

我究竟做错了什么?

I’m using Python 3.4 on Windows. When I run a script, it complains

ImportError: No Module named 'PyQt4'

So I tried to install it, but pip install PyQt4 gives

Could not find any downloads that satisfy the requirement PyQt4

although it does show up when I run pip search PyQt4. I tried to pip install python-qt, which installed successfully but that didn’t solve the problem.

What am I doing wrong?


回答 0

这是Chris Golke构建的Windows wheel软件包-Python Windows Binary软件包 -PyQt

在文件名中cp27表示C-python版本2.7,cp35表示python 3.5等。

由于Qt是一个更复杂的系统,它在python接口的基础上提供了已编译的C ++代码库,因此它的构建可能比仅纯python代码包要复杂得多,这意味着很难从源代码安装它。

确保获取正确的Windows wheel文件(python版本,32/64位),然后使用pip进行安装-例如:

C:\path\where\wheel\is\> pip install PyQt4-4.11.4-cp35-none-win_amd64.whl

如果您运行的是Python 3.5的x64版本,则应正确安装。

Here are Windows wheel packages built by Chris Golke – Python Windows Binary packages – PyQt

In the filenames cp27 means C-python version 2.7, cp35 means python 3.5, etc.

Since Qt is a more complicated system with a compiled C++ codebase underlying the python interface it provides you, it can be more complex to build than just a pure python code package, which means it can be hard to install it from source.

Make sure you grab the correct Windows wheel file (python version, 32/64 bit), and then use pip to install it – e.g:

C:\path\where\wheel\is\> pip install PyQt4-4.11.4-cp35-none-win_amd64.whl

Should properly install if you are running an x64 build of Python 3.5.


回答 1

QT不再支持PyQt4,但是您可以通过pip安装PyQt5:

pip install PyQt5

QT no longer supports PyQt4, but you can install PyQt5 with pip:

pip install PyQt5

回答 2

你不能使用点子。您必须从Riverbank网站下载并运行适用于您的python版本的安装程序。如果您的版本没有安装,则必须为可用的安装程序之一安装Python,或者从源代码进行构建(这涉及到)。其他答案和评论都有链接。

You can’t use pip. You have to download from the Riverbank website and run the installer for your version of python. If there is no install for your version, you will have to install Python for one of the available installers, or build from source (which is rather involved). Other answers and comments have the links.


回答 3

如果您在Windows上安装PyQt4,则默认情况下文件会在此处结束:

C:\ Python27 \ Lib \ site-packages \ PyQt4 *。*

但它还会在此处保留文件:

C:\ Python27 \ Lib \ site-packages \ sip.pyd

如果将sip.pyd和PyQt4文件夹都复制到virtualenv中,则一切正常。

例如:

mkdir c:\code
cd c:\code
virtualenv BACKUP
cd c:\code\BACKUP\scripts
activate

然后使用Windows资源管理器从C:\Python27\Lib\site-packages上述文件(sip.pyd)和文件夹(PyQt4)复制到C:\code\BACKUP\Lib\site-packages\

然后回到CLI:

cd ..                 
(c:\code\BACKUP)
python backup.py

尝试启动从virtualenv内部调用PyQt4的脚本的问题在于virtualenv没有安装PyQt4,并且不知道如何引用上述默认安装。但是,请按照以下步骤将PyQt4复制到您的virtualenv中,并且一切正常。

If you install PyQt4 on Windows, files wind up here by default:

C:\Python27\Lib\site-packages\PyQt4*.*

but it also leaves a file here:

C:\Python27\Lib\site-packages\sip.pyd

If you copy the both the sip.pyd and PyQt4 folder into your virtualenv things will work fine.

For example:

mkdir c:\code
cd c:\code
virtualenv BACKUP
cd c:\code\BACKUP\scripts
activate

Then with windows explorer copy from C:\Python27\Lib\site-packages the file (sip.pyd) and folder (PyQt4) mentioned above to C:\code\BACKUP\Lib\site-packages\

Then back at CLI:

cd ..                 
(c:\code\BACKUP)
python backup.py

The problem with trying to launch a script which calls PyQt4 from within virtualenv is that the virtualenv does not have PyQt4 installed and it doesn’t know how to reference the default installation described above. But follow these steps to copy PyQt4 into your virtualenv and things should work great.


回答 4

可以从网站下载页面直接获得较早的PyQt .exe安装程序。现在,随着PyQt4.12的发布,安装程序已被弃用。您可以通过编译它们使库以某种方式工作,但这意味着要花很多时间。

否则,您可以使用以前的发行版来解决您的目的。可以从以下网站下载.exe Windows安装程序:

https://sourceforge.net/projects/pyqt/files/PyQt4/PyQt-4.11.4/

Earlier PyQt .exe installers were available directly from the website download page. Now with the release of PyQt4.12 , installers have been deprecated. You can make the libraries work somehow by compiling them but that would mean going to great lengths of trouble.

Otherwise you can use the previous distributions to solve your purpose. The .exe windows installers can be downloaded from :

https://sourceforge.net/projects/pyqt/files/PyQt4/PyQt-4.11.4/


回答 5

看来您可能需要对PyQt4进行一些手动安装。

http://pyqt.sourceforge.net/Docs/PyQt4/installation.html

这可能会有所帮助,在教程/逐步设置格式中可能会有所帮助:

http://movingthelamppost.com/blog/html/2013/07/12/installing_pyqt____因为_it_s_too_good_for_pip_or_easy_install_.html

It looks like you may have to do a bit of manual installation for PyQt4.

http://pyqt.sourceforge.net/Docs/PyQt4/installation.html

This might help a bit more, it’s a bit more in a tutorial/set-by-step format:

http://movingthelamppost.com/blog/html/2013/07/12/installing_pyqt____because_it_s_too_good_for_pip_or_easy_install_.html


回答 6

使用当前最新的python 3.6.5

pip3 install PyQt5

工作良好

With current latest python 3.6.5

pip3 install PyQt5

works fine


回答 7

尝试使用PyQt5:

pip install PyQt5

链接上将操作系统用于PyQt4。

或在链接上为您的平台下载支持的车轮。

否则,链接可用于Windows可执行安装程序。希望这可以帮助您安装PyQt4或PyQt5。

Try this for PyQt5:

pip install PyQt5

Use the operating system on this link for PyQt4.

Or download the supported wheel for your platform on this link.

Else use this link for the windows executable installer. Hopefully this helps you to install either PyQt4 or PyQt5.


回答 8

对于Windows:

从此处下载适当版本的PyQt4:

并使用pip进行安装(Python3.6的示例-64位)

 pip install PyQt44.11.4cp36cp36mwin_amd64.whl 

For Windows:

download the appropriate version of the PyQt4 from here:

and install it using pip (example for Python3.6 – 64bit)

 pip install PyQt4‑4.11.4‑cp36‑cp36m‑win_amd64.whl 

回答 9

为Windows 10和python 3.5+安装PyQt5。

点安装PyQt5

install PyQt5 for Windows 10 and python 3.5+.

pip install PyQt5


回答 10

如果在安装PyQt4时出错。

错误:此平台不支持PyQt4-4.11.4-cp27-cp27m-win_amd64.whl。

我的系统类型是64位,但要解决这个错误我已经安装了32位Windows系统的PyQt4的,即PyQt4-4.11.4-cp27-cp27m-win32.whl点击这里查看更多版本

请根据您安装的python版本选择合适的PyQt4版本。

If you have error while installing PyQt4.

Error: PyQt4-4.11.4-cp27-cp27m-win_amd64.whl is not a supported wheel on this platform.

My system type is 64 bit, But to solve this error I have installed PyQt4 of 32 bit windows system, i.e PyQt4-4.11.4-cp27-cp27m-win32.whlclick here to see more versions.

Kindly select appropriate version of PyQt4 according to your installed python version.


回答 11

您也可以使用此命令来安装PyQt5。

pip3 install PyQt5

You can also use this command to install PyQt5.

pip3 install PyQt5

回答 12

我正在使用PyCharm,并且能够安装PyQt5。

PyQt4以及PyQt4Enhanced和windows_whl都无法安装,我猜这是因为不再支持Qt4。

I am using PyCharm, and was able to install PyQt5.

PyQt4, as well as PyQt4Enhanced and windows_whl both failed to install, I’m guessing that’s because Qt4 is no longer supported.


在Python 3中禁止/打印不带b’前缀的字节

问题:在Python 3中禁止/打印不带b’前缀的字节

只需发布此内容,以便稍后查找,因为它总是让我感到困惑:

$ python3.2
Python 3.2 (r32:88445, Oct 20 2012, 14:09:50) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import curses
>>> print(curses.version)
b'2.2'
>>> print(str(curses.version))
b'2.2'
>>> print(curses.version.encode('utf-8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'encode'
>>> print(str(curses.version).encode('utf-8'))
b"b'2.2'"

问题:如何bytes在Python 3中打印不带b'前缀的二进制()字符串?

Just posting this so I can search for it later, as it always seems to stump me:

$ python3.2
Python 3.2 (r32:88445, Oct 20 2012, 14:09:50) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import curses
>>> print(curses.version)
b'2.2'
>>> print(str(curses.version))
b'2.2'
>>> print(curses.version.encode('utf-8'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'bytes' object has no attribute 'encode'
>>> print(str(curses.version).encode('utf-8'))
b"b'2.2'"

As question: how to print a binary (bytes) string in Python 3, without the b' prefix?


回答 0

用途decode

print(curses.version.decode())
# 2.2

Use decode:

print(curses.version.decode())
# 2.2

回答 1

如果字节已经使用适当的字符编码;您可以直接打印它们:

sys.stdout.buffer.write(data)

要么

nwritten = os.write(sys.stdout.fileno(), data)  # NOTE: it may write less than len(data) bytes

If the bytes use an appropriate character encoding already; you could print them directly:

sys.stdout.buffer.write(data)

or

nwritten = os.write(sys.stdout.fileno(), data)  # NOTE: it may write less than len(data) bytes

回答 2

如果我们看一下的源代码bytes.__repr__,看起来就像b''是将烘焙到方法中一样。

最明显的解决方法是b''从结果中手动切片repr()

>>> x = b'\x01\x02\x03\x04'

>>> print(repr(x))
b'\x01\x02\x03\x04'

>>> print(repr(x)[2:-1])
\x01\x02\x03\x04

If we take a look at the source for bytes.__repr__, it looks as if the b'' is baked into the method.

The most obvious workaround is to manually slice off the b'' from the resulting repr():

>>> x = b'\x01\x02\x03\x04'

>>> print(repr(x))
b'\x01\x02\x03\x04'

>>> print(repr(x)[2:-1])
\x01\x02\x03\x04

回答 3

如果数据采用UTF-8兼容格式,则可以将字节转换为字符串。

>>> import curses
>>> print(str(curses.version, "utf-8"))
2.2

如果数据尚不兼容UTF-8,则可以选择先转换为十六进制。例如,当数据是实际的原始字节时。

from binascii import hexlify
from codecs import encode  # alternative
>>> print(hexlify(b"\x13\x37"))
b'1337'
>>> print(str(hexlify(b"\x13\x37"), "utf-8"))
1337
>>>> print(str(encode(b"\x13\x37", "hex"), "utf-8"))
1337

If the data is in an UTF-8 compatible format, you can convert the bytes to a string.

>>> import curses
>>> print(str(curses.version, "utf-8"))
2.2

Optionally convert to hex first, if the data is not already UTF-8 compatible. E.g. when the data are actual raw bytes.

from binascii import hexlify
from codecs import encode  # alternative
>>> print(hexlify(b"\x13\x37"))
b'1337'
>>> print(str(hexlify(b"\x13\x37"), "utf-8"))
1337
>>>> print(str(encode(b"\x13\x37", "hex"), "utf-8"))
1337

pip安装中“ X的构建车轮失败”是什么意思?

问题:pip安装中“ X的构建车轮失败”是什么意思?

在SO上,这是一个真正流行的问题,但是我看过的所有答案中,没有一个能清楚地说明此错误的真正含义以及发生的原因。

造成混乱的原因之一是,当您(例如)这样做时pip install pycparser,您首先会得到以下错误:

Failed building wheel for pycparser

然后出现以下消息,说明该软件包是:

Successfully installed pycparser-2.19


# pip3 install pycparser

Collecting pycparser
  Using cached https://files.pythonhosted.org/packages/68/9e/49196946aee219aead1290e00d1e7fdeab8567783e83e1b9ab5585e6206a/pycparser-2.19.tar.gz
Building wheels for collected packages: pycparser
  Running setup.py bdist_wheel for pycparser ... error
  Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-g_v28hpp/pycparser/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-__w_f6p0 --python-tag cp36:
  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    ...
    File "/usr/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2349, in resolve
      module = __import__(self.module_name, fromlist=['__name__'], level=0)
  ModuleNotFoundError: No module named 'wheel.bdist_wheel'

  ----------------------------------------
  Failed building wheel for pycparser
  Running setup.py clean for pycparser
Failed to build pycparser
Installing collected packages: pycparser
  Running setup.py install for pycparser ... done
Successfully installed pycparser-2.19

这里发生了什么?

(我想了解如何发生某些故障但仍然可以安装,以及是否可以信任此软件包正常运行?)

到目前为止,我已经找到了最好的部分原因是这个

This is a truly popular question here at SO, but none of the many answers I have looked at, clearly explain what this error really mean, and why it occurs.

One source of confusion, is that when (for example) you do pip install pycparser, you first get the error:

Failed building wheel for pycparser

which is then followed by the message that the package was:

Successfully installed pycparser-2.19.


# pip3 install pycparser

Collecting pycparser
  Using cached https://files.pythonhosted.org/packages/68/9e/49196946aee219aead1290e00d1e7fdeab8567783e83e1b9ab5585e6206a/pycparser-2.19.tar.gz
Building wheels for collected packages: pycparser
  Running setup.py bdist_wheel for pycparser ... error
  Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-g_v28hpp/pycparser/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-__w_f6p0 --python-tag cp36:
  Traceback (most recent call last):
    File "<string>", line 1, in <module>
    ...
    File "/usr/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2349, in resolve
      module = __import__(self.module_name, fromlist=['__name__'], level=0)
  ModuleNotFoundError: No module named 'wheel.bdist_wheel'

  ----------------------------------------
  Failed building wheel for pycparser
  Running setup.py clean for pycparser
Failed to build pycparser
Installing collected packages: pycparser
  Running setup.py install for pycparser ... done
Successfully installed pycparser-2.19

What is going on here?

(I would like to understand how something can fail but still get installed and whether you can trust this package functioning correctly?)

So far the best partial explanation I have found is this.


回答 0

(这里是点子维护者!)

如果包装不是车轮,则pip尝试为其构建一个车轮(通过setup.py bdist_wheel)。如果由于任何原因导致安装失败,您将收到“ pycparser的建筑轮子故障”消息,并且pip退回到直接安装(通过setup.py install)。

装好轮子后,pip可以通过正确打开包装来安装轮子。pip尝试尽可能多地通过轮子安装软件包。这是由于使用滚轮的各种优势(例如更快的安装,可缓存的,不再执行代码等)。


您在这里的错误消息是由于wheel缺少软件包,其中包含构建轮子所需的逻辑setup.py bdist_wheel。(pip install wheel可以解决该问题。)


以上是当前默认的旧行为;我们会默认在将来的某个时间切换到PEP 517,为此我们将转到基于标准的流程。我们还为此提供了隔离的版本,因此,默认情况下,您会在这些环境中安装滚轮。:)

(pip maintainer here!)

If the package is not a wheel, pip tries to build a wheel for it (via setup.py bdist_wheel). If that fails for any reason, you get the “Failed building wheel for pycparser” message and pip falls back to installing directly (via setup.py install).

Once we have a wheel, pip can install the wheel by unpacking it correctly. pip tries to install packages via wheels as often as it can. This is because of various advantages of using wheels (like faster installs, cache-able, not executing code again etc).


Your error message here is due to the wheel package being missing, which contains the logic required to build the wheels in setup.py bdist_wheel. (pip install wheel can fix that.)


The above is the legacy behavior that is currently the default; we’ll switch to PEP 517 by default, sometime in the future, moving us to a standards-based process for this. We also have isolated builds for that so, you’d have wheel installed in those environments by default. :)


回答 1

昨天,我遇到了同样的错误: Failed building wheel for hddfancontrol跑步时pip3 install hddfancontrol。结果是Failed to build hddfancontrol。原因是error: invalid command 'bdist_wheel'Running setup.py bdist_wheel for hddfancontrol ... error。通过运行以下命令修复了该错误:

 pip3 install wheel

(从这里开始。)

另外,也可以从此处直接下载“ wheel” 。下载后,可以通过运行以下命令进行安装:

pip3 install "/the/file_path/to/wheel-0.32.3-py2.py3-none-any.whl"

Yesterday, I got the same error: Failed building wheel for hddfancontrol when I ran pip3 install hddfancontrol. The result was Failed to build hddfancontrol. The cause was error: invalid command 'bdist_wheel' and Running setup.py bdist_wheel for hddfancontrol ... error. The error was fixed by running the following:

 pip3 install wheel

(From here.)

Alternatively, the “wheel” can be downloaded directly from here. When downloaded, it can be installed by running the following:

pip3 install "/the/file_path/to/wheel-0.32.3-py2.py3-none-any.whl"

回答 2

从那以后,似乎没有人提到我自己。我自己解决上述问题是最常见的,以确保禁用缓存使用副本:pip install <package> --no-cache-dir

Since, nobody seem to mention this apart myself. My own solution to the above problem is most often to make sure to disable the cached copy by using: pip install <package> --no-cache-dir.


回答 3

从程序包部署的角度解决此问题可能会有所帮助。

那里有许多教程介绍了如何将程序包发布到PyPi。以下是我使用过的几对;

中型
真正的python

我的经验是,这些教程大多数都只使用源代码的.tar,而不使用转盘。因此,在安装使用这些教程创建的软件包时,我收到了“无法构建轮子”错误。

后来我在PyPi上找到了指向Python软件基金会的文档PSF Docs的链接。我发现它们的设置和构建过程略有不同,并且确实包括构建wheel文件。

使用正式记录的方法后,安装软件包时不再收到错误。

因此,错误可能只是开发人员如何打包和部署项目的问题。我们当中没有一个人天生就知道如何使用PyPi,如果它们是在错误的教程上发生的,那么您可以填补空白。

我敢肯定这不是错误的唯一原因,但我敢打赌这是主要原因。

It might be helpful to address this question from a package deployment perspective.

There are many tutorials out there that explain how to publish a package to PyPi. Below are a couple I have used;

medium
real python

My experience is that most of these tutorials only have you use the .tar of the source, not a wheel. Thus, when installing packages created using these tutorials, I’ve received the “Failed to build wheel” error.

I later found the link on PyPi to the Python Software Foundation’s docs PSF Docs. I discovered that their setup and build process is slightly different, and does indeed included building a wheel file.

After using the officially documented method, I no longer received the error when installing my packages.

So, the error might simply be a matter of how the developer packaged and deployed the project. None of us were born knowing how to use PyPi, and if they happened upon the wrong tutorial — well, you can fill in the blanks.

I’m sure that is not the only reason for the error, but I’m willing to bet that is a major reason for it.


回答 4

试试这个:

sudo apt-get install libpcap-dev libpq-dev

当我安装了这两个时,它对我有用。

有关更多信息,请参见此处的链接。

Try this:

sudo apt-get install libpcap-dev libpq-dev

It has worked for me when I have installed these two.

See the link here for more information


回答 5

在Ubuntu 18.04上,我遇到了此问题,因为的apt软件包wheel不包含wheel命令。我认为pip尝试导入wheelpython包,如果成功,则假定wheel命令也可用。Ubuntu打破了这一假设。

apt python3代码包的名称为python3-wheel。这是自动安装的,因为python3-pip建议您这样做。

apt python3 wheel命令包的名称为python-wheel-common。安装此工具也可以为我解决“建筑轮子故障”错误。

On Ubuntu 18.04, I ran into this issue because the apt package for wheel does not include the wheel command. I think pip tries to import the wheel python package, and if that succeeds assumes that the wheel command is also available. Ubuntu breaks that assumption.

The apt python3 code package is named python3-wheel. This is installed automatically because python3-pip recommends it.

The apt python3 wheel command package is named python-wheel-common. Installing this too fixes the “failed building wheel” errors for me.


回答 6

当我尝试安装pip install django-imagekit时,出现了相同的消息。因此,我运行了pip install wheel(我安装了python 2.7),然后重新运行了pip install django-imagekit,它开始工作了。谢谢

I got the same message when I tried to install pip install django-imagekit. So I ran pip install wheel (I had python 2.7) and then I reran pip install django-imagekit and it worked. Thanks


回答 7

我想补充一点,如果您的系统上只有Python3,则需要开始使用pip3而不是pip。

您可以使用以下命令安装pip3;

sudo apt install python3-pip -y

之后,您可以尝试安装所需的软件包。

sudo pip3 install <package>

I would like to add that if you only have Python3 on your system then you need to start using pip3 instead of pip.

You can install pip3 using the following command;

sudo apt install python3-pip -y

After this you can try to install the package you need with;

sudo pip3 install <package>

回答 8

错误:

系统:AWS EC2实例(T2小)

问题:通过安装opencv python时

pip3 install opencv-python

  Problem with the CMake installation, aborting build. CMake executable is cmake
  
  ----------------------------------------
  Failed building wheel for opencv-python
  Running setup.py clean for opencv-python

什么对我有用

pip3 install --upgrade pip setuptools wheel

在此之后,您仍然可能会收到休闲错误错误

    from .cv2 import *
ImportError: libGL.so.1: cannot open shared object file: No such file or directory

安装libgl为我解决了错误。

sudo apt update
sudo apt install libgl1-mesa-glx

希望这可以帮助

Error :

System : aws ec2 instance (t2 small)

issue : while installing opencv python via

pip3 install opencv-python

  Problem with the CMake installation, aborting build. CMake executable is cmake
  
  ----------------------------------------
  Failed building wheel for opencv-python
  Running setup.py clean for opencv-python

What worked for me

pip3 install --upgrade pip setuptools wheel

After this you still might received fallowing error error

    from .cv2 import *
ImportError: libGL.so.1: cannot open shared object file: No such file or directory

Installing libgl solved the error for me.

sudo apt update
sudo apt install libgl1-mesa-glx

Hope this helps


回答 9

安装Brotli时遇到相同的问题

错误

Failed building wheel for Brotli

我通过.whl此处下载文件 并使用以下命令进行安装来解决了该问题

C:\Users\{user_name}\Downloads>pip install Brotli-1.0.9-cp39-cp39-win_amd64.whl

I had the same problem while installing Brotli

ERROR

Failed building wheel for Brotli

I solved it by downloading the .whl file from here and installing it using the below command

C:\Users\{user_name}\Downloads>pip install Brotli-1.0.9-cp39-cp39-win_amd64.whl

回答 10

这可能对您有帮助!….

卸载pycparser:

pip uninstall pycparser

重新安装pycparser:

pip install pycparser

我在安装termcolor时遇到了同样的错误,并通过重新安装进行了修复。

This may Help you ! ….

Uninstalling pycparser:

pip uninstall pycparser

Reinstall pycparser:

pip install pycparser

I got same error while installing termcolor and I fixed it by reinstalling it .


为什么Python 3允许“ 00”作为0的文字,却不允许“ 01”作为1的文字?

问题:为什么Python 3允许“ 00”作为0的文字,却不允许“ 01”作为1的文字?

为什么Python 3允许“ 00”作为原义的0,却不允许“ 01”作为原义的1?有充分的理由吗?这种矛盾使我感到困惑。(我们正在谈论的是Python 3,它故意打破了向后兼容性以实现诸如一致性之类的目标。)

例如:

>>> from datetime import time
>>> time(16, 00)
datetime.time(16, 0)
>>> time(16, 01)
  File "<stdin>", line 1
    time(16, 01)
              ^
SyntaxError: invalid token
>>>

Why does Python 3 allow “00” as a literal for 0 but not allow “01” as a literal for 1? Is there a good reason? This inconsistency baffles me. (And we’re talking about Python 3, which purposely broke backward compatibility in order to achieve goals like consistency.)

For example:

>>> from datetime import time
>>> time(16, 00)
datetime.time(16, 0)
>>> time(16, 01)
  File "<stdin>", line 1
    time(16, 01)
              ^
SyntaxError: invalid token
>>>

回答 0

根据https://docs.python.org/3/reference/lexical_analysis.html#integer-literals

整数文字由以下词汇定义描述:

integer        ::=  decimalinteger | octinteger | hexinteger | bininteger
decimalinteger ::=  nonzerodigit digit* | "0"+
nonzerodigit   ::=  "1"..."9"
digit          ::=  "0"..."9"
octinteger     ::=  "0" ("o" | "O") octdigit+
hexinteger     ::=  "0" ("x" | "X") hexdigit+
bininteger     ::=  "0" ("b" | "B") bindigit+
octdigit       ::=  "0"..."7"
hexdigit       ::=  digit | "a"..."f" | "A"..."F"
bindigit       ::=  "0" | "1"

除了可以存储在可用内存中的整数之外,整数文字的长度没有限制。

请注意,不允许使用非零十进制数字开头的零。这是为了消除C样式八进制文字的歧义,Python在3.0版之前使用了这些样式。

如此处所述,不允许使用非零十进制数字开头的零"0"+作为一个非常特殊的情况是合法的,这在Python 2中是不存在的

integer        ::=  decimalinteger | octinteger | hexinteger | bininteger
decimalinteger ::=  nonzerodigit digit* | "0"
octinteger     ::=  "0" ("o" | "O") octdigit+ | "0" octdigit+

SVN commit r55866在令牌生成器中实现了PEP 3127,它禁止使用旧0<octal>数字。但是,奇怪的是,它也添加了以下注释:

/* in any case, allow '0' as a literal */

带有nonzeroSyntaxError在以下数字序列包含非零数字时抛出的特殊标志。

这很奇怪,因为PEP 3127不允许这种情况:

该PEP建议,将使用Python 3.0(和2.6的Python 3.0预览模式)从语言中删除使用前导零指定八进制数的功能,并且每当前导“ 0”为紧跟着另一个数字

(强调我的)

因此,允许多个零的事实在技术上违反了PEP,并且基本上由Georg Brandl实施为特殊情况。他进行了相应的文档更改,以注意这"0"+是的有效案例decimalinteger(以前已在中进行了介绍octinteger)。

我们可能永远不会确切知道为什么Georg选择使之"0"+有效-在Python中它可能永远是一个奇怪的情况。


更新 [2015年7月28日]:这个问题引发了关于python-ideas 的热烈讨论Georg在其中进行了讨论

史蒂文·达普拉诺(Steven D’Aprano)写道:

为什么这样定义?[…]为什么我们写0000以得到零?

我可以告诉你,但后来我不得不杀了你。

格奥尔格

后来,该线程生成了此错误报告,旨在摆脱这种特殊情况。乔治在这里

我不记得有意进行更改的原因(从文档更改中可以看出)。

我现在无法提出更改的充分理由[…]

因此,我们有了它:这种不一致背后的确切原因已不复存在。

最后,请注意,该错误报告已被拒绝:对于Python 3.x的其余部分,前导零将仅在零整数上继续被接受。

Per https://docs.python.org/3/reference/lexical_analysis.html#integer-literals:

Integer literals are described by the following lexical definitions:

integer        ::=  decimalinteger | octinteger | hexinteger | bininteger
decimalinteger ::=  nonzerodigit digit* | "0"+
nonzerodigit   ::=  "1"..."9"
digit          ::=  "0"..."9"
octinteger     ::=  "0" ("o" | "O") octdigit+
hexinteger     ::=  "0" ("x" | "X") hexdigit+
bininteger     ::=  "0" ("b" | "B") bindigit+
octdigit       ::=  "0"..."7"
hexdigit       ::=  digit | "a"..."f" | "A"..."F"
bindigit       ::=  "0" | "1"

There is no limit for the length of integer literals apart from what can be stored in available memory.

Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0.

As noted here, leading zeros in a non-zero decimal number are not allowed. "0"+ is legal as a very special case, which wasn’t present in Python 2:

integer        ::=  decimalinteger | octinteger | hexinteger | bininteger
decimalinteger ::=  nonzerodigit digit* | "0"
octinteger     ::=  "0" ("o" | "O") octdigit+ | "0" octdigit+

SVN commit r55866 implemented PEP 3127 in the tokenizer, which forbids the old 0<octal> numbers. However, curiously, it also adds this note:

/* in any case, allow '0' as a literal */

with a special nonzero flag that only throws a SyntaxError if the following sequence of digits contains a nonzero digit.

This is odd because PEP 3127 does not allow this case:

This PEP proposes that the ability to specify an octal number by using a leading zero will be removed from the language in Python 3.0 (and the Python 3.0 preview mode of 2.6), and that a SyntaxError will be raised whenever a leading “0” is immediately followed by another digit.

(emphasis mine)

So, the fact that multiple zeros are allowed is technically violating the PEP, and was basically implemented as a special case by Georg Brandl. He made the corresponding documentation change to note that "0"+ was a valid case for decimalinteger (previously that had been covered under octinteger).

We’ll probably never know exactly why Georg chose to make "0"+ valid – it may forever remain an odd corner case in Python.


UPDATE [28 Jul 2015]: This question led to a lively discussion thread on python-ideas in which Georg chimed in:

Steven D’Aprano wrote:

Why was it defined that way? […] Why would we write 0000 to get zero?

I could tell you, but then I’d have to kill you.

Georg

Later on, the thread spawned this bug report aiming to get rid of this special case. Here, Georg says:

I don’t recall the reason for this deliberate change (as seen from the docs change).

I’m unable to come up with a good reason for this change now […]

and thus we have it: the precise reason behind this inconsistency is lost to time.

Finally, note that the bug report was rejected: leading zeros will continue to be accepted only on zero integers for the rest of Python 3.x.


回答 1

这是特例("0"+

2.4.4。整数文字

整数文字由以下词汇定义描述:

整数:: =十进制整数| 八进制| hexinteger | 二进制整数
十进制整数:: =非零数字* “ 0” +
非零数字:: =“ 1” ...“ 9”
数字:: =“ 0” ...“ 9”
八位整数:: =“ 0”(“ o” |“ O”)八位数字+
hexinteger :: =“ 0”(“ x” |“ X”)十六进制+
bininteger :: =“ 0”(“ b” |“ B”)bindigit +
八位数字:: =“ 0” ...“ 7”
十六进制::: digit | “ a” ...“ f” | “ A” ...“ F”
bindigit :: =“ 0” | “ 1”

如果您查看语法,则很容易看到0需要特殊情况。我不确定为什么在+那里需要’ ‘。是时候浏览一下开发邮件列表了…


有趣的是,在Python2中,有多个0解析为octinteger(最终结果仍然0是)

十进制整数:: =非零数字* “ 0”
八位整数:: =“ 0”(“ o” |“ O”)八位数字+ | “ 0”八位数字+

It’s a special case ("0"+)

2.4.4. Integer literals

Integer literals are described by the following lexical definitions:

integer        ::=  decimalinteger | octinteger | hexinteger | bininteger
decimalinteger ::=  nonzerodigit digit* | "0"+
nonzerodigit   ::=  "1"..."9"
digit          ::=  "0"..."9"
octinteger     ::=  "0" ("o" | "O") octdigit+
hexinteger     ::=  "0" ("x" | "X") hexdigit+
bininteger     ::=  "0" ("b" | "B") bindigit+
octdigit       ::=  "0"..."7"
hexdigit       ::=  digit | "a"..."f" | "A"..."F"
bindigit       ::=  "0" | "1"

If you look at the grammar, it’s easy to see that 0 need a special case. I’m not sure why the ‘+‘ is considered necessary there though. Time to dig through the dev mailing list…


Interesting to note that in Python2, more than one 0 was parsed as an octinteger (the end result is still 0 though)

decimalinteger ::=  nonzerodigit digit* | "0"
octinteger     ::=  "0" ("o" | "O") octdigit+ | "0" octdigit+

回答 2

Python2使用前导零指定八进制数:

>>> 010
8

为了避免这种情况(?误导性)行为,Python3需要明确的前缀0b0o0x

>>> 0o10
8

Python2 used the leading zero to specify octal numbers:

>>> 010
8

To avoid this (misleading?) behaviour, Python3 requires explicit prefixes 0b, 0o, 0x:

>>> 0o10
8

Anaconda与Python有何关系?

问题:Anaconda与Python有何关系?

我是一个初学者,我想学习计算机编程。因此,到目前为止,我已经开始自己学习Python,并掌握了有关C和Fortran编程的知识。

现在,我已经安装了Python 3.6.0版,并且一直在努力寻找适合该版本的Python学习文字。甚至在线讲座系列也要求版本2.7和2.5。

现在,我已经有了一本书,但是,该书在版本2中进行了编码,并试图在版本3中使其尽可能接近(根据作者);作者建议“下载Windows版Anaconda”以安装Python。

所以,我的问题是:这是什么“ Anaconda”?我看到这是一个开放的数据科学平台。这是什么意思?是某些编辑器还是诸如Pycharm,IDLE之类的东西?

另外,我从Python.org下载了适用于Windows的Python(我现在正在使用的Python),而我不需要安装任何“开放数据科学平台”。那么这是怎么回事?

请用简单的语言解释。我对这些没有太多的了解。

I am a beginner and I want to learn computer programming. So, for now, I have started learning Python by myself with some knowledge about programming in C and Fortran.

Now, I have installed Python version 3.6.0 and I have struggled finding a suitable text for learning Python in this version. Even the online lecture series ask for versions 2.7 and 2.5 .

Now that I have got a book which, however, makes codes in version 2 and tries to make it as close as possible in version 3 (according to the author); the author recommends “downloading Anaconda for Windows” for installing Python.

So, my question is: What is this ‘Anaconda’? I saw that it was some open data science platform. What does it mean? Is it some editor or something like Pycharm, IDLE or something?

Also, I downloaded my Python (the one that I am using right now) for Windows from Python.org and I didn’t need to install any “open data science platform”. So what is this happening?

Please explain in easy language. I don’t have too much knowledge about these.


回答 0

Anaconda是python和R 发行版。它旨在“开箱即用”地提供数据科学所需的一切(Python方面)。

这包括:

  • 核心Python语言
  • 100多个Python“软件包”(库)
  • Spyder(IDE /编辑器-如PyCharm)和Jupyter
  • conda,Anaconda自己的软件包管理器,用于更新Anaconda和软件包

您的类可能已经推荐了这些额外功能,但是如果您不需要它们,并且可以使用香草Python也可以。

了解更多信息:https : //www.anaconda.com/distribution/

Anaconda is a python and R distribution. It aims to provide everything you need (Python-wise) for data science “out of the box”.

It includes:

  • The core Python language
  • 100+ Python “packages” (libraries)
  • Spyder (IDE/editor – like PyCharm) and Jupyter
  • conda, Anaconda’s own package manager, used for updating Anaconda and packages

Your course may have recommended it as it comes with these extras but if you don’t need them and are getting on fine with vanilla Python that’s OK too.

Learn more: https://www.anaconda.com/distribution/


回答 1

Anaconda是一个Python发行版,可轻松以灵活的方式在Windows或Linux机器上安装Python以及其最常用的第三方库。

我在Windows和Linux上的使用经验都非常积极。它非常完整,可以避免从源代码构建所需的库时出现问题,而这些问题经常通过诸如pip之类的工具一一安装这些库。

顺便说一句:从3.5或3.6开始非常明智,因为2.7即将接近其生命周期,尽管许多应用程序仍依赖它。

至于教程:Python自己的文档非常适合学习该语言。

https://docs.python.org/3/tutorial/

Anaconda is a Python distribution that makes it easy to install Python plus a number of its most often used 3rd party libraries in a flexible way on a Windows or Linux machine.

My experiences with it are very positive, both on Windows and Linux. It is quite complete and avoids problems in building libraries that you need from source code, that frequently plague one by one installations of those libraries by tools like pip.

By the way: It’s very wise to start with 3.5 or 3.6 since 2.7 is approaching the end of its lifecycle, though many applications still depend on it.

As for tutorials: Pythons own docs are quite suitable for learning the language.

https://docs.python.org/3/tutorial/


回答 2

Anaconda是基于Python的数据处理和科学计算平台。它内置了许多非常有用的第三方库。安装Anaconda等效于自动安装Python和一些常用的库,例如Numpy,Pandas,Scrip和Matplotlib,因此,它比常规的Python安装容易得多。如果您没有安装Anaconda,而是仅从python.org安装Python,则还需要使用pip逐一安装各种库。这很痛苦,您需要考虑兼容性,因此强烈建议直接安装Anaconda。

Anaconda is a Python-based data processing and scientific computing platform. It has built in many very useful third-party libraries. Installing Anaconda is equivalent to automatically installing Python and some commonly used libraries such as Numpy, Pandas, Scrip, and Matplotlib, so it makes the installation so much easier than regular Python installation. If you don’t install Anaconda, but instead only install Python from python.org, you also need to use pip to install various libraries one by one. It is painful and you need to consider compatibility, thus it is highly recommended to directly install Anaconda.


pip抛出TypeError:尝试安装新软件包时parse()得到了意外的关键字参数’transport_encoding’

问题:pip抛出TypeError:尝试安装新软件包时parse()得到了意外的关键字参数’transport_encoding’

我正在使用最新版本的Anaconda3。我刚刚安装了它,我正在尝试下载一些软件包。我正在使用Anaconda Prompt。尝试使用pip做任何事情(包括升级现有软件包)时,我得到以下回溯。

    Exception:
Traceback (most recent call last):
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\commands\install.py", line 335, in run
    wb.build(autobuilding=True)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\req\req_set.py", line 487, in _prepare_file
    req_to_install, finder)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\req\req_set.py", line 428, in _check_skip_installed
    req_to_install, upgrade_allowed)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\index.py", line 811, in get_page
    inst = cls(resp.content, resp.url, resp.headers)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\index.py", line 731, in __init__
    namespaceHTMLElements=False,
TypeError: parse() got an unexpected keyword argument 'transport_encoding'

有任何想法吗?(这个问题只有在我安装了tensorflow之后才开始出现)谢谢。

I am using the latest version of Anaconda3. I just installed it and I am trying to download some packages. I am using the Anaconda Prompt. While trying to use pip to do anything (including upgrading existing packages) I get the following traceback.

    Exception:
Traceback (most recent call last):
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\commands\install.py", line 335, in run
    wb.build(autobuilding=True)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\req\req_set.py", line 487, in _prepare_file
    req_to_install, finder)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\req\req_set.py", line 428, in _check_skip_installed
    req_to_install, upgrade_allowed)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\index.py", line 465, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\index.py", line 423, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\index.py", line 568, in _get_pages
    page = self._get_page(location)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\index.py", line 683, in _get_page
    return HTMLPage.get_page(link, session=self.session)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\index.py", line 811, in get_page
    inst = cls(resp.content, resp.url, resp.headers)
  File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\index.py", line 731, in __init__
    namespaceHTMLElements=False,
TypeError: parse() got an unexpected keyword argument 'transport_encoding'

Any ideas? (this problem only started after I installed tensorflow) Thanks.


回答 0

我有同样的问题,对我有用的是用conda更新点子:

conda install pip

它将我的点值从9.0.1-py36hadba87b_3更改为9.0.1-py36h226ae91_4,并解决了问题。

I had the same problem and what worked for me was updating pip with conda:

conda install pip

It changed my pip from 9.0.1-py36hadba87b_3 to 9.0.1-py36h226ae91_4 and solved issue.


回答 1

下载https://github.com/html5lib/html5lib-python/tree/master/html5lib并覆盖tensorflow环境“ envs \ tensorflow \ Lib \ site-packages \ html5lib”中html5lib文件夹中的所有文件,那么您应该能够在那之后运行任何“ pip install”命令

download https://github.com/html5lib/html5lib-python/tree/master/html5lib and overwrite all the files within html5lib folder in your tensorflow environment “envs\tensorflow\Lib\site-packages\html5lib” Then you should be able to run any “pip install” commands after that


回答 2

我在最新版本的Anaconda 3上安装keras时遇到了相同的问题(使用pip安装tensorflow 1.3之后),我可以通过使用conda安装keras来解决此问题。 conda install -c conda-forge keras

I ran into the same problem while installing keras (after I installed tensorflow 1.3 using pip) on the latest version of Anaconda 3. I was able to fix the problem by installing keras using conda conda install -c conda-forge keras


回答 3

安装SerpentAI时出现此确切错误。我所做的所有修复工作都activate serpent在conda提示符下运行,然后再次运行命令。不知道它是否适用于您的情况,但它们似乎足够接近。

编辑-如果上述方法无效,请注释掉以下行:

这对我来说非常有效。(这花费了我们社区中一个有用的成员进行了8个小时的调试)

I was getting this exact error installing SerpentAI. All I did to fix it was run activate serpent in conda prompt and then I ran the command again. Not sure if it’s applicable to your situation, but they seem close enough that it might.

EDIT – if the above didn’t work, comment out this line:

That worked perfectly for me. (this took a helpful member of our community 8 hours to debug)


回答 4

这对我有用:

python -m pip install –upgrade张量流

This worked for me:

python -m pip install –upgrade tensorflow


回答 5

pip3 install -U html5lib=="0.9999999"

为我工作

这是github上的html5lib错误

来自:https : //stackoverflow.com/a/39087283

pip3 install -U html5lib=="0.9999999"

worked for me

here’s the html5lib bug on github

from: https://stackoverflow.com/a/39087283


回答 6

这是给我的解决方法:

cd /usr/share/python-wheels/

目录的内容:

-rwxrwxrwx   1 www-data www-data 493905 Jul 22  2015 html5lib-0.999-py2.py3-none-any.whl
-rw-r--r--   1 root     root     112620 Apr  3  2019 html5lib-0.999999999-py2.py3-none-any.whl

跑:

mv html5lib-0.999-py2.py3-none-any.whl html5lib-0.999-py2.py3-none-any.whl.bak

pip3工作正常。正在加载旧的0.999版本。

Here was the fix for me:

cd /usr/share/python-wheels/

Contents of dir:

-rwxrwxrwx   1 www-data www-data 493905 Jul 22  2015 html5lib-0.999-py2.py3-none-any.whl
-rw-r--r--   1 root     root     112620 Apr  3  2019 html5lib-0.999999999-py2.py3-none-any.whl

Run:

mv html5lib-0.999-py2.py3-none-any.whl html5lib-0.999-py2.py3-none-any.whl.bak

pip3 works fine after. Was loading the old 0.999 version.


asyncio.ensure_future与BaseEventLoop.create_task与简单协程?

问题:asyncio.ensure_future与BaseEventLoop.create_task与简单协程?

我看过一些关于asyncio的基本Python 3.5教程,以各种方式进行相同的操作。在此代码中:

import asyncio  

async def doit(i):
    print("Start %d" % i)
    await asyncio.sleep(3)
    print("End %d" % i)
    return i

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    #futures = [asyncio.ensure_future(doit(i), loop=loop) for i in range(10)]
    #futures = [loop.create_task(doit(i)) for i in range(10)]
    futures = [doit(i) for i in range(10)]
    result = loop.run_until_complete(asyncio.gather(*futures))
    print(result)

上面定义futures变量的所有三个变体都可以达到相同的结果。我可以看到的唯一区别是,在第三个变体中,执行是乱序的(在大多数情况下不重要)。还有其他区别吗?在某些情况下,我不能仅使用最简单的变体(协程的简单列表)吗?

I’ve seen several basic Python 3.5 tutorials on asyncio doing the same operation in various flavours. In this code:

import asyncio  

async def doit(i):
    print("Start %d" % i)
    await asyncio.sleep(3)
    print("End %d" % i)
    return i

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    #futures = [asyncio.ensure_future(doit(i), loop=loop) for i in range(10)]
    #futures = [loop.create_task(doit(i)) for i in range(10)]
    futures = [doit(i) for i in range(10)]
    result = loop.run_until_complete(asyncio.gather(*futures))
    print(result)

All the three variants above that define the futures variable achieve the same result; the only difference I can see is that with the third variant the execution is out of order (which should not matter in most cases). Is there any other difference? Are there cases where I can’t just use the simplest variant (plain list of coroutines)?


回答 0

实际信息:

从Python 3.7开始,为此添加asyncio.create_task(coro)高级功能。

您应该使用它代替其他从Coroutime创建任务的方式。但是,如果您需要从任意等待中创建任务,则应使用asyncio.ensure_future(obj)


旧信息:

ensure_futurecreate_task

ensure_future是一种Task从创建的方法coroutine。它基于参数(包括create_task对协程和类似未来的对象使用of)以不同的方式创建任务。

create_task是的抽象方法AbstractEventLoop。不同的事件循环可以以不同的方式实现此功能。

您应该ensure_future用来创建任务。create_task仅在要实现自己的事件循环类型时才需要。

更新:

@ bj0指向Guido对此主题的回答

的要点ensure_future()是,如果您拥有某种可能是协程或a的东西Future(后者包含a,Task因为这是的子类Future),并且您希望能够在其上调用仅在其上定义的方法Future(可能是唯一的)有用的示例cancel())。当它已经是Future(或Task)时,则不执行任何操作;当它是一个协程时,它将它包裹在一个Task

如果您知道有一个协程,并且希望对其进行调度,则使用的正确API是create_task()。唯一应该调用的时间ensure_future()是在提供接受协程或a的API(如asyncio自己的大多数API)时,Future您需要对其进行一些操作,要求您拥有a Future

然后:

最后,我仍然相信这ensure_future()是一个很少需要的功能的适当模糊的名称。从协程创建任务时,应使用适当命名的 loop.create_task()。也许应该为此起别名 asyncio.create_task()

我感到惊讶。我一直使用的主要动机ensure_future是,与loop的成员相比,它是更高层的函数create_task(讨论中包含了诸如add asyncio.spawn或的想法asyncio.create_task)。

我还可以指出,在我看来,使用可以处理任何Awaitable而非协程的通用函数非常方便。

但是,Guido的答案很明确:“从协程创建任务时,应使用名称正确的loop.create_task()

什么时候应该将协程包裹在任务中?

将协程包装在Task中-是一种在后台启动此协程的方法。例子如下:

import asyncio


async def msg(text):
    await asyncio.sleep(0.1)
    print(text)


async def long_operation():
    print('long_operation started')
    await asyncio.sleep(3)
    print('long_operation finished')


async def main():
    await msg('first')

    # Now you want to start long_operation, but you don't want to wait it finised:
    # long_operation should be started, but second msg should be printed immediately.
    # Create task to do so:
    task = asyncio.ensure_future(long_operation())

    await msg('second')

    # Now, when you want, you can await task finised:
    await task


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

输出:

first
long_operation started
second
long_operation finished

您可以替换asyncio.ensure_future(long_operation())await long_operation()来感受不同。

Actual info:

Starting from Python 3.7 asyncio.create_task(coro) high-level function was added for this purpose.

You should use it instead other ways of creating tasks from coroutimes. However if you need to create task from arbitrary awaitable, you should use asyncio.ensure_future(obj).


Old info:

ensure_future vs create_task

ensure_future is a method to create Task from coroutine. It creates tasks in different ways based on argument (including using of create_task for coroutines and future-like objects).

create_task is an abstract method of AbstractEventLoop. Different event loops can implement this function different ways.

You should use ensure_future to create tasks. You’ll need create_task only if you’re going to implement your own event loop type.

Upd:

@bj0 pointed at Guido’s answer on this topic:

The point of ensure_future() is if you have something that could either be a coroutine or a Future (the latter includes a Task because that’s a subclass of Future), and you want to be able to call a method on it that is only defined on Future (probably about the only useful example being cancel()). When it is already a Future (or Task) this does nothing; when it is a coroutine it wraps it in a Task.

If you know that you have a coroutine and you want it to be scheduled, the correct API to use is create_task(). The only time when you should be calling ensure_future() is when you are providing an API (like most of asyncio’s own APIs) that accepts either a coroutine or a Future and you need to do something to it that requires you to have a Future.

and later:

In the end I still believe that ensure_future() is an appropriately obscure name for a rarely-needed piece of functionality. When creating a task from a coroutine you should use the appropriately-named loop.create_task(). Maybe there should be an alias for that asyncio.create_task()?

It’s surprising to me. My main motivation to use ensure_future all along was that it’s higher-level function comparing to loop’s member create_task (discussion contains some ideas like adding asyncio.spawn or asyncio.create_task).

I can also point that in my opinion it’s pretty convenient to use universal function that can handle any Awaitable rather than coroutines only.

However, Guido’s answer is clear: “When creating a task from a coroutine you should use the appropriately-named loop.create_task()

When coroutines should be wrapped in tasks?

Wrap coroutine in a Task – is a way to start this coroutine “in background”. Here’s example:

import asyncio


async def msg(text):
    await asyncio.sleep(0.1)
    print(text)


async def long_operation():
    print('long_operation started')
    await asyncio.sleep(3)
    print('long_operation finished')


async def main():
    await msg('first')

    # Now you want to start long_operation, but you don't want to wait it finised:
    # long_operation should be started, but second msg should be printed immediately.
    # Create task to do so:
    task = asyncio.ensure_future(long_operation())

    await msg('second')

    # Now, when you want, you can await task finised:
    await task


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

Output:

first
long_operation started
second
long_operation finished

You can replace asyncio.ensure_future(long_operation()) with just await long_operation() to feel the difference.


回答 1

create_task()

  • 接受协程,
  • 返回任务,
  • 它在循环上下文中调用。

ensure_future()

  • 接受期货,协程,等待对象,
  • 返回Task(如果Future通过,则返回Future)。
  • 如果给定的arg是协程,则使用create_task
  • 可以传递循环对象。

如您所见,create_task更具体。


async 没有create_task或sure_future的函数

简单的调用async函数返回协程

>>> async def doit(i):
...     await asyncio.sleep(3)
...     return i
>>> doit(4)   
<coroutine object doit at 0x7f91e8e80ba0>

并且由于gather幕后确保(ensure_future)args为期货,因此明确地ensure_future是多余的。

类似的问题loop.create_task,asyncio.async / ensure_future和Task有什么区别?

create_task()

  • accepts coroutines,
  • returns Task,
  • it is invoked in context of the loop.

ensure_future()

  • accepts Futures, coroutines, awaitable objects,
  • returns Task (or Future if Future passed).
  • if the given arg is a coroutine it uses create_task,
  • loop object can be passed.

As you can see the create_task is more specific.


async function without create_task or ensure_future

Simple invoking async function returns coroutine

>>> async def doit(i):
...     await asyncio.sleep(3)
...     return i
>>> doit(4)   
<coroutine object doit at 0x7f91e8e80ba0>

And since the gather under the hood ensures (ensure_future) that args are futures, explicitly ensure_future is redundant.

Similar question What’s the difference between loop.create_task, asyncio.async/ensure_future and Task?


回答 2

注意:仅对Python 3.7有效(对于Python 3.5,请参考前面的答案)。

从官方文档:

asyncio.create_task(在Python 3.7中添加)是生成新任务的替代方法,而不是ensure_future()


详情:

因此,现在,在Python 3.7及更高版本中,有2个顶级包装函数(相似但不同):

好吧,这两个包装函数最好都可以帮助您调用BaseEventLoop.create_task。唯一的区别是ensure_future接受任何awaitable对象并帮助您将其转换为Future。另外,您还可以在中提供自己的event_loop参数ensure_future。而且,根据您是否需要这些功能,您可以简单地选择要使用的包装器。

Note: Only valid for Python 3.7 (for Python 3.5 refer to the earlier answer).

From the official docs:

asyncio.create_task (added in Python 3.7) is the preferable way for spawning new tasks instead of ensure_future().


Detail:

So now, in Python 3.7 onwards, there are 2 top-level wrapper function (similar but different):

Well, utlimately both of these wrapper functions will help you call BaseEventLoop.create_task. The only difference is ensure_future accept any awaitable object and help you convert it into a Future. And also you can provide your own event_loop parameter in ensure_future. And depending if you need those capability or not, you can simply choose which wrapper to use.


回答 3

在您的示例中,所有这三种类型都是异步执行的。唯一的区别是,在第三个示例中,您预先生成了所有10个协程,然后一起提交给循环。因此只有最后一个随机输出。

for your example, all the three types execute asynchronously. the only difference is that, in the third example, you pre-generated all 10 coroutines, and submitted to the loop together. so only the last one gives output randomly.


将Enum成员序列化为JSON

问题:将Enum成员序列化为JSON

如何将PythonEnum成员序列化为JSON,以便可以将生成的JSON反序列化为Python对象?

例如,此代码:

from enum import Enum    
import json

class Status(Enum):
    success = 0

json.dumps(Status.success)

导致错误:

TypeError: <Status.success: 0> is not JSON serializable

我该如何避免呢?

How do I serialise a Python Enum member to JSON, so that I can deserialise the resulting JSON back into a Python object?

For example, this code:

from enum import Enum    
import json

class Status(Enum):
    success = 0

json.dumps(Status.success)

results in the error:

TypeError: <Status.success: 0> is not JSON serializable

How can I avoid that?


回答 0

如果您想将任意enum.Enum成员编码为JSON,然后将其解码为相同的enum成员(而不是简单的enum成员的value属性),则可以编写一个自定义JSONEncoder类,并使用一个解码函数作为object_hook参数传递给json.load()or来实现json.loads()

PUBLIC_ENUMS = {
    'Status': Status,
    # ...
}

class EnumEncoder(json.JSONEncoder):
    def default(self, obj):
        if type(obj) in PUBLIC_ENUMS.values():
            return {"__enum__": str(obj)}
        return json.JSONEncoder.default(self, obj)

def as_enum(d):
    if "__enum__" in d:
        name, member = d["__enum__"].split(".")
        return getattr(PUBLIC_ENUMS[name], member)
    else:
        return d

as_enum函数依赖于已使用EnumEncoder或类似行为进行编码的JSON 。

对成员的限制PUBLIC_ENUMS是必要的,以避免使用恶意制作的文本来(例如)欺骗调用代码以将私有信息(例如,应用程序使用的密钥)保存到不相关的数据库字段中,然后从该字段中将其公开(请参阅http://chat.stackoverflow.com/transcript/message/35999686#35999686)。

用法示例:

>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}

If you want to encode an arbitrary enum.Enum member to JSON and then decode it as the same enum member (rather than simply the enum member’s value attribute), you can do so by writing a custom JSONEncoder class, and a decoding function to pass as the object_hook argument to json.load() or json.loads():

PUBLIC_ENUMS = {
    'Status': Status,
    # ...
}

class EnumEncoder(json.JSONEncoder):
    def default(self, obj):
        if type(obj) in PUBLIC_ENUMS.values():
            return {"__enum__": str(obj)}
        return json.JSONEncoder.default(self, obj)

def as_enum(d):
    if "__enum__" in d:
        name, member = d["__enum__"].split(".")
        return getattr(PUBLIC_ENUMS[name], member)
    else:
        return d

The as_enum function relies on the JSON having been encoded using EnumEncoder, or something which behaves identically to it.

The restriction to members of PUBLIC_ENUMS is necessary to avoid a maliciously crafted text being used to, for example, trick calling code into saving private information (e.g. a secret key used by the application) to an unrelated database field, from where it could then be exposed (see http://chat.stackoverflow.com/transcript/message/35999686#35999686).

Example usage:

>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}

回答 1

我知道这很老,但我认为这会对人们有所帮助。我刚刚经历了这个确切的问题,发现您是否使用字符串枚举,将您的枚举声明str为几乎所有情况下都可以正常工作的子类:

import json
from enum import Enum

class LogLevel(str, Enum):
    DEBUG = 'DEBUG'
    INFO = 'INFO'

print(LogLevel.DEBUG)
print(json.dumps(LogLevel.DEBUG))
print(json.loads('"DEBUG"'))
print(LogLevel('DEBUG'))

将输出:

LogLevel.DEBUG
"DEBUG"
DEBUG
LogLevel.DEBUG

如您所见,加载JSON将输出字符串,DEBUG但可以轻松将其转换回LogLevel对象。如果您不想创建自定义JSONEncoder,则是一个不错的选择。

I know this is old but I feel this will help people. I just went through this exact problem and discovered if you’re using string enums, declaring your enums as a subclass of str works well for almost all situations:

import json
from enum import Enum

class LogLevel(str, Enum):
    DEBUG = 'DEBUG'
    INFO = 'INFO'

print(LogLevel.DEBUG)
print(json.dumps(LogLevel.DEBUG))
print(json.loads('"DEBUG"'))
print(LogLevel('DEBUG'))

Will output:

LogLevel.DEBUG
"DEBUG"
DEBUG
LogLevel.DEBUG

As you can see, loading the JSON outputs the string DEBUG but it is easily castable back into a LogLevel object. A good option if you don’t want to create a custom JSONEncoder.


回答 2

正确答案取决于您打算对序列化版本进行的处理。

如果您要反序列化回Python,请参见Zero的答案

如果您的序列化版本将要使用另一种语言,那么您可能想使用IntEnum代替,它将自动序列化为相应的整数:

from enum import IntEnum
import json

class Status(IntEnum):
    success = 0
    failure = 1

json.dumps(Status.success)

这将返回:

'0'

The correct answer depends on what you intend to do with the serialized version.

If you are going to unserialize back into Python, see Zero’s answer.

If your serialized version is going to another language then you probably want to use an IntEnum instead, which is automatically serialized as the corresponding integer:

from enum import IntEnum
import json

class Status(IntEnum):
    success = 0
    failure = 1

json.dumps(Status.success)

and this returns:

'0'

回答 3

在Python 3.7中,只能使用 json.dumps(enum_obj, default=str)

In Python 3.7, can just use json.dumps(enum_obj, default=str)


回答 4

我喜欢Zero Piraeus的回答,但是对它进行了稍作修改,以便使用称为Boto的Amazon Web Services(AWS)的API。

class EnumEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Enum):
            return obj.name
        return json.JSONEncoder.default(self, obj)

然后,我将此方法添加到我的数据模型中:

    def ToJson(self) -> str:
        return json.dumps(self.__dict__, cls=EnumEncoder, indent=1, sort_keys=True)

我希望这可以帮助别人。

I liked Zero Piraeus’ answer, but modified it slightly for working with the API for Amazon Web Services (AWS) known as Boto.

class EnumEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Enum):
            return obj.name
        return json.JSONEncoder.default(self, obj)

I then added this method to my data model:

    def ToJson(self) -> str:
        return json.dumps(self.__dict__, cls=EnumEncoder, indent=1, sort_keys=True)

I hope this helps someone.


回答 5

如果您使用的jsonpickle是最简单的方法,则应如下所示。

from enum import Enum
import jsonpickle


@jsonpickle.handlers.register(Enum, base=True)
class EnumHandler(jsonpickle.handlers.BaseHandler):

    def flatten(self, obj, data):
        return obj.value  # Convert to json friendly format


if __name__ == '__main__':
    class Status(Enum):
        success = 0
        error = 1

    class SimpleClass:
        pass

    simple_class = SimpleClass()
    simple_class.status = Status.success

    json = jsonpickle.encode(simple_class, unpicklable=False)
    print(json)

在Json序列化之后,您将获得预期的{"status": 0}而不是

{"status": {"__objclass__": {"py/type": "__main__.Status"}, "_name_": "success", "_value_": 0}}

If you are using jsonpickle the easiest way should look as below.

from enum import Enum
import jsonpickle


@jsonpickle.handlers.register(Enum, base=True)
class EnumHandler(jsonpickle.handlers.BaseHandler):

    def flatten(self, obj, data):
        return obj.value  # Convert to json friendly format


if __name__ == '__main__':
    class Status(Enum):
        success = 0
        error = 1

    class SimpleClass:
        pass

    simple_class = SimpleClass()
    simple_class.status = Status.success

    json = jsonpickle.encode(simple_class, unpicklable=False)
    print(json)

After Json serialization you will have as expected {"status": 0} instead of

{"status": {"__objclass__": {"py/type": "__main__.Status"}, "_name_": "success", "_value_": 0}}

回答 6

这为我工作:

class Status(Enum):
    success = 0

    def __json__(self):
        return self.value

不必更改其他任何内容。显然,您只会从中获得该值,并且如果您想稍后将序列化的值转换回枚举,则需要做一些其他工作。

This worked for me:

class Status(Enum):
    success = 0

    def __json__(self):
        return self.value

Didn’t have to change anything else. Obviously, you’ll only get the value out of this and will need to do some other work if you want to convert the serialized value back into the enum later.