标签归档:python-2.7

同时安装Anacondas 2.7和3.5可以吗?

问题:同时安装Anacondas 2.7和3.5可以吗?

我目前正在将Anaconda与Python 2.7一起使用,但是我将需要使用Python 3.5。可以同时安装它们吗?我应该期待一些问题吗?
我使用的是64位Win8。

I am using currently Anaconda with Python 2.7, but I will need to use Python 3.5. Is it ok to have them installed both in the same time? Should I expect some problems?
I am on a 64-bit Win8.


回答 0

我的理解是,您无需再次安装Anaconda即可开始使用其他版本的python。相反,conda 可以单独管理python 2和3环境

My understanding is you don’t need to install Anaconda again to start using a different version of python. Instead, conda has the ability to separately manage python 2 and 3 environments.


回答 1

我会同时使用这两种方法,具体取决于我所帮助的部门(有些人喜欢2.7,有些人则喜欢3.5)。无论如何,我使用Anaconda,默认安装为3.5。我将环境用于其他版本的python,软件包等。因此,例如,当我想开始使用python 2.7时,我运行了:

 conda create -n Python27 python=2.7

这将创建一个名为Python27的新环境并安装Python版本2.7。您可以在该行中添加参数以默认情况下安装其他软件包,也可以只是从头开始。该环境将自动激活,只需在命令行中键入deactivate(windows)或source deactivate(linux,osx)即可停用。要在以后激活,请键入activate Python27(windows)或source activate Python27(linux,osx)。如果您选择采用那条路线,我建议您阅读Anaconda中的管理环境文档。

更新资料

conda4.6版开始,您现在可以使用conda activateconda deactivate。采用source现在已被弃用,最终将被删除。

I use both depending on who in my department I am helping (Some people prefer 2.7, others 3.5). Anyway, I use Anaconda and my default installation is 3.5. I use environments for other versions of python, packages, etc.. So for example, when I wanted to start using python 2.7 I ran:

 conda create -n Python27 python=2.7

This creates a new environment named Python27 and installs Python version 2.7. You can add arguments to that line for installing other packages by default or just start from scratch. The environment will automatically activate, to deactivate simply type deactivate (windows) or source deactivate (linux, osx) in the command line. To activate in the future type activate Python27 (windows) or source activate Python27 (linux, osx). I would recommend reading the documentation for Managing Environments in Anaconda, if you choose to take that route.

Update

As of conda version 4.6 you can now use conda activate and conda deactivate. The use of source is now deprecated and will eventually be removed.


回答 2

是的你可以。

您不必都下载两个Anaconda。

只有您需要下载Anaconda版本之一,并且需要激活其他版本的Anaconda python。

如果您拥有Python 3,则可以这样设置Python 2内核;

python2 -m pip install ipykernel

python2 -m ipykernel install --user

如果您有Python 2,

python3 -m pip install ipykernel

python3 -m ipykernel install --user

然后,您将能够看到两个版本的Python!

如果您正在使用Anaconda Spyder,则应在此处交换版本:

如果您使用的是木星,请在这里检查:

注意:如果安装后Jupiter或Anaconda已打开,则需要重新启动。然后您将能够看到。

Yes you can.

You don’t have to download both Anaconda.

Only you need to download one of the version of Anaconda and need activate other version of Anaconda python.

If you have Python 3, you can set up a Python 2 kernel like this;

python2 -m pip install ipykernel

python2 -m ipykernel install --user

If you have Python 2,

python3 -m pip install ipykernel

python3 -m ipykernel install --user

Then you will be able to see both version of Python!

If you are using Anaconda Spyder then you should swap version here:

If you are using Jupiter then check here:

Note: If your Jupiter or Anaconda already open after installation you need to restart again. Then you will be able to see.


回答 3

我已经安装了python 2.7.13和3.6.2。首先为python 3安装Anaconda,然后可以使用conda语法获得2.7。我的安装使用了:conda create -n py27 python = 2.7.13 anaconda

I have python 2.7.13 and 3.6.2 both installed. Install Anaconda for python 3 first and then you can use conda syntax to get 2.7. My install used: conda create -n py27 python=2.7.13 anaconda


回答 4

是的,可以同时安装两个版本。如今,实际上已经很期待了。2.7中编写了很多东西,但是3.5正在成为规范。我建议您尽快将所有python更新到3.5。

Yes, It should be alright to have both versions installed. It’s actually pretty much expected nowadays. A lot of stuff is written in 2.7, but 3.5 is becoming the norm. I would recommend updating all your python to 3.5 ASAP, though.


回答 5

Anaconda是根据您的要求制造的。它也是环境经理。它分离出环境。之所以这样做,是因为较新/不稳定的宿主语言版本不支持稳定和旧版软件包。因此,需要一种可以在同一台计算机上分离和管理这些版本的软件,而无需重新安装或卸载单个主机编程语言/环境。

您可以在Anaconda文档中找到环境的创建/删除。

希望这会有所帮助。

Anaconda is made for the purpose you are asking. It is also an environment manager. It separates out environments. It was made because stable and legacy packages were not supported with newer/unstable versions of host languages; therefore a software was required that could separate and manage these versions on the same machine without the need to reinstall or uninstall individual host programming languages/environments.

You can find creation/deletion of environments in the Anaconda documentation.

Hope this helped.


在列表中的特定索引处插入元素,然后返回更新后的列表

问题:在列表中的特定索引处插入元素,然后返回更新后的列表

我有这个:

>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]

>>> print a.insert(2, 3)
None

>>> print a
[1, 2, 3, 4]

>>> b = a.insert(3, 6)
>>> print b
None

>>> print a
[1, 2, 3, 6, 4]

有没有一种方法可以获取更新的列表作为结果,而不是就地更新原始列表?

I have this:

>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]

>>> print a.insert(2, 3)
None

>>> print a
[1, 2, 3, 4]

>>> b = a.insert(3, 6)
>>> print b
None

>>> print a
[1, 2, 3, 6, 4]

Is there a way I can get the updated list as the result, instead of updating the original list in place?


回答 0

l.insert(index, obj)实际上不返回任何东西。它只是更新列表。

正如ATO所说,您可以做到b = a[:index] + [obj] + a[index:]。但是,另一种方法是:

a = [1, 2, 4]
b = a[:]
b.insert(2, 3)

l.insert(index, obj) doesn’t actually return anything. It just updates the list.

As ATO said, you can do b = a[:index] + [obj] + a[index:]. However, another way is:

a = [1, 2, 4]
b = a[:]
b.insert(2, 3)

回答 1

最高效的方法

您也可以使用列表中的切片索引插入元素。例如:

>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]

在给定索引处将多个元素一起插入,您要做的就是使用list要插入的多个元素中的一个。例如:

>>> a = [1, 2, 4]
>>> insert_at = 2   # Index starting from which multiple elements will be inserted

# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]

>>> a[insert_at:insert_at] = insert_elements
>>> a   # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]

使用列表理解的替代方法 (但性能很慢)

作为替代方案,它可以使用来实现清单理解enumerate过。(但是请不要这样做。这只是为了说明)

>>> a = [1, 2, 4]
>>> insert_at = 2

>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]

所有解决方案的性能比较

以下timeit是所有答案与Python 3.4.5的1000个元素列表的比较:

  • 使用切片插入的地雷解答 -最快(每个循环3.08微秒)

     mquadri$ python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
     100000 loops, best of 3: 3.08 µsec per loop
  • ATOzTOA接受的基于切片列表合并的答案 -秒(每个循环6.71微秒)

     mquadri$ python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
     100000 loops, best of 3: 6.71 µsec per loop
  • 鲁希·潘查尔(Rushy Panchal)的票数最多,答案list.insert(...)-第三(每个循环26.5 微秒

     python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
     10000 loops, best of 3: 26.5 µsec per loop
  • 我的回答列表理解enumerate四- (每圈168微秒很慢)

     mquadri$ python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
     10000 loops, best of 3: 168 µsec per loop

Most performance efficient approach

You may also insert the element using the slice indexing in the list. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]

For inserting multiple elements together at a given index, all you need to do is to use a list of multiple elements that you want to insert. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2   # Index starting from which multiple elements will be inserted

# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]

>>> a[insert_at:insert_at] = insert_elements
>>> a   # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]

Alternative using list comprehension (but very slow in terms of performance):

As an alternative, it can be achieved using list comprehension with enumerate too. (But please don’t do it this way. It is just for illustration):

>>> a = [1, 2, 4]
>>> insert_at = 2

>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]

Performance comparison of all solutions

Here’s the timeit comparison of all the answers with list of 1000 elements for Python 3.4.5:

  • Mine answer using sliced insertion – Fastest (3.08 µsec per loop)

     mquadri$ python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
     100000 loops, best of 3: 3.08 µsec per loop
    
  • ATOzTOA’s accepted answer based on merge of sliced lists – Second (6.71 µsec per loop)

     mquadri$ python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
     100000 loops, best of 3: 6.71 µsec per loop
    
  • Rushy Panchal’s answer with most votes using list.insert(...)– Third (26.5 usec per loop)

     python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
     10000 loops, best of 3: 26.5 µsec per loop
    
  • My answer with List Comprehension and enumerate – Fourth (very slow with 168 µsec per loop)

     mquadri$ python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
     10000 loops, best of 3: 168 µsec per loop
    

回答 2

我得到的最短信息: b = a[:2] + [3] + a[2:]

>>>
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> b = a[:2] + [3] + a[2:]
>>> print a
[1, 2, 4]
>>> print b
[1, 2, 3, 4]

The shortest I got: b = a[:2] + [3] + a[2:]

>>>
>>> a = [1, 2, 4]
>>> print a
[1, 2, 4]
>>> b = a[:2] + [3] + a[2:]
>>> print a
[1, 2, 4]
>>> print b
[1, 2, 3, 4]

回答 3

最干净的方法是复制列表,然后将对象插入副本。在Python 3上,可以通过list.copy以下方式完成:

new = old.copy()
new.insert(index, value)

在Python 2上,可以通过new = old[:](通过python 3也可以)复制列表。

在性能方面,与其他建议的方法没有区别:

$ python --version
Python 3.8.1
$ python -m timeit -s "a = list(range(1000))" "b = a.copy(); b.insert(500, 3)"
100000 loops, best of 5: 2.84 µsec per loop
$ python -m timeit -s "a = list(range(1000))" "b = a.copy(); b[500:500] = (3,)"
100000 loops, best of 5: 2.76 µsec per loop

The cleanest approach is to copy the list and then insert the object into the copy. On Python 3 this can be done via list.copy:

new = old.copy()
new.insert(index, value)

On Python 2 copying the list can be achieved via new = old[:] (this also works on Python 3).

In terms of performance there is no difference to other proposed methods:

$ python --version
Python 3.8.1
$ python -m timeit -s "a = list(range(1000))" "b = a.copy(); b.insert(500, 3)"
100000 loops, best of 5: 2.84 µsec per loop
$ python -m timeit -s "a = list(range(1000))" "b = a.copy(); b[500:500] = (3,)"
100000 loops, best of 5: 2.76 µsec per loop

回答 4

使用Python列表insert()方法。用法:

#句法

insert()方法的语法-

list.insert(index, obj)

#参数

  • index-这是需要在其中插入对象obj的索引。
  • obj-这是要插入给定列表的对象。

#Return Value此方法不返回任何值,但会将给定元素插入给定索引。

例:

a = [1,2,4,5]

a.insert(2,3)

print(a)

退货 [1, 2, 3, 4, 5]

Use the Python list insert() method. Usage:

#Syntax

The syntax for the insert() method −

list.insert(index, obj)

#Parameters

  • index − This is the Index where the object obj need to be inserted.
  • obj − This is the Object to be inserted into the given list.

#Return Value This method does not return any value, but it inserts the given element at the given index.

Example:

a = [1,2,4,5]

a.insert(2,3)

print(a)

Returns [1, 2, 3, 4, 5]


将Python字典转换为JSON数组

问题:将Python字典转换为JSON数组

目前,我有这本词典,使用印刷pprint

{'AlarmExTempHum': '\x00\x00\x00\x00\x00\x00\x00\x00',  
'AlarmIn': 0,  
'AlarmOut': '\x00\x00',  
'AlarmRain': 0,  
'AlarmSoilLeaf': '\x00\x00\x00\x00',  
'BarTrend': 60,  
'BatteryStatus': 0,  
'BatteryVolts': 4.751953125,  
'CRC': 55003,
'EOL': '\n\r',
'ETDay': 0,
'ETMonth': 0,
'ETYear': 0,
'ExtraHum1': None,
'ExtraHum2': None,
'ExtraHum3': None,
'ExtraHum4': None,
'ExtraHum5': None,
'ExtraHum6': None,
'ExtraHum7': None,
'ExtraTemp1': None,
'ExtraTemp2': None,
'ExtraTemp3': None,
'ExtraTemp4': None,
'ExtraTemp5': None,
'ExtraTemp6': None,
'ExtraTemp7': None,
'ForecastIcon': 2,
'ForecastRuleNo': 122,
'HumIn': 31,
'HumOut': 94,
'LOO': 'LOO',
'LeafTemps': '\xff\xff\xff\xff',
'LeafWetness': '\xff\xff\xff\x00',
'NextRec': 37,
'PacketType': 0,
'Pressure': 995.9363359295631,
'RainDay': 0.0,
'RainMonth': 0.0,
'RainRate': 0.0,
'RainStorm': 0.0,
'RainYear': 2.8,
'SoilMoist': '\xff\xff\xff\xff',
'SoilTemps': '\xff\xff\xff\xff',
'SolarRad': None,
'StormStartDate': '2127-15-31',
'SunRise': 849,
'SunSet': 1611,
'TempIn': 21.38888888888889,
'TempOut': 0.8888888888888897,
'UV': None,
'WindDir': 219,
'WindSpeed': 3.6,
'WindSpeed10Min': 3.6}

当我这样做时:

import json
d = (my dictionary above)
jsonarray = json.dumps(d)

我收到此错误: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

Currently I have this dictionary, printed using pprint:

{'AlarmExTempHum': '\x00\x00\x00\x00\x00\x00\x00\x00',  
'AlarmIn': 0,  
'AlarmOut': '\x00\x00',  
'AlarmRain': 0,  
'AlarmSoilLeaf': '\x00\x00\x00\x00',  
'BarTrend': 60,  
'BatteryStatus': 0,  
'BatteryVolts': 4.751953125,  
'CRC': 55003,
'EOL': '\n\r',
'ETDay': 0,
'ETMonth': 0,
'ETYear': 0,
'ExtraHum1': None,
'ExtraHum2': None,
'ExtraHum3': None,
'ExtraHum4': None,
'ExtraHum5': None,
'ExtraHum6': None,
'ExtraHum7': None,
'ExtraTemp1': None,
'ExtraTemp2': None,
'ExtraTemp3': None,
'ExtraTemp4': None,
'ExtraTemp5': None,
'ExtraTemp6': None,
'ExtraTemp7': None,
'ForecastIcon': 2,
'ForecastRuleNo': 122,
'HumIn': 31,
'HumOut': 94,
'LOO': 'LOO',
'LeafTemps': '\xff\xff\xff\xff',
'LeafWetness': '\xff\xff\xff\x00',
'NextRec': 37,
'PacketType': 0,
'Pressure': 995.9363359295631,
'RainDay': 0.0,
'RainMonth': 0.0,
'RainRate': 0.0,
'RainStorm': 0.0,
'RainYear': 2.8,
'SoilMoist': '\xff\xff\xff\xff',
'SoilTemps': '\xff\xff\xff\xff',
'SolarRad': None,
'StormStartDate': '2127-15-31',
'SunRise': 849,
'SunSet': 1611,
'TempIn': 21.38888888888889,
'TempOut': 0.8888888888888897,
'UV': None,
'WindDir': 219,
'WindSpeed': 3.6,
'WindSpeed10Min': 3.6}

When I do this:

import json
d = (my dictionary above)
jsonarray = json.dumps(d)

I get this error: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte


回答 0

如果您可以在json中使用不可打印的符号,请添加ensure_ascii=Falsedumps通话中。

>>> json.dumps(your_data, ensure_ascii=False)

如果ensure_ascii是假的,那么返回值将是一个 unicode实例受到正常的Python strunicode 强制规则,而不是被转义为ASCII str

If you are fine with non-printable symbols in your json, then add ensure_ascii=False to dumps call.

>>> json.dumps(your_data, ensure_ascii=False)

If ensure_ascii is false, then the return value will be a unicode instance subject to normal Python str to unicode coercion rules instead of being escaped to an ASCII str.


回答 1

sure_ascii = False实际上只会将问题推迟到解码阶段:

>>> dict2 = {'LeafTemps': '\xff\xff\xff\xff',}
>>> json1 = json.dumps(dict2, ensure_ascii=False)
>>> print(json1)
{"LeafTemps": "����"}
>>> json.loads(json1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 328, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 381, in raw_decode
    obj, end = self.scan_once(s, idx)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

最终,您无法将原始字节存储在JSON文档中,因此,您将需要使用一些方法来明确地将任意字节序列编码为ASCII字符串-例如base64。

>>> import json
>>> from base64 import b64encode, b64decode
>>> my_dict = {'LeafTemps': '\xff\xff\xff\xff',} 
>>> my_dict['LeafTemps'] = b64encode(my_dict['LeafTemps'])
>>> json.dumps(my_dict)
'{"LeafTemps": "/////w=="}'
>>> json.loads(json.dumps(my_dict))
{u'LeafTemps': u'/////w=='}
>>> new_dict = json.loads(json.dumps(my_dict))
>>> new_dict['LeafTemps'] = b64decode(new_dict['LeafTemps'])
>>> print new_dict
{u'LeafTemps': '\xff\xff\xff\xff'}

ensure_ascii=False really only defers the issue to the decoding stage:

>>> dict2 = {'LeafTemps': '\xff\xff\xff\xff',}
>>> json1 = json.dumps(dict2, ensure_ascii=False)
>>> print(json1)
{"LeafTemps": "����"}
>>> json.loads(json1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 328, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 381, in raw_decode
    obj, end = self.scan_once(s, idx)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

Ultimately you can’t store raw bytes in a JSON document, so you’ll want to use some means of unambiguously encoding a sequence of arbitrary bytes as an ASCII string – such as base64.

>>> import json
>>> from base64 import b64encode, b64decode
>>> my_dict = {'LeafTemps': '\xff\xff\xff\xff',} 
>>> my_dict['LeafTemps'] = b64encode(my_dict['LeafTemps'])
>>> json.dumps(my_dict)
'{"LeafTemps": "/////w=="}'
>>> json.loads(json.dumps(my_dict))
{u'LeafTemps': u'/////w=='}
>>> new_dict = json.loads(json.dumps(my_dict))
>>> new_dict['LeafTemps'] = b64decode(new_dict['LeafTemps'])
>>> print new_dict
{u'LeafTemps': '\xff\xff\xff\xff'}

回答 2

如果您使用的是Python 2,请不要忘记在脚本的第一行添加UTF-8文件编码注释。

# -*- coding: UTF-8 -*-

这将解决一些Unicode问题,并使您的生活更轻松。

If you use Python 2, don’t forget to add the UTF-8 file encoding comment on the first line of your script.

# -*- coding: UTF-8 -*-

This will fix some Unicode problems and make your life easier.


回答 3

我使用的一种可能的解决方案是使用python3。它似乎解决了许多utf问题。

很抱歉无法提供最新答案,但将来可能会对您有所帮助。

例如,

#!/usr/bin/env python3
import json
# your code follows

One possible solution that I use is to use python3. It seems to solve many utf issues.

Sorry for the late answer, but it may help people in the future.

For example,

#!/usr/bin/env python3
import json
# your code follows

没有名为setuptools的模块

问题:没有名为setuptools的模块

我想安装twilio的安装文件。通过给定命令安装它时,出现错误:

没有名为setuptools的模块。

您能告诉我该怎么办吗?

我在用 python 2.7

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Python27>python D:\test\twilio-twilio-python-26f6707\setup.py install
Traceback (most recent call last):
  File "D:\test\twilio-twilio-python-26f6707\setup.py", line 2, in <module>
    from setuptools import setup, find_packages
ImportError: No module named setuptools

I want to install setup file of twilio. When I install it through given command it is given me an error:

No module named setuptools.

Could you please let me know what should I do?

I am using python 2.7

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Python27>python D:\test\twilio-twilio-python-26f6707\setup.py install
Traceback (most recent call last):
  File "D:\test\twilio-twilio-python-26f6707\setup.py", line 2, in <module>
    from setuptools import setup, find_packages
ImportError: No module named setuptools

回答 0

安装并重setuptools试。

尝试命令:

sudo apt-get install -y python-setuptools

Install setuptools and try again.

try command:

sudo apt-get install -y python-setuptools

回答 1

对于ubuntu用户,由于未在系统范围内安装setuptool,因此可能会出现此错误。只需使用以下命令安装setuptool:

sudo apt-get install -y python-setuptools

对于python3:

sudo apt-get install -y python3-setuptools

之后,请使用

sudo python setup.py install

就这样。

For ubuntu users, this error may arise because setuptool is not installed system-wide. Simply install setuptool using the command:

sudo apt-get install -y python-setuptools

For python3:

sudo apt-get install -y python3-setuptools

After that, install your package again normally, using

sudo python setup.py install

That’s all.


回答 2

对于Python运行此命令

apt-get install -y python-setuptools

对于Python 3。

apt-get install -y python3-setuptools

For Python Run This Command

apt-get install -y python-setuptools

For Python 3.

apt-get install -y python3-setuptools

回答 3

PyPA推荐的用于安装和管理Python包的工具pippip包含在Python 3.4(PEP 453)中,但是对于较旧的版本,这是安装方法(在Windows上使用Python 3.3):

下载https://bootstrap.pypa.io/get-pip.py

>c:\Python33\python.exe get-pip.py
Downloading/unpacking pip
Downloading/unpacking setuptools
Installing collected packages: pip, setuptools
Successfully installed pip setuptools
Cleaning up...

用法示例:

>c:\Python33\Scripts\pip.exe install pymysql
Downloading/unpacking pymysql
Installing collected packages: pymysql
Successfully installed pymysql
Cleaning up...

在您的情况下,将是这样(似乎pip缓存独立于Python版本):

C:\Python27>python.exe \code\Python\get-pip.py
Requirement already up-to-date: pip in c:\python27\lib\site-packages
Collecting wheel
  Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB)
    100% |################################| 69kB 255kB/s
Installing collected packages: wheel
Successfully installed wheel-0.29.0

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install twilio
Collecting twilio
  Using cached twilio-5.3.0.tar.gz
Collecting httplib2>=0.7 (from twilio)
  Using cached httplib2-0.9.2.tar.gz
Collecting six (from twilio)
  Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pytz (from twilio)
  Using cached pytz-2015.7-py2.py3-none-any.whl
Building wheels for collected packages: twilio, httplib2
  Running setup.py bdist_wheel for twilio ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e0\f2\a7\c57f6d153c440b93bd24c1243123f276dcacbf43cc43b7f906
  Running setup.py bdist_wheel for httplib2 ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e1\a3\05\e66aad1380335ee0a823c8f1b9006efa577236a24b3cb1eade
Successfully built twilio httplib2
Installing collected packages: httplib2, six, pytz, twilio
Successfully installed httplib2-0.9.2 pytz-2015.7 six-1.10.0 twilio-5.3.0

The PyPA recommended tool for installing and managing Python packages is pip. pip is included with Python 3.4 (PEP 453), but for older versions here’s how to install it (on Windows, using Python 3.3):

Download https://bootstrap.pypa.io/get-pip.py

>c:\Python33\python.exe get-pip.py
Downloading/unpacking pip
Downloading/unpacking setuptools
Installing collected packages: pip, setuptools
Successfully installed pip setuptools
Cleaning up...

Sample usage:

>c:\Python33\Scripts\pip.exe install pymysql
Downloading/unpacking pymysql
Installing collected packages: pymysql
Successfully installed pymysql
Cleaning up...

In your case it would be this (it appears that pip caches independent of Python version):

C:\Python27>python.exe \code\Python\get-pip.py
Requirement already up-to-date: pip in c:\python27\lib\site-packages
Collecting wheel
  Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB)
    100% |################################| 69kB 255kB/s
Installing collected packages: wheel
Successfully installed wheel-0.29.0

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install twilio
Collecting twilio
  Using cached twilio-5.3.0.tar.gz
Collecting httplib2>=0.7 (from twilio)
  Using cached httplib2-0.9.2.tar.gz
Collecting six (from twilio)
  Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pytz (from twilio)
  Using cached pytz-2015.7-py2.py3-none-any.whl
Building wheels for collected packages: twilio, httplib2
  Running setup.py bdist_wheel for twilio ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e0\f2\a7\c57f6d153c440b93bd24c1243123f276dcacbf43cc43b7f906
  Running setup.py bdist_wheel for httplib2 ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e1\a3\05\e66aad1380335ee0a823c8f1b9006efa577236a24b3cb1eade
Successfully built twilio httplib2
Installing collected packages: httplib2, six, pytz, twilio
Successfully installed httplib2-0.9.2 pytz-2015.7 six-1.10.0 twilio-5.3.0

回答 4

对于python3是:

sudo apt-get install -y python3-setuptools

For python3 is:

sudo apt-get install -y python3-setuptools

为什么在Python 2.7中自愿使用印刷括号?

问题:为什么在Python 2.7中自愿使用印刷括号?

在Python 2.7中,以下两者将执行相同的操作

print("Hello, World!") # Prints "Hello, World!"

print "Hello, World!" # Prints "Hello, World!"

但是以下内容不会

print("Hello,", "World!") # Prints the tuple: ("Hello,", "World!")

print "Hello,", "World!" # Prints the words "Hello, World!"

在Python 3.x中,括号print是强制性的,本质上使其成为一个函数,但是在2.7中,两者都可以使用不同的结果。我print在Python 2.7中还应该了解什么?

In Python 2.7 both the following will do the same

print("Hello, World!") # Prints "Hello, World!"

print "Hello, World!" # Prints "Hello, World!"

However the following will not

print("Hello,", "World!") # Prints the tuple: ("Hello,", "World!")

print "Hello,", "World!" # Prints the words "Hello, World!"

In Python 3.x parenthesis on print is mandatory, essentially making it a function, but in 2.7 both will work with differing results. What else should I know about print in Python 2.7?


回答 0

在Python 2.x print中,实际上是一个特殊的语句,而不是一个函数*。

这也是为什么不能像这样使用的原因: lambda x: print x

请注意,(expr)它不会创建元组(结果为expr),但,会创建。在方寸之间这种可能的结果print (x),并print (x, y)在Python 2.7

(1)   # 1 -- no tuple Mister!
(1,)  # (1,)
(1,2) # (1, 2)
1,2   # 1 2 -- no tuple and no parenthesis :) [See below for print caveat.]

但是,由于print是Python 2.x中的特殊语法语句/语法构造,因此,如果没有括号,它将,以特殊方式处理,并且不会创建元组。对print语句的这种特殊处理使它无论是否有尾随都可以采取不同的行动,

快乐的编码。


* printPython 2中的此行为可以更改为Python 3:

from __future__ import print_function

In Python 2.x print is actually a special statement and not a function*.

This is also why it can’t be used like: lambda x: print x

Note that (expr) does not create a Tuple (it results in expr), but , does. This likely results in the confusion between print (x) and print (x, y) in Python 2.7

(1)   # 1 -- no tuple Mister!
(1,)  # (1,)
(1,2) # (1, 2)
1,2   # 1 2 -- no tuple and no parenthesis :) [See below for print caveat.]

However, since print is a special syntax statement/grammar construct in Python 2.x then, without the parenthesis, it treats the ,‘s in a special manner – and does not create a Tuple. This special treatment of the print statement enables it to act differently if there is a trailing , or not.

Happy coding.


*This print behavior in Python 2 can be changed to that of Python 3:

from __future__ import print_function

回答 1

这一切都非常简单,与向前或向后兼容性无关。

print在版本3之前的所有Python版本中,该语句的一般形式为:

print expr1, expr2, ... exprn

(依次对每个表达式求值,将其转换为字符串并在它们之间显示一个空格。)

但是请记住,在表达式周围加上括号仍然是相同的表达式。

因此,您也可以这样写:

print (expr1), (expr2), ... (expr3)

这与调用函数无关。

It’s all very simple and has nothing to do with forward or backward compatibility.

The general form for the print statement in all Python versions before version 3 is:

print expr1, expr2, ... exprn

(Each expression in turn is evaluated, converted to a string and displayed with a space between them.)

But remember that putting parentheses around an expression is still the same expression.

So you can also write this as:

print (expr1), (expr2), ... (expr3)

This has nothing to do with calling a function.


回答 2

在谈到UTF-8时,我们有一个有趣的副作用。

>> greek = dict( dog="σκύλος", cat="γάτα" )
>> print greek['dog'], greek['cat']
σκύλος γάτα
>> print (greek['dog'], greek['cat'])
('\xcf\x83\xce\xba\xcf\x8d\xce\xbb\xce\xbf\xcf\x82', '\xce\xb3\xce\xac\xcf\x84\xce\xb1')

最后打印的是带有十六进制字节值的元组。

Here we have interesting side effect when it comes to UTF-8.

>> greek = dict( dog="σκύλος", cat="γάτα" )
>> print greek['dog'], greek['cat']
σκύλος γάτα
>> print (greek['dog'], greek['cat'])
('\xcf\x83\xce\xba\xcf\x8d\xce\xbb\xce\xbf\xcf\x82', '\xce\xb3\xce\xac\xcf\x84\xce\xb1')

The last print is tuple with hexadecimal byte values.


回答 3

基本上在Python 3之前的Python中,print是一个特殊的语句,如果作为参数获取,则打印所有字符串。因此,print "foo","bar"仅表示“先打印’foo’,再打印’bar’”。这样做的问题是,很容易将print当作一个函数来使用,而Python语法对此却模棱两可,因为它(a,b)是一个包含ab只是foo(a,b)对两个参数的函数的调用的元组。

因此,他们对3进行了不兼容的更改,以减少程序的歧义性和规则性。

(实际上,我认为2.7的行为与2.6的行为相同,但我不确定。)

Basically in Python before Python 3, print was a special statement that printed all the strings if got as arguments. So print "foo","bar" simply meant “print ‘foo’ followed by ‘bar'”. The problem with that was it was tempting to act as if print were a function, and the Python grammar is ambiguous on that, since (a,b) is a tuple containing a and b but foo(a,b) is a call to a function of two arguments.

So they made the incompatible change for 3 to make programs less ambiguous and more regular.

(Actually, I think 2.7 behaves as 2.6 did on this, but I’m not certain.)


将列表的Python列表写入csv文件

问题:将列表的Python列表写入csv文件

我有一长串以下形式的清单-

a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]]

即列表中的值是不同的类型-浮点数,整数,字符串。如何将其写入csv文件,以便输出的csv文件看起来像

1.2,abc,3
1.2,werew,4
.
.
.
1.4,qew,2

I have a long list of lists of the following form —

a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]]

i.e. the values in the list are of different types — float,int, strings.How do I write it into a csv file so that my output csv file looks like

1.2,abc,3
1.2,werew,4
.
.
.
1.4,qew,2

回答 0

Python的内置CSV模块可以轻松处理此问题:

import csv

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(a)

假设您的问题中的清单定义为a。您可以通过各种可选参数来调整输出CSV的确切格式,csv.writer()如上面链接的库参考页中所述。

Python 3更新

import csv

with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(a)

Python’s built-in CSV module can handle this easily:

import csv

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(a)

This assumes your list is defined as a, as it is in your question. You can tweak the exact format of the output CSV via the various optional parameters to csv.writer() as documented in the library reference page linked above.

Update for Python 3

import csv

with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(a)

回答 1

您可以使用pandas

In [1]: import pandas as pd

In [2]: a = [[1.2,'abc',3],[1.2,'werew',4],[1.4,'qew',2]]

In [3]: my_df = pd.DataFrame(a)

In [4]: my_df.to_csv('my_csv.csv', index=False, header=False)

You could use pandas:

In [1]: import pandas as pd

In [2]: a = [[1.2,'abc',3],[1.2,'werew',4],[1.4,'qew',2]]

In [3]: my_df = pd.DataFrame(a)

In [4]: my_df.to_csv('my_csv.csv', index=False, header=False)

回答 2

import csv
with open(file_path, 'a') as outcsv:   
    #configure writer to write standard csv file
    writer = csv.writer(outcsv, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
    writer.writerow(['number', 'text', 'number'])
    for item in list:
        #Write item to outcsv
        writer.writerow([item[0], item[1], item[2]])

官方文档:http : //docs.python.org/2/library/csv.html

import csv
with open(file_path, 'a') as outcsv:   
    #configure writer to write standard csv file
    writer = csv.writer(outcsv, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
    writer.writerow(['number', 'text', 'number'])
    for item in list:
        #Write item to outcsv
        writer.writerow([item[0], item[1], item[2]])

official docs: http://docs.python.org/2/library/csv.html


回答 3

如果出于某种原因你想要做手工(不使用模块一样csvpandasnumpy等):

with open('myfile.csv','w') as f:
    for sublist in mylist:
        for item in sublist:
            f.write(item + ',')
        f.write('\n')

当然,滚动自己的版本可能容易出错且效率低下……这通常就是为什么要使用该模块的原因。但是有时编写自己的内容可以帮助您了解它们的工作原理,有时则更容易。

If for whatever reason you wanted to do it manually (without using a module like csv,pandas,numpy etc.):

with open('myfile.csv','w') as f:
    for sublist in mylist:
        for item in sublist:
            f.write(item + ',')
        f.write('\n')

Of course, rolling your own version can be error-prone and inefficient … that’s usually why there’s a module for that. But sometimes writing your own can help you understand how they work, and sometimes it’s just easier.


回答 4

在我很大的列表中使用csv.writer花费了很长时间。我决定使用熊猫,它更快,更容易控制和理解:

 import pandas

 yourlist = [[...],...,[...]]
 pd = pandas.DataFrame(yourlist)
 pd.to_csv("mylist.csv")

好的部分,您可以更改一些内容以制作更好的csv文件:

 yourlist = [[...],...,[...]]
 columns = ["abcd","bcde","cdef"] #a csv with 3 columns
 index = [i[0] for i in yourlist] #first element of every list in yourlist
 not_index_list = [i[1:] for i in yourlist]
 pd = pandas.DataFrame(not_index_list, columns = columns, index = index)

 #Now you have a csv with columns and index:
 pd.to_csv("mylist.csv")

Using csv.writer in my very large list took quite a time. I decided to use pandas, it was faster and more easy to control and understand:

 import pandas

 yourlist = [[...],...,[...]]
 pd = pandas.DataFrame(yourlist)
 pd.to_csv("mylist.csv")

The good part you can change somethings to make a better csv file:

 yourlist = [[...],...,[...]]
 columns = ["abcd","bcde","cdef"] #a csv with 3 columns
 index = [i[0] for i in yourlist] #first element of every list in yourlist
 not_index_list = [i[1:] for i in yourlist]
 pd = pandas.DataFrame(not_index_list, columns = columns, index = index)

 #Now you have a csv with columns and index:
 pd.to_csv("mylist.csv")

回答 5

Ambers的解决方案也适用于numpy数组:

from pylab import *
import csv

array_=arange(0,10,1)
list_=[array_,array_*2,array_*3]
with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(list_)

Ambers’s solution also works well for numpy arrays:

from pylab import *
import csv

array_=arange(0,10,1)
list_=[array_,array_*2,array_*3]
with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(list_)

回答 6

如果您不想为此导入csv模块,则可以仅使用Python内置组件将列表列表写入csv文件

with open("output.csv", "w") as f:
    for row in a:
        f.write("%s\n" % ','.join(str(col) for col in row))

If you don’t want to import csv module for that, you can write a list of lists to a csv file using only Python built-ins

with open("output.csv", "w") as f:
    for row in a:
        f.write("%s\n" % ','.join(str(col) for col in row))

回答 7

确保lineterinator='\n'创建创作者时注明;否则,当数据源来自其他csv文件时,每条数据行之后可能会在文件中写入多余的空行…

这是我的解决方案:

with open('csvfile', 'a') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter='    ',quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
for i in range(0, len(data)):
    spamwriter.writerow(data[i])

Make sure to indicate lineterinator='\n' when create the writer; otherwise, an extra empty line might be written into file after each data line when data sources are from other csv file…

Here is my solution:

with open('csvfile', 'a') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter='    ',quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
for i in range(0, len(data)):
    spamwriter.writerow(data[i])

回答 8

如何将列表列表转储到pickle中并使用pickle模块恢复呢?很方便

>>> import pickle
>>> 
>>> mylist = [1, 'foo', 'bar', {1, 2, 3}, [ [1,4,2,6], [3,6,0,10]]]
>>> with open('mylist', 'wb') as f:
...     pickle.dump(mylist, f) 


>>> with open('mylist', 'rb') as f:
...      mylist = pickle.load(f)
>>> mylist
[1, 'foo', 'bar', {1, 2, 3}, [[1, 4, 2, 6], [3, 6, 0, 10]]]
>>> 

How about dumping the list of list into pickle and restoring it with pickle module? It’s quite convenient.

>>> import pickle
>>> 
>>> mylist = [1, 'foo', 'bar', {1, 2, 3}, [ [1,4,2,6], [3,6,0,10]]]
>>> with open('mylist', 'wb') as f:
...     pickle.dump(mylist, f) 


>>> with open('mylist', 'rb') as f:
...      mylist = pickle.load(f)
>>> mylist
[1, 'foo', 'bar', {1, 2, 3}, [[1, 4, 2, 6], [3, 6, 0, 10]]]
>>> 

回答 9

在csv.writer函数中使用换行符跟随示例时,出现错误消息。以下代码对我有用。

 with open(strFileName, "w") as f:
    writer = csv.writer(f, delimiter=',',  quoting=csv.QUOTE_MINIMAL)
    writer.writerows(result)

I got an error message when following the examples with a newline parameter in the csv.writer function. The following code worked for me.

 with open(strFileName, "w") as f:
    writer = csv.writer(f, delimiter=',',  quoting=csv.QUOTE_MINIMAL)
    writer.writerows(result)

无法安装Python软件包[SSL:TLSV1_ALERT_PROTOCOL_VERSION]

问题:无法安装Python软件包[SSL:TLSV1_ALERT_PROTOCOL_VERSION]

我正在尝试使用安装Python库pip,并收到SSL错误:

~/projects/base  pre-master±  pip install xdict

Collecting xdict
  Could not fetch URL https://pypi.python.org/simple/xdict/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) - skipping
  Could not find a version that satisfies the requirement xdict (from versions: )
No matching distribution found for xdict

点子版本:点子9.0.1

如何解决此错误?

I am trying to install a Python library using pip, getting an SSL error:

~/projects/base  pre-master±  pip install xdict

Collecting xdict
  Could not fetch URL https://pypi.python.org/simple/xdict/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) - skipping
  Could not find a version that satisfies the requirement xdict (from versions: )
No matching distribution found for xdict

pip version: pip 9.0.1

How do I fix this error?


回答 0

升级点如下:

curl https://bootstrap.pypa.io/get-pip.py | python

注意:sudo python如果不在虚拟环境中,则可能需要使用以上内容。

(请注意,pip使用pipie进行pip install --upgrade pip升级也不会正确升级。这只是一个鸡与蛋的问题。pip除非使用TLS> = 1.2,否则它将无法正常工作。)

本详细答案所述,这是由于最近对pip的TLS弃用。Python.org网站已停止支持 TLS版本1.0和1.1。

从Python状态页面:

已完成 -滚动式电源不足已完成,并且TLSv1.0和TLSv1.1已被禁用。世界标准时间4月11日15:37


对于PyCharm(virtualenv)用户:

  1. 使用Shell运行虚拟环境。(将“ ./venv/bin/activate”替换为您自己的路径)

    source ./venv/bin/activate
  2. 运行升级

    curl https://bootstrap.pypa.io/get-pip.py | python
  3. 重新启动您的PyCharm实例,然后在Preference中检查您的Python解释器。

Upgrade pip as follows:

curl https://bootstrap.pypa.io/get-pip.py | python

Note: You may need to use sudo python above if not in a virtual environment.

(Note that upgrading pip using pip i.e pip install --upgrade pip will also not upgrade it correctly. It’s just a chicken-and-egg issue. pip won’t work unless using TLS >= 1.2.)

As mentioned in this detailed answer, this is due to the recent TLS deprecation for pip. Python.org sites have stopped support for TLS versions 1.0 and 1.1.

From the Python status page:

Completed – The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC


For PyCharm (virtualenv) users:

  1. Run virtual environment with shell. (replace “./venv/bin/activate” to your own path)

    source ./venv/bin/activate
    
  2. Run upgrade

    curl https://bootstrap.pypa.io/get-pip.py | python
    
  3. Restart your PyCharm instance, and check your Python interpreter in Preference.


回答 1

但是,如果curl命令本身因错误而失败,或者即使升级后“ tlsv1警报协议版本”仍然存在pip,则表示操作系统的基础OpenSSL库版本< 1.0.1或Python版本< 2.7.9(或3.4Python 3中的< )不支持较新的TLS 1.2协议这pip需要连接到PyPI中,因为大约一年前。您可以在Python解释器中轻松检查它:

>>> import ssl
>>> ssl.OPENSSL_VERSION
'OpenSSL 0.9.8o 01 Jun 2010'
>>> ssl.PROTOCOL_TLSv1_2
 AttributeError: 'module' object has no attribute 'PROTOCOL_TLSv1_2'

AttributeError(而不是预期的“5”)是指你的Python STDLIB ssl模块,对旧的OpenSSL的lib编译,缺乏对TLSv1.2工作协议(即使OpenSSL库可以或可以在以后更新)的支持。

幸运的是,无需手动升级额外的Python软件包即可解决此问题,而无需升级Python(以及整个系统),详细的逐步指南位于Stackoverflow上

注意,curlpipwget所有依赖于相同的OpenSSL lib中建立SSL连接(使用$ openssl version命令)。从curl版本7.34开始,libcurl支持TLS 1.2 ,但是如果您具有OpenSSL版本1.0.2(或更高版本),则较旧的curl版本应该能够连接。


PS
对于Python 3中,请使用python3pip3无处不在(除非你是在一个VENV / virtualenv中),包括curl从命令上面
$ curl https://bootstrap.pypa.io/get-pip.py | python3 --user

But if the curl command itself fails with error, or “tlsv1 alert protocol version” persists even after upgrading pip, it means your operating system’s underlying OpenSSL library version<1.0.1 or Python version<2.7.9 (or <3.4 in Python 3) do not support the newer TLS 1.2 protocol that pip needs to connect to PyPI since about a year ago. You can easily check it in Python interpreter:

>>> import ssl
>>> ssl.OPENSSL_VERSION
'OpenSSL 0.9.8o 01 Jun 2010'
>>> ssl.PROTOCOL_TLSv1_2
 AttributeError: 'module' object has no attribute 'PROTOCOL_TLSv1_2'

The AttributeError (instead of expected ‘5’) means your Python stdlib ssl module, compiled against old openssl lib, is lacking support for the TLSv1.2 protocol (even if the openssl library can or could be updated later).

Fortunately, it can be solved without upgrading Python (and the whole system), by manually installing extra Python packages — the detailed step-by-step guide is available here on Stackoverflow.

Note, curl and pip and wget all depend on the same OpenSSL lib for establishing SSL connections (use $ openssl version command). libcurl supports TLS 1.2 since curl version 7.34, but older curl versions should be able to connect if you had OpenSSL version 1.0.2 (or later).


P.S.
For Python 3, please use python3 and pip3 everywhere (unless you are in a venv/virtualenv), including the curl command from above:
$ curl https://bootstrap.pypa.io/get-pip.py | python3 --user


回答 2

在OS X上遵循@Anupam的回答后,无论我使用哪种权限运行,都会导致以下错误:

由于环境错误而无法安装软件包:[Errno 13]权限被拒绝:…

最终什么工作是直接从我的浏览器下载一封来自PyPI一个较新的PIP封装(9.0.3) – https://pypi.org/simple/pip/,提取内容,然后PIP本地安装包:

pip install ./pip-9.0.3/

这解决了我的[SSL: TLSV1_ALERT_PROTOCOL_VERSION]错误。

Following @Anupam’s answer on OS X resulted in the following error for me, regardless of permissions I ran it with:

Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: …

What eventually worked was to download a newer pip package (9.0.3) from PyPI directly from my browser – https://pypi.org/simple/pip/, extract the contents, and then pip install the package locally:

pip install ./pip-9.0.3/

This fixed my [SSL: TLSV1_ALERT_PROTOCOL_VERSION] errors.


回答 3

@Anupam的解决方案对我有用。但是,我必须使用sudo并指定虚拟Python环境的确切位置:

curl https://bootstrap.pypa.io/get-pip.py | sudo /Users/{your user name}/{path to python}/bin/python

@Anupam‘s solution worked for me. However, I had to use sudo and specify the exact location of my virtual Python environment:

curl https://bootstrap.pypa.io/get-pip.py | sudo /Users/{your user name}/{path to python}/bin/python

回答 4

为了升级本地版本,我使用了一个轻微的变体:

curl https://bootstrap.pypa.io/get-pip.py | python - --user

如果您按照本要点所述将pip和程序包放在主目录下,则会出现此问题。

To upgrade the local version I used a slight variant:

curl https://bootstrap.pypa.io/get-pip.py | python - --user

This problem arises if you keep your pip and packages under your home directory as described in this gist.


回答 5

以下解决方案为我工作:

brew install python2

它还升级pip到版本1.10.1

The following solution worked for me:

brew install python2

It also upgraded pip to version 1.10.1


回答 6

检查您的TLS版本:

python2 -c "import urllib2,json; print(json.loads(urllib2.urlopen('https://www.howsmyssl.com/a/check').read())['tls_version'])"

如果您的TLS版本低于1.2,则您必须对其进行升级,因为PyPI存储库正处于弃用早期TLS的限制期。

来源- 升级Python的时间:TLS v1.2很快将成为必需

您可以使用以下命令升级TLS版本:

sudo apt-get update && sudo apt-get install openssl libssl-dev

这应该可以解决您的问题。祝好运!

编辑:您可以使用自己的专用python软件包存储库下载软件包,而不管TLS版本如何。 专用Python软件包存储库

Check your TLS version:

python2 -c "import urllib2,json; print(json.loads(urllib2.urlopen('https://www.howsmyssl.com/a/check').read())['tls_version'])"

If your TLS version is less than 1.2 you have to upgrade it since the PyPI repository is on a brownout period of deprecating early TLS.

Source – Time To Upgrade Your Python: TLS v1.2 Will Soon Be Mandatory

You can upgrade the TLS version using the following command:

sudo apt-get update && sudo apt-get install openssl libssl-dev

This should fix your problem. Good luck!

EDIT: You can download packages using your own private python package repository regardless of TLS version. Private Python Package Repository


回答 7

这对我有用。在python之前添加sudo

curl https://bootstrap.pypa.io/get-pip.py |sudo python

This worked for me. Add sudo before python

curl https://bootstrap.pypa.io/get-pip.py |sudo python

回答 8

对于Python2 WIN10用户:

1.彻底卸载python,包括所有文件夹。

2.获取并安装最新的python-2.7.msi(版本2.7.15)

3.步骤2之后,您可能还会发现pip也已安装。

4.现在,如果尚未更改系统的环境,则可以立即使用pip安装软件包。“ tlsv1警报协议版本”将不会出现。

For Python2 WIN10 Users:

1.Uninstall python thoroughly ,include all folders.

2.Fetch and install the lastest python-2.7.msi (ver 2.7.15)

3.After step 2,you may find pip had been installed too.

4.Now ,if your system’env haven’t been changed,you can use pip to install packages now.The “tlsv1 alert protocol version” will not appear.


回答 9

我尝试了所有现有修补程序,但对我不起作用

我通过在https://www.python.org/downloads/mac-osx/下载.pkg重新安装了python 2.7(还将安装pip)

安装下载pkg后对我有效

I tried all existing fixes and not working for me

I re-install python 2.7 (will also install pip) by downloading .pkg at https://www.python.org/downloads/mac-osx/

works for me after installation downloaded pkg


回答 10

我也遇到了这个问题。潜在的问题是Python 2.7版本<2.7.9中的ssl库不再与pip机制兼容。

如果您在Windows上运行,并且您(像我们一样)无法轻松地从2.7的不兼容版本FWIW升级,我发现如果您从另一个最新版本的Python(例如Python 2.7)的安装中复制以下文件。 15)在另一台机器上进行安装:

    Lib\ssl.py
    libs\_ssl.lib
    DLLs\_ssl.dll

它将有效地将您的SSL层“升级”到受支持的层;这样我们就可以再次使用pip,甚至可以升级pip。

I ran into this problem as well. The underlying problem is that the ssl library in Python 2.7 versions < 2.7.9 is no longer compatible with the pip mechanism.

If you are running on Windows, and you (like us) can’t easily upgrade from an incompatible version of 2.7, FWIW, I found that if you copy the following files from another install of the latest version of Python (e.g. Python 2.7.15) on another machine to your installation:

    Lib\ssl.py
    libs\_ssl.lib
    DLLs\_ssl.dll

it will effectively “upgrade” your SSL layer to one which is supported; we were then be able to use pip again, even to upgrade pip.


回答 11

这对我有用,我安装了最新版本的pip,然后安装了库(ciscoconfparse)。

升级点数:

curl https://bootstrap.pypa.io/get-pip.py | sudo /Users/{your user name}/{path to python}/bin/python

This worked for me, I installed latest version of pip and then installed the library (ciscoconfparse).

Upgrading pip:

curl https://bootstrap.pypa.io/get-pip.py | sudo /Users/{your user name}/{path to python}/bin/python

回答 12

myenv:

python 2.7.14

点9.0.1

mac osx 10.9.4


mysolution:

  1. get-pip.pyhttps://packaging.python.org/tutorials/installing-packages/手动下载

  2. python get-pip.py


参考:

https://github.com/pypa/warehouse/issues/3293#issuecomment-378468534

https://packaging.python.org/tutorials/installing-packages/

安全下载get-pip.py [1]

运行python get-pip.py。[2]这将安装或升级点子。此外,如果尚未安装setuptools和wheel,则将安装它们。

确保pip,setuptools和wheel最新

尽管仅pip即可从预构建的二进制归档文件进行安装,但是最新的setuptools和wheel项目副本对于确保您也可以从源归档文件进行安装很有用:

python -m pip install --upgrade pip setuptools wheel

myenv:

python 2.7.14

pip 9.0.1

mac osx 10.9.4


mysolution:

  1. download get-pip.py manually from https://packaging.python.org/tutorials/installing-packages/

  2. run python get-pip.py


refs:

https://github.com/pypa/warehouse/issues/3293#issuecomment-378468534

https://packaging.python.org/tutorials/installing-packages/

Securely Download get-pip.py [1]

Run python get-pip.py. [2] This will install or upgrade pip. Additionally, it will install setuptools and wheel if they’re not installed already.

Ensure pip, setuptools, and wheel are up to date

While pip alone is sufficient to install from pre-built binary archives, up to date copies of the setuptools and wheel projects are useful to ensure you can also install from source archives:

python -m pip install --upgrade pip setuptools wheel


回答 13

我也在Windows10上遇到了这个问题,并尝试了所有答案,但没有解决我的问题。

C:\ python367 \ Scripts> pip安装Flask

收集Flask找不到满足Flask要求的版本(来自版本:)找不到Flask的匹配发行版

之后,我发现pip配置文件已被修改。因此,我将设置pip.ini为原始默认配置,重新运行pip命令,它对我有用!

总结我的解决方案:

  1. 检查pip.ini(通常在path下C:\ProgramData\pip)是否已被修改;

  2. 如果在步骤1中为是,请尝试将其重置为默认配置。

I also hit this problem on my windows10 and tried all the answers but didn’t solve my problem.

C:\python367\Scripts>pip install Flask

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

After that, I find the pip configuration file had been modified. So, I set the pip.ini as the original default configuration, re-run the pip command and it works for me!

In summary of the solution of mine:

  1. Check the pip.ini (usually under the path C:\ProgramData\pip) had been modified;

  2. If yes in step1, try to reset it to a default configuration.


回答 14

或者只是所需的库不在存储库中。我是Python新手,关于升级pip的所有建议最终都被误导了。我只需要查看https://pypi.org/,发现该库(在我的情况下为气流)停在某个旧版本上,然后将其重命名。是的,愚蠢的解决方案也是可能的:-)。

Or simply the required library just isn’t in the repo. I’m Python newbie and all advices about upgrading pip finally shown as misleading. I had just to look into https://pypi.org/ , finding the library (airflow in my case) stopped at some old version, after which it was renamed. Yes, also that silly solution is also possible :-).


回答 15

对于所有python3pip3用户:

curl https://bootstrap.pypa.io/get-pip.py | sudo python3

然后假设您要安装熊猫

pip3 install pandas --user

For all the python3 and pip3 users out there:

curl https://bootstrap.pypa.io/get-pip.py | sudo python3

and then assume you want to install pandas

pip3 install pandas --user

回答 16

通过以下方式安装pip的答案:

  1. curl https://bootstrap.pypa.io/get-pip.py |sudo python 要么
  2. curl https://bootstrap.pypa.io/get-pip.py | python

由于我不断收到错误,因此对我不起作用:

Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping
ERROR: Could not find a version that satisfies the requirement pip (from versions: none)
ERROR: No matching distribution found for pip

我必须pip通过以下方式手动安装:

  1. 前往pip发行网站
  2. 下载tar.gz版本
  3. 将文件解压缩到本地并cd进入目录
  4. python setup.py install

The answers of installing pip via:

  1. curl https://bootstrap.pypa.io/get-pip.py |sudo python or
  2. curl https://bootstrap.pypa.io/get-pip.py | python

did not work for me as I kept on getting the error:

Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping
ERROR: Could not find a version that satisfies the requirement pip (from versions: none)
ERROR: No matching distribution found for pip

I had to install pip manually via:

  1. Go the pip distribution website
  2. Download the tar.gz version
  3. Unpack the file locally and cd into the directory
  4. run python setup.py install

如何使用列的格式字符串显示浮点数的pandas DataFrame?

问题:如何使用列的格式字符串显示浮点数的pandas DataFrame?

我想使用print()和IPython 显示给定格式的熊猫数据框display()。例如:

df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])
print df

         cost
foo   123.4567
bar   234.5678
baz   345.6789
quux  456.7890

我想以某种方式强迫这样做

         cost
foo   $123.46
bar   $234.57
baz   $345.68
quux  $456.79

无需修改数据本身或创建副本,只需更改其显示方式即可。

我怎样才能做到这一点?

I would like to display a pandas dataframe with a given format using print() and the IPython display(). For example:

df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])
print df

         cost
foo   123.4567
bar   234.5678
baz   345.6789
quux  456.7890

I would like to somehow coerce this into printing

         cost
foo   $123.46
bar   $234.57
baz   $345.68
quux  $456.79

without having to modify the data itself or create a copy, just change the way it is displayed.

How can I do this?


回答 0

import pandas as pd
pd.options.display.float_format = '${:,.2f}'.format
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])
print(df)

Yield

        cost
foo  $123.46
bar  $234.57
baz  $345.68
quux $456.79

但这仅在您希望每个浮点数都用美元符号格式化时才有效。

否则,如果您只想为某些浮点数设置美元格式,那么我认为您必须预先修改数据框(将这些浮点数转换为字符串):

import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])
df['foo'] = df['cost']
df['cost'] = df['cost'].map('${:,.2f}'.format)
print(df)

Yield

         cost       foo
foo   $123.46  123.4567
bar   $234.57  234.5678
baz   $345.68  345.6789
quux  $456.79  456.7890
import pandas as pd
pd.options.display.float_format = '${:,.2f}'.format
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])
print(df)

yields

        cost
foo  $123.46
bar  $234.57
baz  $345.68
quux $456.79

but this only works if you want every float to be formatted with a dollar sign.

Otherwise, if you want dollar formatting for some floats only, then I think you’ll have to pre-modify the dataframe (converting those floats to strings):

import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])
df['foo'] = df['cost']
df['cost'] = df['cost'].map('${:,.2f}'.format)
print(df)

yields

         cost       foo
foo   $123.46  123.4567
bar   $234.57  234.5678
baz   $345.68  345.6789
quux  $456.79  456.7890

回答 1

如果您不想修改数据框,则可以对该列使用自定义格式程序。

import pandas as pd
pd.options.display.float_format = '${:,.2f}'.format
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])


print df.to_string(formatters={'cost':'${:,.2f}'.format})

Yield

        cost
foo  $123.46
bar  $234.57
baz  $345.68
quux $456.79

If you don’t want to modify the dataframe, you could use a custom formatter for that column.

import pandas as pd
pd.options.display.float_format = '${:,.2f}'.format
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])


print df.to_string(formatters={'cost':'${:,.2f}'.format})

yields

        cost
foo  $123.46
bar  $234.57
baz  $345.68
quux $456.79

回答 2

从Pandas 0.17开始,现在有一个样式系统,该系统实质上使用Python格式字符串提供DataFrame的格式化视图:

import pandas as pd
import numpy as np

constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
                   columns=['name','value'])
C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
C

显示

这是一个视图对象;DataFrame本身不会更改格式,但是DataFrame中的更新会反映在视图中:

constants.name = ['pie','eek']
C

但是,它似乎有一些局限性:

  • 在原位添加新的行和/或列似乎会导致样式视图不一致(不添加行/列标签):

    constants.loc[2] = dict(name='bogus', value=123.456)
    constants['comment'] = ['fee','fie','fo']
    constants
    

看起来不错,但是:

C

  • 格式化仅适用于值,不适用于索引条目:

    constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
                   columns=['name','value'])
    constants.set_index('name',inplace=True)
    C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
    C
    

As of Pandas 0.17 there is now a styling system which essentially provides formatted views of a DataFrame using Python format strings:

import pandas as pd
import numpy as np

constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
                   columns=['name','value'])
C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
C

which displays

This is a view object; the DataFrame itself does not change formatting, but updates in the DataFrame are reflected in the view:

constants.name = ['pie','eek']
C

However it appears to have some limitations:

  • Adding new rows and/or columns in-place seems to cause inconsistency in the styled view (doesn’t add row/column labels):

    constants.loc[2] = dict(name='bogus', value=123.456)
    constants['comment'] = ['fee','fie','fo']
    constants
    

which looks ok but:

C

  • Formatting works only for values, not index entries:

    constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
                   columns=['name','value'])
    constants.set_index('name',inplace=True)
    C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
    C
    


回答 3

与上面的unutbu相似,您也可以applymap如下使用:

import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])

df = df.applymap("${0:.2f}".format)

Similar to unutbu above, you could also use applymap as follows:

import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])

df = df.applymap("${0:.2f}".format)

回答 4

我喜欢将pandas.apply()与python format()结合使用。

import pandas as pd
s = pd.Series([1.357, 1.489, 2.333333])

make_float = lambda x: "${:,.2f}".format(x)
s.apply(make_float)

而且,它可以轻松地用于多列…

df = pd.concat([s, s * 2], axis=1)

make_floats = lambda row: "${:,.2f}, ${:,.3f}".format(row[0], row[1])
df.apply(make_floats, axis=1)

I like using pandas.apply() with python format().

import pandas as pd
s = pd.Series([1.357, 1.489, 2.333333])

make_float = lambda x: "${:,.2f}".format(x)
s.apply(make_float)

Also, it can be easily used with multiple columns…

df = pd.concat([s, s * 2], axis=1)

make_floats = lambda row: "${:,.2f}, ${:,.3f}".format(row[0], row[1])
df.apply(make_floats, axis=1)

回答 5

您还可以将语言环境设置为您所在的区域,并将float_format设置为使用货币格式。这将自动为美国的货币设置$符号。

import locale

locale.setlocale(locale.LC_ALL, "en_US.UTF-8")

pd.set_option("float_format", locale.currency)

df = pd.DataFrame(
    [123.4567, 234.5678, 345.6789, 456.7890],
    index=["foo", "bar", "baz", "quux"],
    columns=["cost"],
)
print(df)

        cost
foo  $123.46
bar  $234.57
baz  $345.68
quux $456.79

You can also set locale to your region and set float_format to use a currency format. This will automatically set $ sign for currency in USA.

import locale

locale.setlocale(locale.LC_ALL, "en_US.UTF-8")

pd.set_option("float_format", locale.currency)

df = pd.DataFrame(
    [123.4567, 234.5678, 345.6789, 456.7890],
    index=["foo", "bar", "baz", "quux"],
    columns=["cost"],
)
print(df)

        cost
foo  $123.46
bar  $234.57
baz  $345.68
quux $456.79

回答 6

摘要:


    df = pd.DataFrame({'money': [100.456, 200.789], 'share': ['100,000', '200,000']})
    print(df)
    print(df.to_string(formatters={'money': '${:,.2f}'.format}))
    for col_name in ('share',):
        df[col_name] = df[col_name].map(lambda p: int(p.replace(',', '')))
    print(df)
    """
        money    share
    0  100.456  100,000
    1  200.789  200,000

        money    share
    0 $100.46  100,000
    1 $200.79  200,000

         money   share
    0  100.456  100000
    1  200.789  200000
    """

summary:


    df = pd.DataFrame({'money': [100.456, 200.789], 'share': ['100,000', '200,000']})
    print(df)
    print(df.to_string(formatters={'money': '${:,.2f}'.format}))
    for col_name in ('share',):
        df[col_name] = df[col_name].map(lambda p: int(p.replace(',', '')))
    print(df)
    """
        money    share
    0  100.456  100,000
    1  200.789  200,000

        money    share
    0 $100.46  100,000
    1 $200.79  200,000

         money   share
    0  100.456  100000
    1  200.789  200000
    """

从__future__导入absolute_import实际起什么作用?

问题:从__future__导入absolute_import实际起什么作用?

我已经回答了有关Python中绝对导入的问题,我认为通过阅读Python 2.5 changelog和随附的PEP可以理解。但是,在安装Python 2.5并尝试制作一个正确使用的示例时from __future__ import absolute_import,我意识到事情还不清楚。

直接从上面链接的更改日志,此语句准确总结了我对绝对导入更改的理解:

假设您有一个像这样的包目录:

pkg/
pkg/__init__.py
pkg/main.py
pkg/string.py

这定义了一个名为的包,pkg其中包含pkg.mainpkg.string子模块。

考虑main.py模块中的代码。如果执行该语句会import string怎样?在Python 2.4和更早的版本,它会先看看在包的目录进行相对进口,发现包装/ string.py,进口该文件的内容pkg.string模块,并且该模块被绑定到名字"string"pkg.main模块的命名空间。

所以我创建了这个确切的目录结构:

$ ls -R
.:
pkg/

./pkg:
__init__.py  main.py  string.py

__init__.py并且string.py是空的。main.py包含以下代码:

import string
print string.ascii_uppercase

不出所料,使用Python 2.5运行此命令失败,并显示AttributeError

$ python2.5 pkg/main.py
Traceback (most recent call last):
  File "pkg/main.py", line 2, in <module>
    print string.ascii_uppercase
AttributeError: 'module' object has no attribute 'ascii_uppercase'

但是,在2.5更新日志中,我们发现了这一点(添加了重点):

在Python 2.5中,您可以import使用from __future__ import absolute_import指令将的行为切换为绝对导入。在将来的版本(可能是Python 2.7)中,此绝对导入行为将成为默认设置。一旦将绝对导入设置为默认设置,import string就将始终找到标准库的版本。

因此pkg/main2.py,我创建了,main.py但与将来的import指令相同。现在看起来像这样:

from __future__ import absolute_import
import string
print string.ascii_uppercase

但是,使用Python 2.5运行它会失败AttributeError

$ python2.5 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 3, in <module>
    print string.ascii_uppercase
AttributeError: 'module' object has no attribute 'ascii_uppercase'

这个漂亮的断然反驳该语句import string始终找到STD-库版本绝对进口启用。而且,尽管警告了绝对导入已计划成为“新的默认”行为,但无论使用还是不使用__future__指令,我都使用Python 2.7遇到了相同的问题:

$ python2.7 pkg/main.py
Traceback (most recent call last):
  File "pkg/main.py", line 2, in <module>
    print string.ascii_uppercase
AttributeError: 'module' object has no attribute 'ascii_uppercase'

$ python2.7 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 3, in <module>
    print string.ascii_uppercase
AttributeError: 'module' object has no attribute 'ascii_uppercase'

以及Python 3.5(有无)(假设print两个文件中的语句均已更改):

$ python3.5 pkg/main.py
Traceback (most recent call last):
  File "pkg/main.py", line 2, in <module>
    print(string.ascii_uppercase)
AttributeError: module 'string' has no attribute 'ascii_uppercase'

$ python3.5 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 3, in <module>
    print(string.ascii_uppercase)
AttributeError: module 'string' has no attribute 'ascii_uppercase'

我已经测试了其他变化。相反的string.py,我已经创建了一个空的模块-一个新的目录string仅包含一个空的__init__.py-而不是从发放的进口main.py,我有cd“d到pkg并直接从REPL运行的进口。这些变体(或它们的组合)都没有改变上面的结果。我无法将其与我已阅读的有关__future__指令和绝对导入的内容相协调。

在我看来,这很容易通过以下方式进行解释(这是来自Python 2文档,但该语句在适用于Python 3的同一文档中保持不变):

系统路径

(…)

在程序启动时进行初始化,该列表的第一项path[0]是包含用于调用Python解释器的脚本的目录。如果脚本目录不可用(例如,如果解释器是交互式调用的,或者从标准输入中读取了脚本),path[0]则为空字符串,字符串将Python首先引导到当前目录中的搜索模块。

那我想念什么呢?为什么该__future__声明似乎不按其要求行事?在文档的这两部分之间以及所描述的行为与实际行为之间,这种矛盾的解决方案是什么?

I have answered a question regarding absolute imports in Python, which I thought I understood based on reading the Python 2.5 changelog and accompanying PEP. However, upon installing Python 2.5 and attempting to craft an example of properly using from __future__ import absolute_import, I realize things are not so clear.

Straight from the changelog linked above, this statement accurately summarized my understanding of the absolute import change:

Let’s say you have a package directory like this:

pkg/
pkg/__init__.py
pkg/main.py
pkg/string.py

This defines a package named pkg containing the pkg.main and pkg.string submodules.

Consider the code in the main.py module. What happens if it executes the statement import string? In Python 2.4 and earlier, it will first look in the package’s directory to perform a relative import, finds pkg/string.py, imports the contents of that file as the pkg.string module, and that module is bound to the name "string" in the pkg.main module’s namespace.

So I created this exact directory structure:

$ ls -R
.:
pkg/

./pkg:
__init__.py  main.py  string.py

__init__.py and string.py are empty. main.py contains the following code:

import string
print string.ascii_uppercase

As expected, running this with Python 2.5 fails with an AttributeError:

$ python2.5 pkg/main.py
Traceback (most recent call last):
  File "pkg/main.py", line 2, in <module>
    print string.ascii_uppercase
AttributeError: 'module' object has no attribute 'ascii_uppercase'

However, further along in the 2.5 changelog, we find this (emphasis added):

In Python 2.5, you can switch import‘s behaviour to absolute imports using a from __future__ import absolute_import directive. This absolute-import behaviour will become the default in a future version (probably Python 2.7). Once absolute imports are the default, import string will always find the standard library’s version.

I thus created pkg/main2.py, identical to main.py but with the additional future import directive. It now looks like this:

from __future__ import absolute_import
import string
print string.ascii_uppercase

Running this with Python 2.5, however… fails with an AttributeError:

$ python2.5 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 3, in <module>
    print string.ascii_uppercase
AttributeError: 'module' object has no attribute 'ascii_uppercase'

This pretty flatly contradicts the statement that import string will always find the std-lib version with absolute imports enabled. What’s more, despite the warning that absolute imports are scheduled to become the “new default” behavior, I hit this same problem using both Python 2.7, with or without the __future__ directive:

$ python2.7 pkg/main.py
Traceback (most recent call last):
  File "pkg/main.py", line 2, in <module>
    print string.ascii_uppercase
AttributeError: 'module' object has no attribute 'ascii_uppercase'

$ python2.7 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 3, in <module>
    print string.ascii_uppercase
AttributeError: 'module' object has no attribute 'ascii_uppercase'

as well as Python 3.5, with or without (assuming the print statement is changed in both files):

$ python3.5 pkg/main.py
Traceback (most recent call last):
  File "pkg/main.py", line 2, in <module>
    print(string.ascii_uppercase)
AttributeError: module 'string' has no attribute 'ascii_uppercase'

$ python3.5 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 3, in <module>
    print(string.ascii_uppercase)
AttributeError: module 'string' has no attribute 'ascii_uppercase'

I have tested other variations of this. Instead of string.py, I have created an empty module — a directory named string containing only an empty __init__.py — and instead of issuing imports from main.py, I have cd‘d to pkg and run imports directly from the REPL. Neither of these variations (nor a combination of them) changed the results above. I cannot reconcile this with what I have read about the __future__ directive and absolute imports.

It seems to me that this is easily explicable by the following (this is from the Python 2 docs but this statement remains unchanged in the same docs for Python 3):

sys.path

(…)

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first.

So what am I missing? Why does the __future__ statement seemingly not do what it says, and what is the resolution of this contradiction between these two sections of documentation, as well as between described and actual behavior?


回答 0

变更日志的字眼很草率。from __future__ import absolute_import并不关心某些东西是否是标准库的一部分,import string也不会总是为您提供启用绝对导入的标准库模块。

from __future__ import absolute_import表示如果您愿意import string,Python将始终寻找顶级string模块,而不是current_package.string。但是,它不会影响Python用于确定string模块文件的逻辑。当你做

python pkg/script.py

pkg/script.py看起来不像是Python软件包的一部分。按照正常步骤,将pkg目录添加到路径,.py目录中的所有文件pkg看起来都像顶级模块。import string发现pkg/string.py不是因为它正在执行相对导入,而是因为它pkg/string.py似乎是顶级模块string。这不是标准库string模块的事实并没有出现。

要将文件作为pkg软件包的一部分运行,您可以

python -m pkg.script

在这种情况下,该pkg目录将不会添加到路径中。但是,当前目录将被添加到路径中。

您还可以添加一些样板,pkg/script.py以使Python pkg即使在作为文件运行时也将其视为包的一部分:

if __name__ == '__main__' and __package__ is None:
    __package__ = 'pkg'

但是,这不会影响sys.path。您需要进行一些其他处理才能pkg从路径中删除目录,并且如果pkg的父目录不在路径中,则也需要将其粘贴在路径中。

The changelog is sloppily worded. from __future__ import absolute_import does not care about whether something is part of the standard library, and import string will not always give you the standard-library module with absolute imports on.

from __future__ import absolute_import means that if you import string, Python will always look for a top-level string module, rather than current_package.string. However, it does not affect the logic Python uses to decide what file is the string module. When you do

python pkg/script.py

pkg/script.py doesn’t look like part of a package to Python. Following the normal procedures, the pkg directory is added to the path, and all .py files in the pkg directory look like top-level modules. import string finds pkg/string.py not because it’s doing a relative import, but because pkg/string.py appears to be the top-level module string. The fact that this isn’t the standard-library string module doesn’t come up.

To run the file as part of the pkg package, you could do

python -m pkg.script

In this case, the pkg directory will not be added to the path. However, the current directory will be added to the path.

You can also add some boilerplate to pkg/script.py to make Python treat it as part of the pkg package even when run as a file:

if __name__ == '__main__' and __package__ is None:
    __package__ = 'pkg'

However, this won’t affect sys.path. You’ll need some additional handling to remove the pkg directory from the path, and if pkg‘s parent directory isn’t on the path, you’ll need to stick that on the path too.


回答 1

绝对导入和相对导入之间的差异仅在您从包中导入一个模块并且该模块从该包中导入另一个子模块时才起作用。看到不同:

$ mkdir pkg
$ touch pkg/__init__.py
$ touch pkg/string.py
$ echo 'import string;print(string.ascii_uppercase)' > pkg/main1.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pkg/main1.py", line 1, in <module>
    import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
>>> 
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/main2.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 

特别是:

$ python2 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 1, in <module>
    from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 
$ python2 -m pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ

请注意,python2 pkg/main2.py启动python2和导入后的行为不同pkg.main2(等同于使用-m开关)。

如果要运行程序包的子模块,请始终使用该-m开关,该开关可防止解释器链接sys.path列表并正确处理子模块的语义。

另外,我更喜欢对包子模块使用显式相对导入,因为它们在失败的情况下提供了更多的语义和更好的错误消息。

The difference between absolute and relative imports come into play only when you import a module from a package and that module imports an other submodule from that package. See the difference:

$ mkdir pkg
$ touch pkg/__init__.py
$ touch pkg/string.py
$ echo 'import string;print(string.ascii_uppercase)' > pkg/main1.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pkg/main1.py", line 1, in <module>
    import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
>>> 
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/main2.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 

In particular:

$ python2 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 1, in <module>
    from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 
$ python2 -m pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Note that python2 pkg/main2.py has a different behaviour then launching python2 and then importing pkg.main2 (which is equivalent to using the -m switch).

If you ever want to run a submodule of a package always use the -m switch which prevents the interpreter for chaining the sys.path list and correctly handles the semantics of the submodule.

Also, I much prefer using explicit relative imports for package submodules since they provide more semantics and better error messages in case of failure.


Python dict如何创建密钥或向密钥添加元素?

问题:Python dict如何创建密钥或向密钥添加元素?

我有一本空字典。名称:dict_x 将具有其值为列表的键。

从一个单独的迭代中,我获得一个键(例如:)key_123和一个项目(一个元组),将其放置在dict_xvalue 的列表中key_123

如果该键已经存在,我想添加此项。如果此键不存在,我想用一个空列表创建它,然后追加到它或只在其中添加一个元组。

将来再次出现此键时,由于它存在,我希望再次添加该值。

我的代码包含以下内容:

获取关键和价值。

看看中是否存在NOTdict_x

如果没有创建它: dict_x[key] == []

之后: dict_x[key].append(value)

这是这样做的方式吗?我应该尝试使用try/except积木吗?

I have an empty dictionary. Name: dict_x It is to have keys of which values are lists.

From a separate iteration, I obtain a key (ex: key_123), and an item (a tuple) to place in the list of dict_x‘s value key_123.

If this key already exists, I want to append this item. If this key does not exist, I want to create it with an empty list and then append to it or just create it with a tuple in it.

In future when again this key comes up, since it exists, I want the value to be appended again.

My code consists of this:

Get key and value.

See if NOT key exists in dict_x.

and if not create it: dict_x[key] == []

Afterwards: dict_x[key].append(value)

Is this the way to do it? Shall I try to use try/except blocks?


回答 0

用途dict.setdefault()

dic.setdefault(key,[]).append(value)

help(dict.setdefault)

    setdefault(...)
        D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

Use dict.setdefault():

dic.setdefault(key,[]).append(value)

help(dict.setdefault):

    setdefault(...)
        D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

回答 1

这是执行此操作的各种方法,因此您可以比较它的外观并选择所需的内容。我以我认为最“ pythonic”的方式对它们进行了排序,并评论了乍一看可能并不明显的利弊:

使用collections.defaultdict

import collections
dict_x = collections.defaultdict(list)

...

dict_x[key].append(value)

优点:可能是最佳性能。缺点:在Python 2.4.x中不可用。

使用dict().setdefault()

dict_x = {}

...

dict_x.setdefault(key, []).append(value)

缺点:未使用list()s的创建效率低。

使用try ... except

dict_x = {}

...

try:
    values = dict_x[key]
except KeyError:
    values = dict_x[key] = []
values.append(value)

要么:

try:
    dict_x[key].append(value)
except KeyError:
    dict_x[key] = [value]

Here are the various ways to do this so you can compare how it looks and choose what you like. I’ve ordered them in a way that I think is most “pythonic”, and commented the pros and cons that might not be obvious at first glance:

Using collections.defaultdict:

import collections
dict_x = collections.defaultdict(list)

...

dict_x[key].append(value)

Pros: Probably best performance. Cons: Not available in Python 2.4.x.

Using dict().setdefault():

dict_x = {}

...

dict_x.setdefault(key, []).append(value)

Cons: Inefficient creation of unused list()s.

Using try ... except:

dict_x = {}

...

try:
    values = dict_x[key]
except KeyError:
    values = dict_x[key] = []
values.append(value)

Or:

try:
    dict_x[key].append(value)
except KeyError:
    dict_x[key] = [value]

回答 2

您可以为此使用defaultdict

from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')

这比setdefault没有创建最终不会使用的新列表要有效得多。每次调用setdefault都会创建一个新列表,即使该条目已存在于字典中也是如此。

You can use a defaultdict for this.

from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')

This is slightly more efficient than setdefault since you don’t end up creating new lists that you don’t end up using. Every call to setdefault is going to create a new list, even if the item already exists in the dictionary.


回答 3

您可以使用defaultdictcollections

来自doc的示例:

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)

You can use defaultdict in collections.

An example from doc:

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)

回答 4

dictionary['key'] = dictionary.get('key', []) + list_to_append
dictionary['key'] = dictionary.get('key', []) + list_to_append