使用子流程获取实时输出

问题:使用子流程获取实时输出

我正在尝试为命令行程序(svnadmin verify)编写包装脚本,该脚本将显示该操作的良好进度指示器。这要求我能够立即看到包装程序输出的每一行。

我认为我只是使用subprocess.Popen,use 来执行程序stdout=PIPE,然后读取其中的每一行并据此进行操作。但是,当我运行以下代码时,输​​出似乎被缓冲在某处,导致它出现在两个块中,第1到332行,然后是333到439行(输出的最后一行)

from subprocess import Popen, PIPE, STDOUT

p = Popen('svnadmin verify /var/svn/repos/config', stdout = PIPE, 
        stderr = STDOUT, shell = True)
for line in p.stdout:
    print line.replace('\n', '')

在稍微了解一下子流程的文档之后,我发现了bufsize参数Popen,因此我尝试将bufsize设置为1(缓冲每行)和0(没有缓冲),但是两个值似乎都没有改变行的传递方式。

在这一点上,我开始精通吸管,因此编写了以下输出循环:

while True:
    try:
        print p.stdout.next().replace('\n', '')
    except StopIteration:
        break

但是得到了相同的结果。

是否可以获取使用子进程执行的程序的“实时”程序输出?Python中还有其他向前兼容的选项(不是exec*)吗?

I am trying to write a wrapper script for a command line program (svnadmin verify) that will display a nice progress indicator for the operation. This requires me to be able to see each line of output from the wrapped program as soon as it is output.

I figured that I’d just execute the program using subprocess.Popen, use stdout=PIPE, then read each line as it came in and act on it accordingly. However, when I ran the following code, the output appeared to be buffered somewhere, causing it to appear in two chunks, lines 1 through 332, then 333 through 439 (the last line of output)

from subprocess import Popen, PIPE, STDOUT

p = Popen('svnadmin verify /var/svn/repos/config', stdout = PIPE, 
        stderr = STDOUT, shell = True)
for line in p.stdout:
    print line.replace('\n', '')

After looking at the documentation on subprocess a little, I discovered the bufsize parameter to Popen, so I tried setting bufsize to 1 (buffer each line) and 0 (no buffer), but neither value seemed to change the way the lines were being delivered.

At this point I was starting to grasp for straws, so I wrote the following output loop:

while True:
    try:
        print p.stdout.next().replace('\n', '')
    except StopIteration:
        break

but got the same result.

Is it possible to get ‘realtime’ program output of a program executed using subprocess? Is there some other option in Python that is forward-compatible (not exec*)?


回答 0

我尝试了这个,由于某种原因,代码

for line in p.stdout:
  ...

积极地缓冲,变体

while True:
  line = p.stdout.readline()
  if not line: break
  ...

才不是。显然,这是一个已知的错误:http : //bugs.python.org/issue3907(从2018年8月29日开始,此问题已“关闭”)

I tried this, and for some reason while the code

for line in p.stdout:
  ...

buffers aggressively, the variant

while True:
  line = p.stdout.readline()
  if not line: break
  ...

does not. Apparently this is a known bug: http://bugs.python.org/issue3907 (The issue is now “Closed” as of Aug 29, 2018)


回答 1

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
    print line,
p.stdout.close()
p.wait()
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
    print line,
p.stdout.close()
p.wait()

回答 2

您可以将子流程的输出直接定向到流。简化示例:

subprocess.run(['ls'], stderr=sys.stderr, stdout=sys.stdout)

You can direct the subprocess output to the streams directly. Simplified example:

subprocess.run(['ls'], stderr=sys.stderr, stdout=sys.stdout)

回答 3

您可以尝试以下方法:

import subprocess
import sys

process = subprocess.Popen(
    cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)

while True:
    out = process.stdout.read(1)
    if out == '' and process.poll() != None:
        break
    if out != '':
        sys.stdout.write(out)
        sys.stdout.flush()

如果您使用readline而不是read,则在某些情况下不会打印输入消息。尝试使用需要内联输入的命令并亲自查看。

You can try this:

import subprocess
import sys

process = subprocess.Popen(
    cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)

while True:
    out = process.stdout.read(1)
    if out == '' and process.poll() != None:
        break
    if out != '':
        sys.stdout.write(out)
        sys.stdout.flush()

If you use readline instead of read, there will be some cases where the input message is not printed. Try it with a command the requires an inline input and see for yourself.


回答 4

流子stdin和stdout与ASYNCIO在Python的博客文章凯文·麦卡锡显示了如何ASYNCIO做到这一点:

import asyncio
from asyncio.subprocess import PIPE
from asyncio import create_subprocess_exec


async def _read_stream(stream, callback):
    while True:
        line = await stream.readline()
        if line:
            callback(line)
        else:
            break


async def run(command):
    process = await create_subprocess_exec(
        *command, stdout=PIPE, stderr=PIPE
    )

    await asyncio.wait(
        [
            _read_stream(
                process.stdout,
                lambda x: print(
                    "STDOUT: {}".format(x.decode("UTF8"))
                ),
            ),
            _read_stream(
                process.stderr,
                lambda x: print(
                    "STDERR: {}".format(x.decode("UTF8"))
                ),
            ),
        ]
    )

    await process.wait()


async def main():
    await run("docker build -t my-docker-image:latest .")


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

The Streaming subprocess stdin and stdout with asyncio in Python blog post by Kevin McCarthy shows how to do it with asyncio:

import asyncio
from asyncio.subprocess import PIPE
from asyncio import create_subprocess_exec


async def _read_stream(stream, callback):
    while True:
        line = await stream.readline()
        if line:
            callback(line)
        else:
            break


async def run(command):
    process = await create_subprocess_exec(
        *command, stdout=PIPE, stderr=PIPE
    )

    await asyncio.wait(
        [
            _read_stream(
                process.stdout,
                lambda x: print(
                    "STDOUT: {}".format(x.decode("UTF8"))
                ),
            ),
            _read_stream(
                process.stderr,
                lambda x: print(
                    "STDERR: {}".format(x.decode("UTF8"))
                ),
            ),
        ]
    )

    await process.wait()


async def main():
    await run("docker build -t my-docker-image:latest .")


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

回答 5

实时输出问题已解决:在捕获c程序的实时输出时,我在Python中确实遇到了类似的问题。我添加了“ fflush(stdout) ;” 在我的C代码中 它为我工作。这是代码片段

<< C程序>>

#include <stdio.h>
void main()
{
    int count = 1;
    while (1)
    {
        printf(" Count  %d\n", count++);
        fflush(stdout);
        sleep(1);
    }
}

<< Python程序>>

#!/usr/bin/python

import os, sys
import subprocess


procExe = subprocess.Popen(".//count", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

while procExe.poll() is None:
    line = procExe.stdout.readline()
    print("Print:" + line)

<<输出>>打印:计数1打印:计数2打印:计数3

希望能帮助到你。

〜塞拉姆

Real Time Output Issue resolved: I encountered a similar issue in Python, while capturing the real time output from C program. I added fflush(stdout); in my C code. It worked for me. Here is the code.

C program:

#include <stdio.h>
void main()
{
    int count = 1;
    while (1)
    {
        printf(" Count  %d\n", count++);
        fflush(stdout);
        sleep(1);
    }
}

Python program:

#!/usr/bin/python

import os, sys
import subprocess


procExe = subprocess.Popen(".//count", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

while procExe.poll() is None:
    line = procExe.stdout.readline()
    print("Print:" + line)

Output:

Print: Count  1
Print: Count  2
Print: Count  3

回答 6

我不久前遇到了同样的问题。我的解决方案read是放弃对该方法的迭代,即使您的子流程未完成执行,该方法也会立即返回,等等。

I ran into the same problem awhile back. My solution was to ditch iterating for the read method, which will return immediately even if your subprocess isn’t finished executing, etc.


回答 7

根据使用情况,您可能还想禁用子流程本身中的缓冲。

如果子进程将是Python进程,则可以在调用之前执行此操作:

os.environ["PYTHONUNBUFFERED"] = "1"

或者将其作为env参数传递给Popen

否则,如果您使用的是Linux / Unix,则可以使用该stdbuf工具。例如:

cmd = ["stdbuf", "-oL"] + cmd

另请参见这里stdbuf或其他选项。

(有关相同答案,请参见此处。)

Depending on the use case, you might also want to disable the buffering in the subprocess itself.

If the subprocess will be a Python process, you could do this before the call:

os.environ["PYTHONUNBUFFERED"] = "1"

Or alternatively pass this in the env argument to Popen.

Otherwise, if you are on Linux/Unix, you can use the stdbuf tool. E.g. like:

cmd = ["stdbuf", "-oL"] + cmd

See also here about stdbuf or other options.

(See also here for the same answer.)


回答 8

我使用此解决方案在子流程上获得实时输出。该过程完成后,该循环将立即停止,不再需要break语句或可能的无限循环。

sub_process = subprocess.Popen(my_command, close_fds=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while sub_process.poll() is None:
    out = sub_process.stdout.read(1)
    sys.stdout.write(out)
    sys.stdout.flush()

I used this solution to get realtime output on a subprocess. This loop will stop as soon as the process completes leaving out a need for a break statement or possible infinite loop.

sub_process = subprocess.Popen(my_command, close_fds=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while sub_process.poll() is None:
    out = sub_process.stdout.read(1)
    sys.stdout.write(out)
    sys.stdout.flush()

回答 9

在此处找到此“即插即用”功能。像魅力一样工作!

import subprocess

def myrun(cmd):
    """from http://blog.kagesenshi.org/2008/02/teeing-python-subprocesspopen-output.html
    """
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout = []
    while True:
        line = p.stdout.readline()
        stdout.append(line)
        print line,
        if line == '' and p.poll() != None:
            break
    return ''.join(stdout)

Found this “plug-and-play” function here. Worked like a charm!

import subprocess

def myrun(cmd):
    """from http://blog.kagesenshi.org/2008/02/teeing-python-subprocesspopen-output.html
    """
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout = []
    while True:
        line = p.stdout.readline()
        stdout.append(line)
        print line,
        if line == '' and p.poll() != None:
            break
    return ''.join(stdout)

回答 10

您可以在子进程的输出中的每个字节上使用迭代器。这允许从子进程进行内联更新(以’\ r’结尾的行覆盖先前的输出行):

from subprocess import PIPE, Popen

command = ["my_command", "-my_arg"]

# Open pipe to subprocess
subprocess = Popen(command, stdout=PIPE, stderr=PIPE)


# read each byte of subprocess
while subprocess.poll() is None:
    for c in iter(lambda: subprocess.stdout.read(1) if subprocess.poll() is None else {}, b''):
        c = c.decode('ascii')
        sys.stdout.write(c)
sys.stdout.flush()

if subprocess.returncode != 0:
    raise Exception("The subprocess did not terminate correctly.")

You may use an iterator over each byte in the output of the subprocess. This allows inline update (lines ending with ‘\r’ overwrite previous output line) from the subprocess:

from subprocess import PIPE, Popen

command = ["my_command", "-my_arg"]

# Open pipe to subprocess
subprocess = Popen(command, stdout=PIPE, stderr=PIPE)


# read each byte of subprocess
while subprocess.poll() is None:
    for c in iter(lambda: subprocess.stdout.read(1) if subprocess.poll() is None else {}, b''):
        c = c.decode('ascii')
        sys.stdout.write(c)
sys.stdout.flush()

if subprocess.returncode != 0:
    raise Exception("The subprocess did not terminate correctly.")

回答 11

在Python 3.x中,该过程可能会挂起,因为输出是字节数组而不是字符串。确保将其解码为字符串。

从Python 3.6开始,您可以使用Popen Constructor中的参数encoding来实现。完整的例子:

process = subprocess.Popen(
    'my_command',
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    shell=True,
    encoding='utf-8',
    errors='replace'
)

while True:
    realtime_output = process.stdout.readline()

    if realtime_output == '' and process.poll() is not None:
        break

    if realtime_output:
        print(realtime_output.strip(), flush=True)

请注意,此代码重定向 stderrstdout处理输出错误

In Python 3.x the process might hang because the output is a byte array instead of a string. Make sure you decode it into a string.

Starting from Python 3.6 you can do it using the parameter encoding in Popen Constructor. The complete example:

process = subprocess.Popen(
    'my_command',
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    shell=True,
    encoding='utf-8',
    errors='replace'
)

while True:
    realtime_output = process.stdout.readline()

    if realtime_output == '' and process.poll() is not None:
        break

    if realtime_output:
        print(realtime_output.strip(), flush=True)

Note that this code redirects stderr to stdout and handles output errors.


回答 12

将pexpect [ http://www.noah.org/wiki/Pexpect ]与非阻塞的阅读行一起使用将解决此问题。这是由于管道是缓冲的,因此您的应用程序的输出将被管道缓冲,因此,直到缓冲填满或进程终止,您才能获得该输出。

Using pexpect with non-blocking readlines will resolve this problem. It stems from the fact that pipes are buffered, and so your app’s output is getting buffered by the pipe, therefore you can’t get to that output until the buffer fills or the process dies.


回答 13

完整的解决方案:

import contextlib
import subprocess

# Unix, Windows and old Macintosh end-of-line
newlines = ['\n', '\r\n', '\r']
def unbuffered(proc, stream='stdout'):
    stream = getattr(proc, stream)
    with contextlib.closing(stream):
        while True:
            out = []
            last = stream.read(1)
            # Don't loop forever
            if last == '' and proc.poll() is not None:
                break
            while last not in newlines:
                # Don't loop forever
                if last == '' and proc.poll() is not None:
                    break
                out.append(last)
                last = stream.read(1)
            out = ''.join(out)
            yield out

def example():
    cmd = ['ls', '-l', '/']
    proc = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        # Make all end-of-lines '\n'
        universal_newlines=True,
    )
    for line in unbuffered(proc):
        print line

example()

Complete solution:

import contextlib
import subprocess

# Unix, Windows and old Macintosh end-of-line
newlines = ['\n', '\r\n', '\r']
def unbuffered(proc, stream='stdout'):
    stream = getattr(proc, stream)
    with contextlib.closing(stream):
        while True:
            out = []
            last = stream.read(1)
            # Don't loop forever
            if last == '' and proc.poll() is not None:
                break
            while last not in newlines:
                # Don't loop forever
                if last == '' and proc.poll() is not None:
                    break
                out.append(last)
                last = stream.read(1)
            out = ''.join(out)
            yield out

def example():
    cmd = ['ls', '-l', '/']
    proc = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        # Make all end-of-lines '\n'
        universal_newlines=True,
    )
    for line in unbuffered(proc):
        print line

example()

回答 14

这是我经常使用的基本骨架。它使实现超时变得容易,并且能够处理不可避免的挂起过程。

import subprocess
import threading
import Queue

def t_read_stdout(process, queue):
    """Read from stdout"""

    for output in iter(process.stdout.readline, b''):
        queue.put(output)

    return

process = subprocess.Popen(['dir'],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT,
                           bufsize=1,
                           cwd='C:\\',
                           shell=True)

queue = Queue.Queue()
t_stdout = threading.Thread(target=t_read_stdout, args=(process, queue))
t_stdout.daemon = True
t_stdout.start()

while process.poll() is None or not queue.empty():
    try:
        output = queue.get(timeout=.5)

    except Queue.Empty:
        continue

    if not output:
        continue

    print(output),

t_stdout.join()

This is the basic skeleton that I always use for this. It makes it easy to implement timeouts and is able to deal with inevitable hanging processes.

import subprocess
import threading
import Queue

def t_read_stdout(process, queue):
    """Read from stdout"""

    for output in iter(process.stdout.readline, b''):
        queue.put(output)

    return

process = subprocess.Popen(['dir'],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT,
                           bufsize=1,
                           cwd='C:\\',
                           shell=True)

queue = Queue.Queue()
t_stdout = threading.Thread(target=t_read_stdout, args=(process, queue))
t_stdout.daemon = True
t_stdout.start()

while process.poll() is None or not queue.empty():
    try:
        output = queue.get(timeout=.5)

    except Queue.Empty:
        continue

    if not output:
        continue

    print(output),

t_stdout.join()

回答 15

(此解决方案已通过Python 2.7.15进行了测试
),每行读/写后只需要sys.stdout.flush():

while proc.poll() is None:
    line = proc.stdout.readline()
    sys.stdout.write(line)
    # or print(line.strip()), you still need to force the flush.
    sys.stdout.flush()

(This solution has been tested with Python 2.7.15)
You just need to sys.stdout.flush() after each line read/write:

while proc.poll() is None:
    line = proc.stdout.readline()
    sys.stdout.write(line)
    # or print(line.strip()), you still need to force the flush.
    sys.stdout.flush()

回答 16

很少有建议使用python 3.x或pthon 2.x的答案,下面的代码对两者都适用。

 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,)
    stdout = []
    while True:
        line = p.stdout.readline()
        if not isinstance(line, (str)):
            line = line.decode('utf-8')
        stdout.append(line)
        print (line)
        if (line == '' and p.poll() != None):
            break

Few answers suggesting python 3.x or pthon 2.x , Below code will work for both.

 p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,)
    stdout = []
    while True:
        line = p.stdout.readline()
        if not isinstance(line, (str)):
            line = line.decode('utf-8')
        stdout.append(line)
        print (line)
        if (line == '' and p.poll() != None):
            break

为什么列表中允许尾随逗号?

问题:为什么列表中允许尾随逗号?

我很好奇为什么在Python中列表中的尾部逗号是有效的语法,并且似乎Python只是忽略了它:

>>> ['a','b',]
['a', 'b']

自从('a')('a',)是两个元组时,它是一个有意义的元组,但是在列表中呢?

I am curious why in Python a trailing comma in a list is valid syntax, and it seems that Python simply ignores it:

>>> ['a','b',]
['a', 'b']

It makes sense when its a tuple since ('a') and ('a',) are two different things, but in lists?


回答 0

主要优点是,它使多行列表更易于编辑,并减少了差异。

变更:

s = ['manny',
     'mo',
     'jack',
]

至:

s = ['manny',
     'mo',
     'jack',
     'roger',
]

仅涉及差异的单行更改:

  s = ['manny',
       'mo',
       'jack',
+      'roger',
  ]

当省略尾部逗号时,这击败了更令人困惑的多行差异:

  s = ['manny',
       'mo',
-      'jack'
+      'jack',
+      'roger'
  ]

后者的差异使得很难看到仅添加了一行,而另一行没有更改内容。

它还降低了这样做的风险:

s = ['manny',
     'mo',
     'jack'
     'roger'  # Added this line, but forgot to add a comma on the previous line
]

并触发隐式字符串文字串联,产生s = ['manny', 'mo', 'jackroger']而不是预期的结果。

The main advantages are that it makes multi-line lists easier to edit and that it reduces clutter in diffs.

Changing:

s = ['manny',
     'mo',
     'jack',
]

to:

s = ['manny',
     'mo',
     'jack',
     'roger',
]

involves only a one-line change in the diff:

  s = ['manny',
       'mo',
       'jack',
+      'roger',
  ]

This beats the more confusing multi-line diff when the trailing comma was omitted:

  s = ['manny',
       'mo',
-      'jack'
+      'jack',
+      'roger'
  ]

The latter diff makes it harder to see that only one line was added and that the other line didn’t change content.

It also reduces the risk of doing this:

s = ['manny',
     'mo',
     'jack'
     'roger'  # Added this line, but forgot to add a comma on the previous line
]

and triggering implicit string literal concatenation, producing s = ['manny', 'mo', 'jackroger'] instead of the intended result.


回答 1

这是一种常见的语法约定,允许在数组中尾随逗号,C和Java之类的语言都允许,并且Python似乎已对其列表数据结构采用了该约定。在生成用于填充列表的代码时,它特别有用:只需生成一系列元素和逗号,而无需将最后一个元素和逗号视为特殊情况,并且不应该在末尾加逗号。

It’s a common syntactical convention to allow trailing commas in an array, languages like C and Java allow it, and Python seems to have adopted this convention for its list data structure. It’s particularly useful when generating code for populating a list: just generate a sequence of elements and commas, no need to consider the last one as a special case that shouldn’t have a comma at the end.


回答 2

它有助于消除某种错误。有时在多行上写列表会更清晰。但是在以后的维护中,您可能需要重新排列项目。

l1 = [
        1,
        2,
        3,
        4,
        5
]

# Now you want to rearrange

l1 = [
        1,
        2,
        3,
        5
        4,
]

# Now you have an error

但是,如果允许使用尾随逗号,则可以轻松地重新排列行而不会引起错误。

It helps to eliminate a certain kind of bug. It’s sometimes clearer to write lists on multiple lines. But in, later maintenace you may want to rearrange the items.

l1 = [
        1,
        2,
        3,
        4,
        5
]

# Now you want to rearrange

l1 = [
        1,
        2,
        3,
        5
        4,
]

# Now you have an error

But if you allow trailing commas, and use them, you can easily rearrange the lines without introducing an error.


回答 3

元组的不同之处在于,('a')它使用隐式连续和()s作为优先运算符进行扩展,而('a',)引用长度为1的元组。

你原来的例子是 tuple('a')

A tuple is different because ('a') is expanded using implicit continuation and ()s as a precendence operator, whereas ('a',) refers to a length 1 tuple.

Your original example would have been tuple('a')


回答 4

主要原因是使diff变得不那么复杂。例如,您有一个列表:

list = [
    'a',
    'b',
    'c'
]

并且您想要向其中添加另一个元素。然后,您将最终执行此操作:

list = [
    'a',
    'b',
    'c',
    'd'
]

因此,diff将显示出两行已更改,首先在’c’处添加’,’,在最后一行添加’d’。

因此,python允许在列表的最后一个元素中尾部加上’,’,以防止可能引起混淆的额外差异。

The main reason is to make diff less complicated. For example you have a list :

list = [
    'a',
    'b',
    'c'
]

and you want to add another element to it. Then you will be end up doing this:

list = [
    'a',
    'b',
    'c',
    'd'
]

thus, diff will show that two lines have been changed, first adding ‘,’ in line with ‘c’ and adding ‘d’ at last line.

So, python allows trailing ‘,’ in last element of list, to prevent extra diff which can cause confusion.


列出给定类的层次结构中的所有基类?

问题:列出给定类的层次结构中的所有基类?

给定一个类Foo(无论它是否是新型类),如何生成所有基类-在继承层次结构中的任何位置issubclass

Given a class Foo (whether it is a new-style class or not), how do you generate all the base classes – anywhere in the inheritance hierarchy – it issubclass of?


回答 0

inspect.getmro(cls)适用于新样式和旧样式类,并以与NewClass.mro()方法解析相同的顺序返回:类及其所有祖先类的列表。

>>> class A(object):
>>>     pass
>>>
>>> class B(A):
>>>     pass
>>>
>>> import inspect
>>> inspect.getmro(B)
(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)

inspect.getmro(cls) works for both new and old style classes and returns the same as NewClass.mro(): a list of the class and all its ancestor classes, in the order used for method resolution.

>>> class A(object):
>>>     pass
>>>
>>> class B(A):
>>>     pass
>>>
>>> import inspect
>>> inspect.getmro(B)
(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)

回答 1

请参阅python上的可用__bases__属性class,该属性包含基类的元组:

>>> def classlookup(cls):
...     c = list(cls.__bases__)
...     for base in c:
...         c.extend(classlookup(base))
...     return c
...
>>> class A: pass
...
>>> class B(A): pass
...
>>> class C(object, B): pass
...
>>> classlookup(C)
[<type 'object'>, <class __main__.B at 0x00AB7300>, <class __main__.A at 0x00A6D630>]

See the __bases__ property available on a python class, which contains a tuple of the bases classes:

>>> def classlookup(cls):
...     c = list(cls.__bases__)
...     for base in c:
...         c.extend(classlookup(base))
...     return c
...
>>> class A: pass
...
>>> class B(A): pass
...
>>> class C(object, B): pass
...
>>> classlookup(C)
[<type 'object'>, <class __main__.B at 0x00AB7300>, <class __main__.A at 0x00A6D630>]

回答 2

inspect.getclasstree()将创建一个嵌套的类及其基列表。用法:

inspect.getclasstree(inspect.getmro(IOError)) # Insert your Class instead of IOError.

inspect.getclasstree() will create a nested list of classes and their bases. Usage:

inspect.getclasstree(inspect.getmro(IOError)) # Insert your Class instead of IOError.

回答 3

您可以使用__bases__类对象的元组:

class A(object, B, C):
    def __init__(self):
       pass
print A.__bases__

返回的元组__bases__具有其所有基类。

希望能帮助到你!

you can use the __bases__ tuple of the class object:

class A(object, B, C):
    def __init__(self):
       pass
print A.__bases__

The tuple returned by __bases__ has all its base classes.

Hope it helps!


回答 4

在python 3.7中,您无需导入inspect,type.mro将为您提供结果。

>>> class A:
...   pass
... 
>>> class B(A):
...   pass
... 
>>> type.mro(B)
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
>>>

注意,在python 3.x中,每个类都继承自基础对象类。

In python 3.7 you don’t need to import inspect, type.mro will give you the result.

>>> class A:
...   pass
... 
>>> class B(A):
...   pass
... 
>>> type.mro(B)
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
>>>

attention that in python 3.x every class inherits from base object class.


回答 5

根据Python文档,我们还可以简单地使用class.__mro__属性或class.mro()方法:

>>> class A:
...     pass
... 
>>> class B(A):
...     pass
... 
>>> B.__mro__
(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
>>> A.__mro__
(<class '__main__.A'>, <class 'object'>)
>>> object.__mro__
(<class 'object'>,)
>>>
>>> B.mro()
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
>>> A.mro()
[<class '__main__.A'>, <class 'object'>]
>>> object.mro()
[<class 'object'>]
>>> A in B.mro()
True

According to the Python doc, we can also simply use class.__mro__ attribute or class.mro() method:

>>> class A:
...     pass
... 
>>> class B(A):
...     pass
... 
>>> B.__mro__
(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
>>> A.__mro__
(<class '__main__.A'>, <class 'object'>)
>>> object.__mro__
(<class 'object'>,)
>>>
>>> B.mro()
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
>>> A.mro()
[<class '__main__.A'>, <class 'object'>]
>>> object.mro()
[<class 'object'>]
>>> A in B.mro()
True


回答 6

尽管Jochen的回答非常有帮助和正确,但是您可以使用inspect模块的.getmro()方法获得类层次结构,但是突出显示Python的继承层次结构也很重要:

例如:

class MyClass(YourClass):

继承类

  • 儿童班
  • 派生类
  • 子类

例如:

class YourClass(Object):

继承的类

  • 家长班
  • 基类
  • 超类

一个类可以从另一个类继承-该类的属性是继承的-特别是其方法是继承的-这意味着继承(子)类的实例可以访问该继承(父)类的属性

实例->类->然后继承的类

使用

import inspect
inspect.getmro(MyClass)

将在Python中向您显示层次结构。

Although Jochen’s answer is very helpful and correct, as you can obtain the class hierarchy using the .getmro() method of the inspect module, it’s also important to highlight that Python’s inheritance hierarchy is as follows:

ex:

class MyClass(YourClass):

An inheriting class

  • Child class
  • Derived class
  • Subclass

ex:

class YourClass(Object):

An inherited class

  • Parent class
  • Base class
  • Superclass

One class can inherit from another – The class’ attributed are inherited – in particular, its methods are inherited – this means that instances of an inheriting (child) class can access attributed of the inherited (parent) class

instance -> class -> then inherited classes

using

import inspect
inspect.getmro(MyClass)

will show you the hierarchy, within Python.


将两个LISTS的值之和添加到新的LIST中

问题:将两个LISTS的值之和添加到新的LIST中

我有以下两个列表:

first = [1,2,3,4,5]
second = [6,7,8,9,10]

现在,我想将这两个列表中的项目添加到新列表中。

输出应该是

third = [7,9,11,13,15]

I have the following two lists:

first = [1,2,3,4,5]
second = [6,7,8,9,10]

Now I want to add the items from both of these lists into a new list.

output should be

third = [7,9,11,13,15]

回答 0

zip功能在此处有用,可与列表推导一起使用。

[x + y for x, y in zip(first, second)]

如果您有一个列表列表(而不是两个列表):

lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]

The zip function is useful here, used with a list comprehension.

[x + y for x, y in zip(first, second)]

If you have a list of lists (instead of just two lists):

lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]

回答 1

来自文档

import operator
list(map(operator.add, first,second))

From docs

import operator
list(map(operator.add, first,second))

回答 2

假设两个列表a,并b具有相同的长度,你不需要压缩,numpy的或其他任何东西。

Python 2.x和3.x:

[a[i]+b[i] for i in range(len(a))]

Assuming both lists a and b have same length, you do not need zip, numpy or anything else.

Python 2.x and 3.x:

[a[i]+b[i] for i in range(len(a))]

回答 3

numpy中的默认行为是逐组件添加

import numpy as np
np.add(first, second)

哪个输出

array([7,9,11,13,15])

Default behavior in numpy is add componentwise

import numpy as np
np.add(first, second)

which outputs

array([7,9,11,13,15])

回答 4

这可以扩展到任意数量的列表:

[sum(sublist) for sublist in itertools.izip(*myListOfLists)]

在你的情况下,myListOfLists[first, second]

This extends itself to any number of lists:

[sum(sublist) for sublist in itertools.izip(*myListOfLists)]

In your case, myListOfLists would be [first, second]


回答 5

尝试以下代码:

first = [1, 2, 3, 4]
second = [2, 3, 4, 5]
third = map(sum, zip(first, second))

Try the following code:

first = [1, 2, 3, 4]
second = [2, 3, 4, 5]
third = map(sum, zip(first, second))

回答 6

执行此操作的简单方法和快速方法是:

three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

另外,您可以使用numpy sum:

from numpy import sum
three = sum([first,second], axis=0) # array([7,9,11,13,15])

The easy way and fast way to do this is:

three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

Alternatively, you can use numpy sum:

from numpy import sum
three = sum([first,second], axis=0) # array([7,9,11,13,15])

回答 7

first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
three = map(lambda x,y: x+y,first,second)
print three



Output 
[7, 9, 11, 13, 15]
first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
three = map(lambda x,y: x+y,first,second)
print three



Output 
[7, 9, 11, 13, 15]

回答 8

一线解决方案

list(map(lambda x,y: x+y, a,b))

one-liner solution

list(map(lambda x,y: x+y, a,b))

回答 9

Thiru在3月17日9:25回答了我的问题。

这更加简单快捷,这是他的解决方案:

执行此操作的简单方法和快速方法是:

 three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

另外,您可以使用numpy sum:

 from numpy import sum
 three = sum([first,second], axis=0) # array([7,9,11,13,15])

您需要numpy!

numpy数组可以做一些像矢量的操作

import numpy as np
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = list(np.array(a) + np.array(b))
print c
# [7, 9, 11, 13, 15]

My answer is repeated with Thiru’s that answered it in Mar 17 at 9:25.

It was simpler and quicker, here are his solutions:

The easy way and fast way to do this is:

 three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

Alternatively, you can use numpy sum:

 from numpy import sum
 three = sum([first,second], axis=0) # array([7,9,11,13,15])

You need numpy!

numpy array could do some operation like vectors
import numpy as np
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = list(np.array(a) + np.array(b))
print c
# [7, 9, 11, 13, 15]

回答 10

如果未知数量的相同长度的列表,则可以使用以下功能。

在这里,* args接受可变数量的列表参数(但每个参数仅求和相同数量的元素)。再次使用*来解压缩每个列表中的元素。

def sum_lists(*args):
    return list(map(sum, zip(*args)))

a = [1,2,3]
b = [1,2,3]  

sum_lists(a,b)

输出:

[2, 4, 6]

或有3个清单

sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])

输出:

[19, 19, 19, 19, 19]

If you have an unknown number of lists of the same length, you can use the below function.

Here the *args accepts a variable number of list arguments (but only sums the same number of elements in each). The * is used again to unpack the elements in each of the lists.

def sum_lists(*args):
    return list(map(sum, zip(*args)))

a = [1,2,3]
b = [1,2,3]  

sum_lists(a,b)

Output:

[2, 4, 6]

Or with 3 lists

sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])

Output:

[19, 19, 19, 19, 19]

回答 11

您可以使用zip(),将两个数组“交织”在一起,然后使用map(),它将对一个可迭代对象中的每个元素应用一个函数:

>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9,10]
>>> zip(a, b)
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
>>> map(lambda x: x[0] + x[1], zip(a, b))
[7, 9, 11, 13, 15]

You can use zip(), which will “interleave” the two arrays together, and then map(), which will apply a function to each element in an iterable:

>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9,10]
>>> zip(a, b)
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
>>> map(lambda x: x[0] + x[1], zip(a, b))
[7, 9, 11, 13, 15]

回答 12

这是另一种方法。我们利用python的内部__add__函数:

class SumList(object):
    def __init__(self, this_list):
        self.mylist = this_list

    def __add__(self, other):
        new_list = []
        zipped_list = zip(self.mylist, other.mylist)
        for item in zipped_list:
            new_list.append(item[0] + item[1])
        return SumList(new_list)

    def __repr__(self):
        return str(self.mylist)

list1 = SumList([1,2,3,4,5])
list2 = SumList([10,20,30,40,50])
sum_list1_list2 = list1 + list2
print(sum_list1_list2)

输出量

[11, 22, 33, 44, 55]

Here is another way to do it. We make use of the internal __add__ function of python:

class SumList(object):
    def __init__(self, this_list):
        self.mylist = this_list

    def __add__(self, other):
        new_list = []
        zipped_list = zip(self.mylist, other.mylist)
        for item in zipped_list:
            new_list.append(item[0] + item[1])
        return SumList(new_list)

    def __repr__(self):
        return str(self.mylist)

list1 = SumList([1,2,3,4,5])
list2 = SumList([10,20,30,40,50])
sum_list1_list2 = list1 + list2
print(sum_list1_list2)

Output

[11, 22, 33, 44, 55]

回答 13

如果您还想添加列表中的其余值,则可以使用它(在Python3.5中有效)

def addVectors(v1, v2):
    sum = [x + y for x, y in zip(v1, v2)]
    if not len(v1) >= len(v2):
        sum += v2[len(v1):]
    else:
        sum += v1[len(v2):]

    return sum


#for testing 
if __name__=='__main__':
    a = [1, 2]
    b = [1, 2, 3, 4]
    print(a)
    print(b)
    print(addVectors(a,b))

If you want to add also the rest of the values in the lists you can use this (this is working in Python3.5)

def addVectors(v1, v2):
    sum = [x + y for x, y in zip(v1, v2)]
    if not len(v1) >= len(v2):
        sum += v2[len(v1):]
    else:
        sum += v1[len(v2):]

    return sum


#for testing 
if __name__=='__main__':
    a = [1, 2]
    b = [1, 2, 3, 4]
    print(a)
    print(b)
    print(addVectors(a,b))

回答 14

    first = [1,2,3,4,5]
    second = [6,7,8,9,10]
    #one way
    third = [x + y for x, y in zip(first, second)]
    print("third" , third) 
    #otherway
    fourth = []
    for i,j in zip(first,second):
        global fourth
        fourth.append(i + j)
    print("fourth" , fourth )
#third [7, 9, 11, 13, 15]
#fourth [7, 9, 11, 13, 15]
    first = [1,2,3,4,5]
    second = [6,7,8,9,10]
    #one way
    third = [x + y for x, y in zip(first, second)]
    print("third" , third) 
    #otherway
    fourth = []
    for i,j in zip(first,second):
        global fourth
        fourth.append(i + j)
    print("fourth" , fourth )
#third [7, 9, 11, 13, 15]
#fourth [7, 9, 11, 13, 15]

回答 15

这是另一种方法。它对我来说很好。

N=int(input())
num1 = list(map(int, input().split()))
num2 = list(map(int, input().split()))
sum=[]

for i in range(0,N):
  sum.append(num1[i]+num2[i])

for element in sum:
  print(element, end=" ")

print("")

Here is another way to do it.It is working fine for me .

N=int(input())
num1 = list(map(int, input().split()))
num2 = list(map(int, input().split()))
sum=[]

for i in range(0,N):
  sum.append(num1[i]+num2[i])

for element in sum:
  print(element, end=" ")

print("")

回答 16

j = min(len(l1), len(l2))
l3 = [l1[i]+l2[i] for i in range(j)]
j = min(len(l1), len(l2))
l3 = [l1[i]+l2[i] for i in range(j)]

回答 17

也许是最简单的方法:

first = [1,2,3,4,5]
second = [6,7,8,9,10]
three=[]

for i in range(0,5):
    three.append(first[i]+second[i])

print(three)

Perhaps the simplest approach:

first = [1,2,3,4,5]
second = [6,7,8,9,10]
three=[]

for i in range(0,5):
    three.append(first[i]+second[i])

print(three)

回答 18

如果您将列表视为numpy数组,则需要轻松对其求和:

import numpy as np

third = np.array(first) + np.array(second)

print third

[7, 9, 11, 13, 15]

If you consider your lists as numpy array, then you need to easily sum them:

import numpy as np

third = np.array(first) + np.array(second)

print third

[7, 9, 11, 13, 15]

回答 19

如果您有不同长度的列表怎么办,那么您可以尝试这样的操作(使用zip_longest

from itertools import zip_longest  # izip_longest for python2.x

l1 = [1, 2, 3]
l2 = [4, 5, 6, 7]

>>> list(map(sum, zip_longest(l1, l2, fillvalue=0)))
[5, 7, 9, 7]

What if you have list with different length, then you can try something like this (using zip_longest)

from itertools import zip_longest  # izip_longest for python2.x

l1 = [1, 2, 3]
l2 = [4, 5, 6, 7]

>>> list(map(sum, zip_longest(l1, l2, fillvalue=0)))
[5, 7, 9, 7]

回答 20

您可以使用此方法,但仅当两个列表的大小相同时,该方法才有效:

first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
third = []

a = len(first)
b = int(0)
while True:
    x = first[b]
    y = second[b]
    ans = x + y
    third.append(ans)
    b = b + 1
    if b == a:
        break

print third

You can use this method but it will work only if both the list are of the same size:

first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
third = []

a = len(first)
b = int(0)
while True:
    x = first[b]
    y = second[b]
    ans = x + y
    third.append(ans)
    b = b + 1
    if b == a:
        break

print third

没有名为_sqlite3的模块

问题:没有名为_sqlite3的模块

我试图在运行Debian 5的VPS上运行Django应用程序。运行演示应用程序时,它返回此错误:

  File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in     import_module
    __import__(name)

  File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in <module>
    raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc)

ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that     order): No module named _sqlite3

查看Python安装,它给出了相同的错误:

Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) 
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in <module>
    from dbapi2 import *
  File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in <module>
    from _sqlite3 import *
ImportError: No module named _sqlite3
>>>

在网上阅读后,我了解到Python 2.5应该附带所有必需的SQLite包装器。我需要重新安装Python,还是有另一种方法来启动和运行此模块?

I am trying to run a Django app on my VPS running Debian 5. When I run a demo app, it comes back with this error:

  File "/usr/local/lib/python2.5/site-packages/django/utils/importlib.py", line 35, in     import_module
    __import__(name)

  File "/usr/local/lib/python2.5/site-packages/django/db/backends/sqlite3/base.py", line 30, in <module>
    raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc)

ImproperlyConfigured: Error loading either pysqlite2 or sqlite3 modules (tried in that     order): No module named _sqlite3

Looking at the Python install, it gives the same error:

Python 2.5.2 (r252:60911, May 12 2009, 07:46:31) 
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.5/sqlite3/__init__.py", line 24, in <module>
    from dbapi2 import *
  File "/usr/local/lib/python2.5/sqlite3/dbapi2.py", line 27, in <module>
    from _sqlite3 import *
ImportError: No module named _sqlite3
>>>

Reading on the web, I learn that Python 2.5 should come with all the necessary SQLite wrappers included. Do I need to reinstall Python, or is there another way to get this module up and running?


回答 0

您的makefile文件似乎没有包含适当的.so文件。您可以按照以下步骤纠正此问题:

  1. 安装sqlite-devel(或libsqlite3-dev在某些基于Debian的系统上)
  2. 使用以下命令重新配置和重新编译Python ./configure --enable-loadable-sqlite-extensions && make && sudo make install

注意

sudo make install部分将把python版本设置为系统范围的标准,这可能会产生无法预料的后果。如果您在工作站上运行此命令,则可能希望将其现有python 一起安装,可以使用来完成sudo make altinstall

It seems your makefile didn’t include the appropriate .so file. You can correct this problem with the steps below:

  1. Install sqlite-devel (or libsqlite3-dev on some Debian-based systems)
  2. Re-configure and re-compiled Python with ./configure --enable-loadable-sqlite-extensions && make && sudo make install

Note

The sudo make install part will set that python version to be the system-wide standard, which can have unforseen consequences. If you run this command on your workstation, you’ll probably want to have it installed alongside the existing python, which can be done with sudo make altinstall.


回答 1

我遇到了同样的问题(python2.5从Ubuntu Lucid上的源代码构建),并import sqlite3抛出了同样的异常。我已经libsqlite3-dev从软件包管理器安装了,重新编译了python2.5,然后导入工作了。

I had the same problem (building python2.5 from source on Ubuntu Lucid), and import sqlite3 threw this same exception. I’ve installed libsqlite3-dev from the package manager, recompiled python2.5, and then the import worked.


回答 2

使用pyenv时,我在Ubuntu上的Python 3.5遇到了相同的问题。

如果您使用pyenv安装python ,则将其列为常见的构建问题之一。要解决此问题,请删除已安装的python版本,安装要求(针对此特殊情况libsqlite3-dev),然后重新安装python版本。

I had the same problem with Python 3.5 on Ubuntu while using pyenv.

If you’re installing the python using pyenv, it’s listed as one of the common build problems. To solve it, remove the installed python version, install the requirements (for this particular case libsqlite3-dev), then reinstall the python version.


回答 3

这就是我为使其正常工作所做的。

我正在使用安装了python 2.7.5的pythonbrew(正在使用pip)。

我首先执行了Zubair(上面)所说的,然后运行了以下命令:

sudo apt-get install libsqlite3-dev

然后我运行以下命令:

pip install pysqlite

这解决了数据库问题,我在运行时得到了确认:

python manager.py syncdb

This is what I did to get it to work.

I am using pythonbrew(which is using pip) with python 2.7.5 installed.

I first did what Zubair(above) said and ran this command:

sudo apt-get install libsqlite3-dev

Then I ran this command:

pip install pysqlite

This fixed the database problem and I got confirmation of this when I ran:

python manager.py syncdb

回答 4

  1. 安装sqlite-devel软件包:

    yum install sqlite-devel -y

  2. 从源代码重新编译python:

    ./configure
    make
    make altinstall
  1. Install the sqlite-devel package:

    yum install sqlite-devel -y

  2. Recompile python from the source:

    ./configure
    make
    make altinstall
    

回答 5

我的_sqlite3.so位于/usr/lib/python2.5/lib-dynload/_sqlite3.so中。从您的路径来看,您应该拥有文件/usr/local/lib/python2.5/lib-dynload/_sqlite3.so。

尝试以下方法:

find /usr/local -name _sqlite3.so

如果找不到该文件,则说明您的Python安装可能有问题。如果是,请确保其安装路径在Python路径中。在Python Shell中,

import sys
print sys.path

就我而言,/usr/lib/python2.5/lib-dynload在列表中,因此它可以找到/usr/lib/python2.5/lib-dynload/_sqlite3.so。

My _sqlite3.so is in /usr/lib/python2.5/lib-dynload/_sqlite3.so. Judging from your paths, you should have the file /usr/local/lib/python2.5/lib-dynload/_sqlite3.so.

Try the following:

find /usr/local -name _sqlite3.so

If the file isn’t found, something may be wrong with your Python installation. If it is, make sure the path it’s installed to is in the Python path. In the Python shell,

import sys
print sys.path

In my case, /usr/lib/python2.5/lib-dynload is in the list, so it’s able to find /usr/lib/python2.5/lib-dynload/_sqlite3.so.


回答 6

我最近尝试在Ubuntu 11.04桌面上安装python 2.6.7,以进行一些开发工作。遇到了与此线程类似的问题。我想通过以下方式修复它:

  1. 调整setup.py文件以包含正确的sqlite开发路径。setup.py中的代码片段:

    def sqlite_incdir:
    sqlite_dirs_to_check = [
    os.path.join(sqlite_incdir, '..', 'lib64'),
    os.path.join(sqlite_incdir, '..', 'lib'),
    os.path.join(sqlite_incdir, '..', '..', 'lib64'),
    os.path.join(sqlite_incdir, '..', '..', 'lib'),
    '/usr/lib/x86_64-linux-gnu/'
    ]

    我添加的位是’/ usr / lib / x86_64-linux-gnu /’。

  2. 运行make之后,我没有收到任何警告,提示未构建sqlite支持(即,它正确构建了:P),但是运行后make install,sqlite3仍未使用相同的“ ImportError: No module named _sqlite3" whe running "import sqlite3” 导入。

    因此,该库已编译,但未移至正确的安装路径,因此我复制了该.so文件(cp /usr/src/python/Python-2.6.7/build/lib.linux-x86_64-2.6/_sqlite3.so /usr/local/python-2.6.7/lib/python2.6/sqlite3/这些是我的构建路径,您可能需要根据设置进行调整)。

瞧!现在支持SQLite3。

I recently tried installing python 2.6.7 on my Ubuntu 11.04 desktop for some dev work. Came across similar problems to this thread. I mamaged to fix it by:

  1. Adjusting the setup.py file to include the correct sqlite dev path. Code snippet from setup.py:

    def sqlite_incdir:
    sqlite_dirs_to_check = [
    os.path.join(sqlite_incdir, '..', 'lib64'),
    os.path.join(sqlite_incdir, '..', 'lib'),
    os.path.join(sqlite_incdir, '..', '..', 'lib64'),
    os.path.join(sqlite_incdir, '..', '..', 'lib'),
    '/usr/lib/x86_64-linux-gnu/'
    ]
    

    With the bit that I added being ‘/usr/lib/x86_64-linux-gnu/’.

  2. After running make I did not get any warnings saying the sqlite support was not built (i.e., it built correctly :P ), but after running make install, sqlite3 still did not import with the same “ImportError: No module named _sqlite3" whe running "import sqlite3“.

    So, the library was compiled, but not moved to the correct installation path, so I copied the .so file (cp /usr/src/python/Python-2.6.7/build/lib.linux-x86_64-2.6/_sqlite3.so /usr/local/python-2.6.7/lib/python2.6/sqlite3/ — these are my build paths, you will probably need to adjust them to your setup).

Voila! SQLite3 support now works.


回答 7

我发现很多人都遇到了这个问题,因为在我自己的vps(cent os 7 x64)上,Multi-version Python是通过以下方式解决的:

  1. 找到文件“ _sqlite3.so”

    find / -name _sqlite3.so

    出: /usr/lib64/python2.7/lib-dynload/_sqlite3.so

  2. 找到您要使用的python标准库的目录,

    为了我 /usr/local/lib/python3.6/lib-dynload

  3. 复制文件:

    cp   /usr/lib64/python2.7/lib-dynload/_sqlite3.so /usr/local/lib/python3.6/lib-dynload

最后,一切都会好的。

I found lots of people meet this problem because the Multi-version Python, on my own vps (cent os 7 x64), I solved it in this way:

  1. Find the file “_sqlite3.so”

    find / -name _sqlite3.so
    

    out: /usr/lib64/python2.7/lib-dynload/_sqlite3.so

  2. Find the dir of python Standard library you want to use,

    for me /usr/local/lib/python3.6/lib-dynload

  3. Copy the file:

    cp   /usr/lib64/python2.7/lib-dynload/_sqlite3.so /usr/local/lib/python3.6/lib-dynload
    

Finally, everything will be ok.


回答 8

这在Redhat Centos 6.5中对我有用:

yum install sqlite-devel
pip install pysqlite

This worked for me in Redhat Centos 6.5:

yum install sqlite-devel
pip install pysqlite

回答 9

我的python是从源代码构建的,原因是在exec配置python版本时缺少选项:3.7.4

./configure --enable-loadable-sqlite-extensions --enable-optimizations
make
make install

固定

my python is build from source, the cause is missing options when exec configure python version:3.7.4

./configure --enable-loadable-sqlite-extensions --enable-optimizations
make
make install

fixed


回答 10

我在FreeBSD 8.1中有问题:

- No module named _sqlite3 -

通过站立端口解决———-

/usr/ports/databases/py-sqlite3

在此之后可以看到:

OK ----------
'>>>' import sqlite3 -----
'>>>' sqlite3.apilevel -----
'2.0'

I have the problem in FreeBSD 8.1:

- No module named _sqlite3 -

It is solved by stand the port ———-

/usr/ports/databases/py-sqlite3

after this one can see:

OK ----------
'>>>' import sqlite3 -----
'>>>' sqlite3.apilevel -----
'2.0'

回答 11

是否安装了python-pysqlite2软件包?

sudo apt-get install python-pysqlite2

Is the python-pysqlite2 package installed?

sudo apt-get install python-pysqlite2

回答 12

检查您的settings.py文件。您是否不仅为数据库引擎编写了“ sqlite”而不是“ sqlite3”?

Checking your settings.py file. Did you not just write “sqlite” instead of “sqlite3” for the database engine?


回答 13

sqlite3Python附带。我也有同样的问题,我只是卸载python3.6并重新安装了它。

卸载现有的python:

sudo apt-get remove --purge python3.6

安装python3.6:

sudo apt install build-essential checkinstall
sudo apt install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz
tar xvf Python-3.6.0.tar.xz
cd Python-3.6.0/
./configure
sudo make altinstall

sqlite3 ships with Python. I also had the same problem, I just uninstalled python3.6 and installed it again.

Uninstall existing python:

sudo apt-get remove --purge python3.6

Install python3.6:

sudo apt install build-essential checkinstall
sudo apt install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
wget https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tar.xz
tar xvf Python-3.6.0.tar.xz
cd Python-3.6.0/
./configure
sudo make altinstall

回答 14

您必须使用centos或redhat并自己编译python,这是python的错误,请在python源代码目录中执行此操作,并在下面执行此操作

curl -sk https://gist.github.com/msabramo/2727063/raw/59ea097a1f4c6f114c32f7743308a061698b17fd/gistfile1.diff | patch -p1

you must be in centos or redhat and compile python yourself, it is python‘s bug do this in your python source code dir and do this below

curl -sk https://gist.github.com/msabramo/2727063/raw/59ea097a1f4c6f114c32f7743308a061698b17fd/gistfile1.diff | patch -p1

回答 15

我遇到了同样的问题,上述问题对我没有任何帮助,但是现在我通过

只是删除python.pipsqlite3并重新安装

  1. sudo apt-get remove python.pip
  2. sudo apt-get remove sqlite3

现在再次安装

  1. sudo apt-get install python.pip
  2. sudo apt-get install sqlite3

在我的情况下sqlite3再次安装时它显示了一些错误,然后我键入

  1. sqlite3

在终端上检查是否已卸下,然后开始拆箱

一旦sqlite3安装了启动终端并写入

  1. sqlite3
  2. database.db (创建数据库)

我相信这一定会对您有帮助

I got the same problem, nothing worked for me from the above ans but now I fixed it by

just remove python.pip and sqlite3 and reinstall

  1. sudo apt-get remove python.pip
  2. sudo apt-get remove sqlite3

now install it again

  1. sudo apt-get install python.pip
  2. sudo apt-get install sqlite3

in my case while installing sqlite3 again it showed some error then I typed

  1. sqlite3

on terminal to check if it was removed or not and it started unpacking it

once the sqlite3 is installed fireup terminal and write

  1. sqlite3
  2. database.db (to create a database)

I’m sure this will definitely help you


回答 16

为登录此页面的任何人提供答案,以寻找适用于Windows OS的解决方案:

如果尚未安装pysqlite3或db-sqlite3,则必须安装。您可以使用以下安装。

  • pip安装pysqlite3
  • pip安装db-sqlite3

对我来说,问题在于sqlite3的DLL文件。

解:

  1. 我从sqlite网站上获取了DLL文件。这可能会因您安装的python版本而异。

  2. 我将其粘贴到env的DLL目录中。对我来说,它是“ C:\ Anaconda \ Lib \ DLLs”,但请检查您的。

Putting answer for anyone who lands on this page searching for a solution for Windows OS:

You have to install pysqlite3 or db-sqlite3 if not already installed. you can use following to install.

  • pip install pysqlite3
  • pip install db-sqlite3

For me the issue was with DLL file of sqlite3.

Solution:

  1. I took DLL file from sqlite site. This might vary based on your version of python installation.

  2. I pasted it in the DLL directory of the env. for me it was “C:\Anaconda\Lib\DLLs”, but check for yours.


回答 17

令我感到失望的是,这个问题一直存在到今天。由于我最近一直在尝试在CentOS 8.1上安装vCD CLI,因此在尝试运行它时出现相同的错误,对此我表示欢迎。在我的情况下,我必须解决的方法如下:

  • 使用适当的前缀从头开始安装SQLite3
  • 清理我的Python安装
  • 运行Make install重新安装Python

正如我一直在做的那样,以创建有关如何安装vCD CLI和VMware Container Service Extension的不同博客文章。我最终捕获了用于解决此问题的步骤,并将其放在单独的博客文章中,网址为:

http://www.virtualizationteam.com/cloud/running-vcd-cli-fail-with-the-following-error-modulenotfounderror-no-module-named-_sqlite3.html

我希望这会有所帮助,因为尽管上面的提示帮助我找到了解决方案,但我不得不将其中的几个结合起来并进行一些修改。

I was disappointed this issue still exist till today. As I have recently been trying to install vCD CLI on CentOS 8.1 and I was welcomed with the same error when tried to run it. The way I had to resolve it in my case is as follow:

  • Install SQLite3 from scratch with the proper prefix
  • Make clean my Python Installation
  • Run Make install to reinstall Python

As I have been doing this to create a different blogpost about how to install vCD CLI and VMware Container Service Extension. I have end up capturing the steps I used to fix the issue and put it in a separate blog post at:

http://www.virtualizationteam.com/cloud/running-vcd-cli-fail-with-the-following-error-modulenotfounderror-no-module-named-_sqlite3.html

I hope this helpful, as while the tips above had helped me get to a solution, I had to combine few of them and modify them a bit.


回答 18

下载sqlite3:

wget http://www.sqlite.org/2016/sqlite-autoconf-3150000.tar.gz

请按照以下步骤进行安装:

$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make install

Download sqlite3:

wget http://www.sqlite.org/2016/sqlite-autoconf-3150000.tar.gz

Follow these steps to install:

$tar xvfz sqlite-autoconf-3071502.tar.gz
$cd sqlite-autoconf-3071502
$./configure --prefix=/usr/local
$make install

回答 19

您需要在python环境中安装pysqlite

    $ pip install pysqlite

You need to install pysqlite in your python environment:

    $ pip install pysqlite

回答 20

尝试复制 _sqlite3.so以便Python可以找到它。

它应该很简单:

cp /usr/lib64/python2.6/lib-dynload/_sqlite3.so /usr/local/lib/python2.7/

相信我,尝试一下。

Try copying _sqlite3.so so that Python can find it.

It should be as simple as:

cp /usr/lib64/python2.6/lib-dynload/_sqlite3.so /usr/local/lib/python2.7/

Trust me, try it.


如何为列表中的每个元素添加一个整数?

问题:如何为列表中的每个元素添加一个整数?

如果我有list=[1,2,3]并且想要添加1到每个元素以获取输出[2,3,4],我该怎么做?

我假设我会使用for循环,但不确定具体如何。

If I have list=[1,2,3] and I want to add 1 to each element to get the output [2,3,4], how would I do that?

I assume I would use a for loop but not sure exactly how.


回答 0

new_list = [x+1 for x in my_list]
new_list = [x+1 for x in my_list]

回答 1

>>> mylist = [1,2,3]
>>> [x+1 for x in mylist]
[2, 3, 4]
>>>

list-comprehensions python

>>> mylist = [1,2,3]
>>> [x+1 for x in mylist]
[2, 3, 4]
>>>

list-comprehensions python.


回答 2

列表理解中的其他答案可能是简单加法的最佳选择,但是如果您有一个更复杂的函数需要将其应用于所有元素,则可以进行映射可能是一个不错的选择。

在您的示例中,它将是:

>>> map(lambda x:x+1, [1,2,3])
[2,3,4]

The other answers on list comprehension are probably the best bet for simple addition, but if you have a more complex function that you needed to apply to all the elements then map may be a good fit.

In your example it would be:

>>> map(lambda x:x+1, [1,2,3])
[2,3,4]

回答 3

如果要使用numpy,则还有另一种方法,如下所示

import numpy as np
list1 = [1,2,3]
list1 = list(np.asarray(list1) + 1)

if you want to use numpy there is another method as follows

import numpy as np
list1 = [1,2,3]
list1 = list(np.asarray(list1) + 1)

回答 4

编辑:这不是就地

首先,不要在变量中使用单词“列表”。它遮盖了关键字list

最好的方法是使用拼接来完成它,请注意[:]表示拼接:

>>> _list=[1,2,3]
>>> _list[:]=[i+1 for i in _list]
>>> _list
[2, 3, 4]

Edit: this isn’t in-place

Firstly don’t use the word ‘list’ for your variable. It shadows the keyword list.

The best way is to do it in place using splicing, note the [:] denotes a splice:

>>> _list=[1,2,3]
>>> _list[:]=[i+1 for i in _list]
>>> _list
[2, 3, 4]

回答 5

>>> [x.__add__(1) for x in [1, 3, 5]]
3: [2, 4, 6]

我的目的是要揭示列表中的项目是否为整数,它支持各种内置函数。

>>> [x.__add__(1) for x in [1, 3, 5]]
3: [2, 4, 6]

My intention here is to expose if the item in the list is an integer it supports various built-in functions.


回答 6

Python 2+:

>>> mylist = [1,2,3]
>>> map(lambda x: x + 1, mylist)
[2, 3, 4]

Python 3+:

>>> mylist = [1,2,3]
>>> list(map(lambda x: x + 1, mylist))
[2, 3, 4]

Python 2+:

>>> mylist = [1,2,3]
>>> map(lambda x: x + 1, mylist)
[2, 3, 4]

Python 3+:

>>> mylist = [1,2,3]
>>> list(map(lambda x: x + 1, mylist))
[2, 3, 4]

回答 7

import numpy as np

np.add([1, 2, 3], 1).tolist()

这使

[2, 3, 4]
import numpy as np

np.add([1, 2, 3], 1).tolist()

which gives

[2, 3, 4]

回答 8

遇到了一种效率不高但独特的方法。因此可以共享它,是的,它需要额外的空间来存储另一个列表。

from operator import add
test_list1 = [4, 5, 6, 2, 10]
test_list2 = [1] * len(test_list1)

res_list = list(map(add, test_list1, test_list2))

print(test_list1)
print(test_list2)
print(res_list)

#### Output ####
[4, 5, 6, 2, 10]
[1, 1, 1, 1, 1]
[5, 6, 7, 3, 11]

Came across a not so efficient, but unique way of doing it. So sharing it across.And yes it requires extra space for another list.

from operator import add
test_list1 = [4, 5, 6, 2, 10]
test_list2 = [1] * len(test_list1)

res_list = list(map(add, test_list1, test_list2))

print(test_list1)
print(test_list2)
print(res_list)

#### Output ####
[4, 5, 6, 2, 10]
[1, 1, 1, 1, 1]
[5, 6, 7, 3, 11]

回答 9

list = [1,2,3,4,5]

for index in range(5):
      list[index] = list[index] +1

print(list)
list = [1,2,3,4,5]

for index in range(len(list)):
      list[index] = list[index] +1

print(list)

回答 10

上面的许多答案都很好。我也看到了一些奇怪的答案,可以胜任这项工作。另外,最后看到的答案是通过正常循环。这种愿意给出答案的意愿将我引向itertoolsnumpy,它们将以不同的方式完成相同的工作。

在这里,我介绍了完成此工作的不同方法,以上未作回答。

import operator
import itertools

x = [3, 5, 6, 7]

integer = 89

"""
Want more vairaint can also use zip_longest from itertools instead just zip
"""
#lazy eval
a = itertools.starmap(operator.add, zip(x, [89] * len(x))) # this is not subscriptable but iterable
print(a)
for i in a:
  print(i, end = ",")


# prepared list
a = list(itertools.starmap(operator.add, zip(x, [89] * len(x)))) # this returns list
print(a)



# With numpy (before this, install numpy if not present with `pip install numpy`)
import numpy

res = numpy.ones(len(x), dtype=int) * integer + x # it returns numpy array
res = numpy.array(x) + integer # you can also use this, infact there are many ways to play around
print(res)
print(res.shape) # prints structure of array, i.e. shape

# if you specifically want a list, then use tolist

res_list = res.tolist()
print(res_list)

输出量

>>> <itertools.starmap object at 0x0000028793490AF0> # output by lazy val
>>> 92,94,95,96,                                     # output of iterating above starmap object
>>> [92, 94, 95, 96]                                 # output obtained by casting to list
>>>                   __
>>> # |\ | |  | |\/| |__| \ /
>>> # | \| |__| |  | |     |
>>> [92 94 95 96]                                    # this is numpy.ndarray object
>>> (4,)                                             # shape of array
>>> [92, 94, 95, 96]                                 # this is a list object (doesn't have a shape)

唯一强调使用numpy是,应该始终对numpy之类的库进行此类操作,因为它对于大型数组而言性能高效。

Many of the answers above are very good. I’ve also seen some weird answers that will do the job. Also, the last answer seen was through a normal loop. This willingness to give answers leads me to itertools and numpy, which will do the same job in a different way.

Here I present different ways to do the job, not answered above.

import operator
import itertools

x = [3, 5, 6, 7]

integer = 89

"""
Want more vairaint can also use zip_longest from itertools instead just zip
"""
#lazy eval
a = itertools.starmap(operator.add, zip(x, [89] * len(x))) # this is not subscriptable but iterable
print(a)
for i in a:
  print(i, end = ",")


# prepared list
a = list(itertools.starmap(operator.add, zip(x, [89] * len(x)))) # this returns list
print(a)



# With numpy (before this, install numpy if not present with `pip install numpy`)
import numpy

res = numpy.ones(len(x), dtype=int) * integer + x # it returns numpy array
res = numpy.array(x) + integer # you can also use this, infact there are many ways to play around
print(res)
print(res.shape) # prints structure of array, i.e. shape

# if you specifically want a list, then use tolist

res_list = res.tolist()
print(res_list)

Output

>>> <itertools.starmap object at 0x0000028793490AF0> # output by lazy val
>>> 92,94,95,96,                                     # output of iterating above starmap object
>>> [92, 94, 95, 96]                                 # output obtained by casting to list
>>>                   __
>>> # |\ | |  | |\/| |__| \ /
>>> # | \| |__| |  | |     |
>>> [92 94 95 96]                                    # this is numpy.ndarray object
>>> (4,)                                             # shape of array
>>> [92, 94, 95, 96]                                 # this is a list object (doesn't have a shape)

My sole reason to highlight the use of numpy is that one should always do such manipulations with libraries like numpy because it is performance efficient for very large arrays.


在Alpine Linux上安装Pillow时,没有这样的文件或目录“ limits.h”

问题:在Alpine Linux上安装Pillow时,没有这样的文件或目录“ limits.h”

我在Raspberry Pi 2上运行alpine-linux。我正在尝试通过以下命令安装Pillow:

pip install pillow

这是命令的输出:

Installing collected packages: pillow
Running setup.py install for pillow
    Complete output from command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-gNq0WA/pillow/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-nDKwei-record/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-armv7l-2.7
    creating build/lib.linux-armv7l-2.7/PIL
    copying PIL/XVThumbImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/XpmImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/XbmImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/WmfImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/WebPImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/WalImageFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/TiffTags.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/TiffImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/TgaImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/TarIO.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/SunImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/SpiderImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/SgiImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PyAccess.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PSDraw.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PsdImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PpmImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PngImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PixarImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PdfImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PcxImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PcfFontFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PcdImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PalmImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PaletteFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/OleFileIO.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/MspImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/MpoImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/MpegImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/MicImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/McIdasImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/JpegPresets.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/JpegImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/Jpeg2KImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/IptcImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImtImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageWin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageTransform.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageTk.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageStat.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageShow.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageSequence.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageQt.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImagePath.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImagePalette.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageOps.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageMorph.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageMode.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageMath.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageGrab.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageFont.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageFilter.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageFileIO.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageEnhance.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageDraw2.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageDraw.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageColor.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageCms.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageChops.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/Image.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/IcoImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/IcnsImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/Hdf5StubImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/GribStubImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/GimpPaletteFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/GimpGradientFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/GifImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/GdImageFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/GbrImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/FpxImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/FontFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/FliImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/FitsStubImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ExifTags.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/EpsImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/DcxImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/CurImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ContainerIO.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/BufrStubImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/BmpImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/BdfFontFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/_util.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/_binary.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/__init__.py -> build/lib.linux-armv7l-2.7/PIL
    running egg_info
    writing Pillow.egg-info/PKG-INFO
    writing top-level names to Pillow.egg-info/top_level.txt
    writing dependency_links to Pillow.egg-info/dependency_links.txt
    warning: manifest_maker: standard file '-c' not found

    reading manifest file 'Pillow.egg-info/SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    warning: no files found matching 'LICENSE' under directory 'docs'
    writing manifest file 'Pillow.egg-info/SOURCES.txt'
    copying PIL/OleFileIO-README.md -> build/lib.linux-armv7l-2.7/PIL
    running build_ext
    building 'PIL._imaging' extension
    creating build/temp.linux-armv7l-2.7/libImaging
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c _imaging.c -o build/temp.linux-armv7l-2.7/_imaging.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c outline.c -o build/temp.linux-armv7l-2.7/outline.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/Bands.c -o build/temp.linux-armv7l-2.7/libImaging/Bands.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/ConvertYCbCr.c -o build/temp.linux-armv7l-2.7/libImaging/ConvertYCbCr.o
    In file included from _imaging.c:76:0:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from outline.c:20:0:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/ConvertYCbCr.c:15:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/Bands.c:19:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/Draw.c -o build/temp.linux-armv7l-2.7/libImaging/Draw.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/Filter.c -o build/temp.linux-armv7l-2.7/libImaging/Filter.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/GifEncode.c -o build/temp.linux-armv7l-2.7/libImaging/GifEncode.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/LzwDecode.c -o build/temp.linux-armv7l-2.7/libImaging/LzwDecode.o
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/Draw.c:35:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/Filter.c:27:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/GifEncode.c:20:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/LzwDecode.c:31:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/Offset.c -o build/temp.linux-armv7l-2.7/libImaging/Offset.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/Quant.c -o build/temp.linux-armv7l-2.7/libImaging/Quant.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/PcxDecode.c -o build/temp.linux-armv7l-2.7/libImaging/PcxDecode.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/RawEncode.c -o build/temp.linux-armv7l-2.7/libImaging/RawEncode.o
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/Offset.c:18:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/Quant.c:21:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/PcxDecode.c:17:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/RawEncode.c:21:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/UnpackYCC.c -o build/temp.linux-armv7l-2.7/libImaging/UnpackYCC.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/ZipEncode.c -o build/temp.linux-armv7l-2.7/libImaging/ZipEncode.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/BoxBlur.c -o build/temp.linux-armv7l-2.7/libImaging/BoxBlur.o
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/UnpackYCC.c:17:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/ZipEncode.c:18:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/BoxBlur.c:1:0:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    Building using 4 processes
    gcc -shared -Wl,--as-needed build/temp.linux-armv7l-2.7/_imaging.o build/temp.linux-armv7l-2.7/decode.o build/temp.linux-armv7l-2.7/encode.o build/temp.linux-armv7l-2.7/map.o build/temp.linux-armv7l-2.7/display.o build/temp.linux-armv7l-2.7/outline.o build/temp.linux-armv7l-2.7/path.o build/temp.linux-armv7l-2.7/libImaging/Access.o build/temp.linux-armv7l-2.7/libImaging/AlphaComposite.o build/temp.linux-armv7l-2.7/libImaging/Resample.o build/temp.linux-armv7l-2.7/libImaging/Bands.o build/temp.linux-armv7l-2.7/libImaging/BitDecode.o build/temp.linux-armv7l-2.7/libImaging/Blend.o build/temp.linux-armv7l-2.7/libImaging/Chops.o build/temp.linux-armv7l-2.7/libImaging/Convert.o build/temp.linux-armv7l-2.7/libImaging/ConvertYCbCr.o build/temp.linux-armv7l-2.7/libImaging/Copy.o build/temp.linux-armv7l-2.7/libImaging/Crc32.o build/temp.linux-armv7l-2.7/libImaging/Crop.o build/temp.linux-armv7l-2.7/libImaging/Dib.o build/temp.linux-armv7l-2.7/libImaging/Draw.o build/temp.linux-armv7l-2.7/libImaging/Effects.o build/temp.linux-armv7l-2.7/libImaging/EpsEncode.o build/temp.linux-armv7l-2.7/libImaging/File.o build/temp.linux-armv7l-2.7/libImaging/Fill.o build/temp.linux-armv7l-2.7/libImaging/Filter.o build/temp.linux-armv7l-2.7/libImaging/FliDecode.o build/temp.linux-armv7l-2.7/libImaging/Geometry.o build/temp.linux-armv7l-2.7/libImaging/GetBBox.o build/temp.linux-armv7l-2.7/libImaging/GifDecode.o build/temp.linux-armv7l-2.7/libImaging/GifEncode.o build/temp.linux-armv7l-2.7/libImaging/HexDecode.o build/temp.linux-armv7l-2.7/libImaging/Histo.o build/temp.linux-armv7l-2.7/libImaging/JpegDecode.o build/temp.linux-armv7l-2.7/libImaging/JpegEncode.o build/temp.linux-armv7l-2.7/libImaging/LzwDecode.o build/temp.linux-armv7l-2.7/libImaging/Matrix.o build/temp.linux-armv7l-2.7/libImaging/ModeFilter.o build/temp.linux-armv7l-2.7/libImaging/MspDecode.o build/temp.linux-armv7l-2.7/libImaging/Negative.o build/temp.linux-armv7l-2.7/libImaging/Offset.o build/temp.linux-armv7l-2.7/libImaging/Pack.o build/temp.linux-armv7l-2.7/libImaging/PackDecode.o build/temp.linux-armv7l-2.7/libImaging/Palette.o build/temp.linux-armv7l-2.7/libImaging/Paste.o build/temp.linux-armv7l-2.7/libImaging/Quant.o build/temp.linux-armv7l-2.7/libImaging/QuantOctree.o build/temp.linux-armv7l-2.7/libImaging/QuantHash.o build/temp.linux-armv7l-2.7/libImaging/QuantHeap.o build/temp.linux-armv7l-2.7/libImaging/PcdDecode.o build/temp.linux-armv7l-2.7/libImaging/PcxDecode.o build/temp.linux-armv7l-2.7/libImaging/PcxEncode.o build/temp.linux-armv7l-2.7/libImaging/Point.o build/temp.linux-armv7l-2.7/libImaging/RankFilter.o build/temp.linux-armv7l-2.7/libImaging/RawDecode.o build/temp.linux-armv7l-2.7/libImaging/RawEncode.o build/temp.linux-armv7l-2.7/libImaging/Storage.o build/temp.linux-armv7l-2.7/libImaging/SunRleDecode.o build/temp.linux-armv7l-2.7/libImaging/TgaRleDecode.o build/temp.linux-armv7l-2.7/libImaging/Unpack.o build/temp.linux-armv7l-2.7/libImaging/UnpackYCC.o build/temp.linux-armv7l-2.7/libImaging/UnsharpMask.o build/temp.linux-armv7l-2.7/libImaging/XbmDecode.o build/temp.linux-armv7l-2.7/libImaging/XbmEncode.o build/temp.linux-armv7l-2.7/libImaging/ZipDecode.o build/temp.linux-armv7l-2.7/libImaging/ZipEncode.o build/temp.linux-armv7l-2.7/libImaging/TiffDecode.o build/temp.linux-armv7l-2.7/libImaging/Incremental.o build/temp.linux-armv7l-2.7/libImaging/Jpeg2KDecode.o build/temp.linux-armv7l-2.7/libImaging/Jpeg2KEncode.o build/temp.linux-armv7l-2.7/libImaging/BoxBlur.o -L/usr/lib -L/usr/local/lib -L/usr/lib -ljpeg -lpython2.7 -o build/lib.linux-armv7l-2.7/PIL/_imaging.so
    gcc: error: build/temp.linux-armv7l-2.7/_imaging.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/decode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/encode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/map.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/display.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/outline.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/path.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Access.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/AlphaComposite.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Resample.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Bands.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/BitDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Blend.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Chops.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Convert.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/ConvertYCbCr.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Copy.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Crc32.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Crop.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Dib.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Draw.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Effects.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/EpsEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/File.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Fill.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Filter.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/FliDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Geometry.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/GetBBox.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/GifDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/GifEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/HexDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Histo.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/JpegDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/JpegEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/LzwDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Matrix.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/ModeFilter.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/MspDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Negative.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Offset.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Pack.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/PackDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Palette.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Paste.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Quant.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/QuantOctree.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/QuantHash.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/QuantHeap.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/PcdDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/PcxDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/PcxEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Point.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/RankFilter.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/RawDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/RawEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Storage.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/SunRleDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/TgaRleDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Unpack.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/UnpackYCC.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/UnsharpMask.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/XbmDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/XbmEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/ZipDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/ZipEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/TiffDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Incremental.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Jpeg2KDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Jpeg2KEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/BoxBlur.o: No such file or directory
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/usr/bin/python -c "import setup tools, tokenize;__file__='/tmp/pip-build-gNq0WA/pillow/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-nDKwei-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-gNq0WA/pillow

我认为这可能是相关的部分:

In file included from libImaging/BoxBlur.c:1:0:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.

我的研究表明,头文件可能与此有关。我已经安装了这些:

apk add py-configobj libusb py-pip python-dev gcc linux-headers
pip install --upgrade pip
pip install -U setuptools
pip install Cheetah
pip install pyusb

I’m running alpine-linux on a Raspberry Pi 2. I’m trying to install Pillow via this command:

pip install pillow

This is the output from the command:

Installing collected packages: pillow
Running setup.py install for pillow
    Complete output from command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-build-gNq0WA/pillow/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-nDKwei-record/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-armv7l-2.7
    creating build/lib.linux-armv7l-2.7/PIL
    copying PIL/XVThumbImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/XpmImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/XbmImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/WmfImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/WebPImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/WalImageFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/TiffTags.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/TiffImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/TgaImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/TarIO.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/SunImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/SpiderImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/SgiImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PyAccess.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PSDraw.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PsdImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PpmImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PngImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PixarImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PdfImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PcxImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PcfFontFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PcdImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PalmImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/PaletteFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/OleFileIO.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/MspImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/MpoImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/MpegImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/MicImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/McIdasImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/JpegPresets.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/JpegImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/Jpeg2KImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/IptcImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImtImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageWin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageTransform.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageTk.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageStat.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageShow.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageSequence.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageQt.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImagePath.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImagePalette.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageOps.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageMorph.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageMode.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageMath.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageGrab.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageFont.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageFilter.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageFileIO.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageEnhance.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageDraw2.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageDraw.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageColor.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageCms.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ImageChops.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/Image.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/IcoImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/IcnsImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/Hdf5StubImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/GribStubImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/GimpPaletteFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/GimpGradientFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/GifImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/GdImageFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/GbrImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/FpxImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/FontFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/FliImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/FitsStubImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ExifTags.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/EpsImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/DcxImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/CurImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/ContainerIO.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/BufrStubImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/BmpImagePlugin.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/BdfFontFile.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/_util.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/_binary.py -> build/lib.linux-armv7l-2.7/PIL
    copying PIL/__init__.py -> build/lib.linux-armv7l-2.7/PIL
    running egg_info
    writing Pillow.egg-info/PKG-INFO
    writing top-level names to Pillow.egg-info/top_level.txt
    writing dependency_links to Pillow.egg-info/dependency_links.txt
    warning: manifest_maker: standard file '-c' not found

    reading manifest file 'Pillow.egg-info/SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    warning: no files found matching 'LICENSE' under directory 'docs'
    writing manifest file 'Pillow.egg-info/SOURCES.txt'
    copying PIL/OleFileIO-README.md -> build/lib.linux-armv7l-2.7/PIL
    running build_ext
    building 'PIL._imaging' extension
    creating build/temp.linux-armv7l-2.7/libImaging
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c _imaging.c -o build/temp.linux-armv7l-2.7/_imaging.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c outline.c -o build/temp.linux-armv7l-2.7/outline.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/Bands.c -o build/temp.linux-armv7l-2.7/libImaging/Bands.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/ConvertYCbCr.c -o build/temp.linux-armv7l-2.7/libImaging/ConvertYCbCr.o
    In file included from _imaging.c:76:0:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from outline.c:20:0:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/ConvertYCbCr.c:15:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/Bands.c:19:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/Draw.c -o build/temp.linux-armv7l-2.7/libImaging/Draw.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/Filter.c -o build/temp.linux-armv7l-2.7/libImaging/Filter.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/GifEncode.c -o build/temp.linux-armv7l-2.7/libImaging/GifEncode.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/LzwDecode.c -o build/temp.linux-armv7l-2.7/libImaging/LzwDecode.o
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/Draw.c:35:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/Filter.c:27:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/GifEncode.c:20:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/LzwDecode.c:31:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/Offset.c -o build/temp.linux-armv7l-2.7/libImaging/Offset.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/Quant.c -o build/temp.linux-armv7l-2.7/libImaging/Quant.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/PcxDecode.c -o build/temp.linux-armv7l-2.7/libImaging/PcxDecode.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/RawEncode.c -o build/temp.linux-armv7l-2.7/libImaging/RawEncode.o
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/Offset.c:18:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/Quant.c:21:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/PcxDecode.c:17:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/RawEncode.c:21:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/UnpackYCC.c -o build/temp.linux-armv7l-2.7/libImaging/UnpackYCC.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/ZipEncode.c -o build/temp.linux-armv7l-2.7/libImaging/ZipEncode.o
    gcc -fno-strict-aliasing -Os -fomit-frame-pointer -DNDEBUG -Os -fomit-frame-pointer -fPIC -DHAVE_LIBJPEG -I/tmp/pip-build-gNq0WA/pillow/libImaging -I/usr/include -I/usr/include/python2.7 -c libImaging/BoxBlur.c -o build/temp.linux-armv7l-2.7/libImaging/BoxBlur.o
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/UnpackYCC.c:17:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/ImPlatform.h:10:0,
                    from libImaging/Imaging.h:14,
                    from libImaging/ZipEncode.c:18:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    In file included from libImaging/BoxBlur.c:1:0:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.
    Building using 4 processes
    gcc -shared -Wl,--as-needed build/temp.linux-armv7l-2.7/_imaging.o build/temp.linux-armv7l-2.7/decode.o build/temp.linux-armv7l-2.7/encode.o build/temp.linux-armv7l-2.7/map.o build/temp.linux-armv7l-2.7/display.o build/temp.linux-armv7l-2.7/outline.o build/temp.linux-armv7l-2.7/path.o build/temp.linux-armv7l-2.7/libImaging/Access.o build/temp.linux-armv7l-2.7/libImaging/AlphaComposite.o build/temp.linux-armv7l-2.7/libImaging/Resample.o build/temp.linux-armv7l-2.7/libImaging/Bands.o build/temp.linux-armv7l-2.7/libImaging/BitDecode.o build/temp.linux-armv7l-2.7/libImaging/Blend.o build/temp.linux-armv7l-2.7/libImaging/Chops.o build/temp.linux-armv7l-2.7/libImaging/Convert.o build/temp.linux-armv7l-2.7/libImaging/ConvertYCbCr.o build/temp.linux-armv7l-2.7/libImaging/Copy.o build/temp.linux-armv7l-2.7/libImaging/Crc32.o build/temp.linux-armv7l-2.7/libImaging/Crop.o build/temp.linux-armv7l-2.7/libImaging/Dib.o build/temp.linux-armv7l-2.7/libImaging/Draw.o build/temp.linux-armv7l-2.7/libImaging/Effects.o build/temp.linux-armv7l-2.7/libImaging/EpsEncode.o build/temp.linux-armv7l-2.7/libImaging/File.o build/temp.linux-armv7l-2.7/libImaging/Fill.o build/temp.linux-armv7l-2.7/libImaging/Filter.o build/temp.linux-armv7l-2.7/libImaging/FliDecode.o build/temp.linux-armv7l-2.7/libImaging/Geometry.o build/temp.linux-armv7l-2.7/libImaging/GetBBox.o build/temp.linux-armv7l-2.7/libImaging/GifDecode.o build/temp.linux-armv7l-2.7/libImaging/GifEncode.o build/temp.linux-armv7l-2.7/libImaging/HexDecode.o build/temp.linux-armv7l-2.7/libImaging/Histo.o build/temp.linux-armv7l-2.7/libImaging/JpegDecode.o build/temp.linux-armv7l-2.7/libImaging/JpegEncode.o build/temp.linux-armv7l-2.7/libImaging/LzwDecode.o build/temp.linux-armv7l-2.7/libImaging/Matrix.o build/temp.linux-armv7l-2.7/libImaging/ModeFilter.o build/temp.linux-armv7l-2.7/libImaging/MspDecode.o build/temp.linux-armv7l-2.7/libImaging/Negative.o build/temp.linux-armv7l-2.7/libImaging/Offset.o build/temp.linux-armv7l-2.7/libImaging/Pack.o build/temp.linux-armv7l-2.7/libImaging/PackDecode.o build/temp.linux-armv7l-2.7/libImaging/Palette.o build/temp.linux-armv7l-2.7/libImaging/Paste.o build/temp.linux-armv7l-2.7/libImaging/Quant.o build/temp.linux-armv7l-2.7/libImaging/QuantOctree.o build/temp.linux-armv7l-2.7/libImaging/QuantHash.o build/temp.linux-armv7l-2.7/libImaging/QuantHeap.o build/temp.linux-armv7l-2.7/libImaging/PcdDecode.o build/temp.linux-armv7l-2.7/libImaging/PcxDecode.o build/temp.linux-armv7l-2.7/libImaging/PcxEncode.o build/temp.linux-armv7l-2.7/libImaging/Point.o build/temp.linux-armv7l-2.7/libImaging/RankFilter.o build/temp.linux-armv7l-2.7/libImaging/RawDecode.o build/temp.linux-armv7l-2.7/libImaging/RawEncode.o build/temp.linux-armv7l-2.7/libImaging/Storage.o build/temp.linux-armv7l-2.7/libImaging/SunRleDecode.o build/temp.linux-armv7l-2.7/libImaging/TgaRleDecode.o build/temp.linux-armv7l-2.7/libImaging/Unpack.o build/temp.linux-armv7l-2.7/libImaging/UnpackYCC.o build/temp.linux-armv7l-2.7/libImaging/UnsharpMask.o build/temp.linux-armv7l-2.7/libImaging/XbmDecode.o build/temp.linux-armv7l-2.7/libImaging/XbmEncode.o build/temp.linux-armv7l-2.7/libImaging/ZipDecode.o build/temp.linux-armv7l-2.7/libImaging/ZipEncode.o build/temp.linux-armv7l-2.7/libImaging/TiffDecode.o build/temp.linux-armv7l-2.7/libImaging/Incremental.o build/temp.linux-armv7l-2.7/libImaging/Jpeg2KDecode.o build/temp.linux-armv7l-2.7/libImaging/Jpeg2KEncode.o build/temp.linux-armv7l-2.7/libImaging/BoxBlur.o -L/usr/lib -L/usr/local/lib -L/usr/lib -ljpeg -lpython2.7 -o build/lib.linux-armv7l-2.7/PIL/_imaging.so
    gcc: error: build/temp.linux-armv7l-2.7/_imaging.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/decode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/encode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/map.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/display.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/outline.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/path.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Access.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/AlphaComposite.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Resample.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Bands.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/BitDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Blend.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Chops.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Convert.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/ConvertYCbCr.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Copy.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Crc32.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Crop.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Dib.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Draw.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Effects.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/EpsEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/File.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Fill.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Filter.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/FliDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Geometry.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/GetBBox.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/GifDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/GifEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/HexDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Histo.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/JpegDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/JpegEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/LzwDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Matrix.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/ModeFilter.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/MspDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Negative.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Offset.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Pack.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/PackDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Palette.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Paste.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Quant.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/QuantOctree.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/QuantHash.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/QuantHeap.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/PcdDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/PcxDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/PcxEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Point.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/RankFilter.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/RawDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/RawEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Storage.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/SunRleDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/TgaRleDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Unpack.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/UnpackYCC.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/UnsharpMask.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/XbmDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/XbmEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/ZipDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/ZipEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/TiffDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Incremental.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Jpeg2KDecode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/Jpeg2KEncode.o: No such file or directory
    gcc: error: build/temp.linux-armv7l-2.7/libImaging/BoxBlur.o: No such file or directory
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
Command "/usr/bin/python -c "import setup tools, tokenize;__file__='/tmp/pip-build-gNq0WA/pillow/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-nDKwei-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-gNq0WA/pillow

I think this is probably the relevant section:

In file included from libImaging/BoxBlur.c:1:0:
    /usr/include/python2.7/Python.h:19:20: fatal error: limits.h: No such file or directory
    #include <limits.h>
                        ^
    compilation terminated.

My research shows it’s probably something with the header files. I have installed these:

apk add py-configobj libusb py-pip python-dev gcc linux-headers
pip install --upgrade pip
pip install -U setuptools
pip install Cheetah
pip install pyusb

回答 0

高山Linux使用musl libc。您可能需要安装musl-dev

Alpine Linux uses musl libc. You probably need to install musl-dev.


回答 1

@zakaria答案是正确的,但是如果您偶然发现

fatal error: linux/limits.h: No such file or directory

那么你需要的包linux-headers(注意前缀linux之前limits.h

apk add linux-headers

@zakaria answer is correct, but if you stumble upon

fatal error: linux/limits.h: No such file or directory

then you need the package linux-headers (notice the prefix linux before limits.h

apk add linux-headers

回答 2

limits.h位于libc-dev

apk add libc-dev

limits.h is located in libc-dev:

apk add libc-dev

回答 3

我在docker pyhton:3.6-alpine image,Alpine linux> = 3.3中安装python库正则表达式时遇到了非常相似的问题。

pip install regex

我必须添加gcc和musl-dev软件包

apk --no-cache add gcc musl-dev

I had very similar problem with installing python library regex in docker pyhton:3.6-alpine image, Alpine linux >= 3.3.

pip install regex

I had to add gcc and musl-dev packages

apk --no-cache add gcc musl-dev

回答 4

我发现有些python软件包无法通过pip install安装,但是如果您安装了相关的alpine linux软件包,它们可以工作。例如,pip install uwsgi无法抱怨limits.h,但是apk add uwsgi-python可以正常工作。建议尝试apk添加py-pillow而不是pip安装枕头。

I’ve found some python packages fail to install via pip install but work if you install the associated alpine linux package. For example pip install uwsgi fails complaining about limits.h, but apk add uwsgi-python works fine. Suggest trying apk add py-pillow instead of pip install pillow.


如何使用.yml文件更新现有的Conda环境

问题:如何使用.yml文件更新现有的Conda环境

如何用另一个.yml文件更新先前的conda环境。在具有多个需求文件(例如)的项目上工作时,这非常有用base.yml, local.yml, production.yml

例如,下面是一个base.yml包含conda-forge,conda和pip软件包的文件:

碱基

name: myenv
channels:
  - conda-forge
dependencies:
  - django=1.10.5
  - pip:
    - django-crispy-forms==1.6.1

实际环境是使用创建的 conda env create -f base.yml

稍后,需要将其他软件包添加到中base.yml。另一个文件,例如local.yml,需要导入这些更新。

先前完成此任务的尝试包括:

创建local.yml具有导入定义的文件:

channels:

dependencies:
  - pip:
    - boto3==1.4.4
imports:
  - requirements/base. 

然后运行命令: conda install -f local.yml

这是行不通的。有什么想法吗?

How can a pre-existing conda environment be updated with another .yml file. This is extremely helpful when working on projects that have multiple requirement files, i.e. base.yml, local.yml, production.yml, etc.

For example, below is a base.yml file has conda-forge, conda, and pip packages:

base.yml

name: myenv
channels:
  - conda-forge
dependencies:
  - django=1.10.5
  - pip:
    - django-crispy-forms==1.6.1

The actual environment is created with: conda env create -f base.yml.

Later on, additional packages need to be added to base.yml. Another file, say local.yml, needs to import those updates.

Previous attempts to accomplish this include:

creating a local.yml file with an import definition:

channels:

dependencies:
  - pip:
    - boto3==1.4.4
imports:
  - requirements/base. 

And then run the command: conda install -f local.yml.

This does not work. Any thoughts?


回答 0

尝试使用conda env update

conda activate myenv
conda env update --file local.yml

或无需激活环境(感谢@NumesSanguis):

conda env update --name myenv --file local.yml

Try using conda env update:

conda activate myenv
conda env update --file local.yml

Or without the need to activate the environment (thanks @NumesSanguis):

conda env update --name myenv --file local.yml

回答 1

建议的答案部分正确。您需要添加–prune选项,以卸载从environment.yml中删除的软件包。正确的命令:

conda env update -f local.yml --prune

The suggested answer is partially correct. You’ll need to add the –prune option to also uninstall packages that were removed from the environment.yml. Correct command:

conda env update -f local.yml --prune

回答 2

alkamid的答案是正确的,但是我发现如果环境已经处于活动状态,则Conda无法安装新的依赖项。停用环境首先可以解决此问题:

source deactivate;
conda env update -f whatever.yml;
source activate my_environment_name; # Must be AFTER the conda env update line!

alkamid’s answer is on the right lines, but I have found that Conda fails to install new dependencies if the environment is already active. Deactivating the environment first resolves this:

source deactivate;
conda env update -f whatever.yml;
source activate my_environment_name; # Must be AFTER the conda env update line!

Python:继续外循环中的下一个迭代

问题:Python:继续外循环中的下一个迭代

我想知道是否有任何内置方法可以继续进行python外循环中的下一次迭代。例如,考虑以下代码:

for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            continue
    ...block1...

我希望此继续语句退出jj循环并转到ii循环中的下一项。我可以通过其他方式(通过设置标志变量)来实现此逻辑,但是有没有简单的方法可以做到这一点,或者这就像要求太多吗?

I wanted to know if there are any built-in ways to continue to next iteration in outer loop in python. For example, consider the code:

for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            continue
    ...block1...

I want this continue statement to exit the jj loop and goto next item in the ii loop. I can implement this logic in some other way (by setting a flag variable), but is there an easy way to do this, or is this like asking for too much?


回答 0

for i in ...:
    for j in ...:
        for k in ...:
            if something:
                # continue loop i

在一般情况下,当您有多个循环级别且break对您不起作用时(因为您要继续上一个循环,而不是当前循环的右上循环),可以执行以下操作之一

将您想转义的循环重构为一个函数

def inner():
    for j in ...:
        for k in ...:
            if something:
                return


for i in ...:
    inner()

缺点是您可能需要将以前在范围内的一些变量传递给该新函数。您既可以将它们作为参数传递,也可以在对象上使它们成为实例变量(如果有意义,仅为此函数创建一个新对象),或者全局变量,单例(无论是什么)(ehm,ehm)。

或者,您可以将其定义inner为嵌套函数,然后使其仅捕获所需的内容(可能会更慢?)

for i in ...:
    def inner():
        for j in ...:
            for k in ...:
                if something:
                    return
    inner()

使用exceptions

从哲学上讲,这就是exceptions,在必要时,通过结构化的编程构建块(如果是,为时,为时)中断程序流。

这样做的好处是您不必将单个代码分成多个部分。如果这是您在用Python编写代码时正在设计的某种计算,那么这很好。在早期引入抽象可能会使您减速。

这种方法的坏处在于,解释器/编译器作者通常会认为异常是exceptions情况,因此会相应地对其进行优化。

class ContinueI(Exception):
    pass


continue_i = ContinueI()

for i in ...:
    try:
        for j in ...:
            for k in ...:
                if something:
                    raise continue_i
    except ContinueI:
        continue

为此创建一个特殊的异常类,这样您就不会冒意外地使某些其他异常消失的风险。

完全其他的东西

我相信还有其他解决方案。

for i in ...:
    for j in ...:
        for k in ...:
            if something:
                # continue loop i

In a general case, when you have multiple levels of looping and break does not work for you (because you want to continue one of the upper loops, not the one right above the current one), you can do one of the following

Refactor the loops you want to escape from into a function

def inner():
    for j in ...:
        for k in ...:
            if something:
                return


for i in ...:
    inner()

The disadvantage is that you may need to pass to that new function some variables, which were previously in scope. You can either just pass them as parameters, make them instance variables on an object (create a new object just for this function, if it makes sense), or global variables, singletons, whatever (ehm, ehm).

Or you can define inner as a nested function and let it just capture what it needs (may be slower?)

for i in ...:
    def inner():
        for j in ...:
            for k in ...:
                if something:
                    return
    inner()

Use exceptions

Philosophically, this is what exceptions are for, breaking the program flow through the structured programming building blocks (if, for, while) when necessary.

The advantage is that you don’t have to break the single piece of code into multiple parts. This is good if it is some kind of computation that you are designing while writing it in Python. Introducing abstractions at this early point may slow you down.

Bad thing with this approach is that interpreter/compiler authors usually assume that exceptions are exceptional and optimize for them accordingly.

class ContinueI(Exception):
    pass


continue_i = ContinueI()

for i in ...:
    try:
        for j in ...:
            for k in ...:
                if something:
                    raise continue_i
    except ContinueI:
        continue

Create a special exception class for this, so that you don’t risk accidentally silencing some other exception.

Something else entirely

I am sure there are still other solutions.


回答 1

for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            break
    else:
        ...block1...

Break 将中断内部循环,并且不会执行block1(仅在内部循环正常退出时才会运行)。

for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            break
    else:
        ...block1...

Break will break the inner loop, and block1 won’t be executed (it will run only if the inner loop is exited normally).


回答 2

在其他语言中,您可以标记循环并从标记循环中中断。 Python增强提案(PEP)3136建议将它们添加到Python中,Guido拒绝了它

但是,我拒绝这样的理由是,如此复杂的代码很少需要此功能。在大多数情况下,现有的变通办法可以生成干净的代码,例如使用“返回”。虽然我确信在某些(罕见)实际情况下,代码的清晰性会受到重构的影响,从而可以使用return,但是这被两个问题抵消了:

  1. 复杂性永久地增加了语言。这不仅会影响所有Python实现,而且会影响每个源代码分析工具,当然还会影响该语言的所有文档。

  2. 我期望该功能的滥用程度将超过其正确使用的程度,从而导致代码清晰度净下降(此后对所有编写的Python代码进行衡量)。懒惰的程序员无处不在,在您不了解它之前,您就难以理解难以理解的代码。

因此,如果那是您希望自己没有运气的原因,请查看其他答案之一,因为那里有不错的选择。

In other languages you can label the loop and break from the labelled loop. Python Enhancement Proposal (PEP) 3136 suggested adding these to Python but Guido rejected it:

However, I’m rejecting it on the basis that code so complicated to require this feature is very rare. In most cases there are existing work-arounds that produce clean code, for example using ‘return’. While I’m sure there are some (rare) real cases where clarity of the code would suffer from a refactoring that makes it possible to use return, this is offset by two issues:

  1. The complexity added to the language, permanently. This affects not only all Python implementations, but also every source analysis tool, plus of course all documentation for the language.

  2. My expectation that the feature will be abused more than it will be used right, leading to a net decrease in code clarity (measured across all Python code written henceforth). Lazy programmers are everywhere, and before you know it you have an incredible mess on your hands of unintelligible code.

So if that’s what you were hoping for you’re out of luck, but look at one of the other answers as there are good options there.


回答 3

我认为您可以执行以下操作:

for ii in range(200):
    restart = False
    for jj in range(200, 400):
        ...block0...
        if something:
            restart = True
            break
    if restart:
        continue
    ...block1...

I think you could do something like this:

for ii in range(200):
    restart = False
    for jj in range(200, 400):
        ...block0...
        if something:
            restart = True
            break
    if restart:
        continue
    ...block1...

回答 4

我认为最简单的方法之一是用“ break”语句代替“ continue”,即

for ii in range(200):
 for jj in range(200, 400):
    ...block0...
    if something:
        break
 ...block1...       

例如,以下是简单的代码,可查看其运行的确切情况:

for i in range(10):
    print("doing outer loop")
    print("i=",i)
    for p in range(10):
        print("doing inner loop")
        print("p=",p)
        if p==3:
            print("breaking from inner loop")
            break
    print("doing some code in outer loop")

I think one of the easiest ways to achieve this is to replace “continue” with “break” statement,i.e.

for ii in range(200):
 for jj in range(200, 400):
    ...block0...
    if something:
        break
 ...block1...       

For example, here is the easy code to see how exactly it goes on:

for i in range(10):
    print("doing outer loop")
    print("i=",i)
    for p in range(10):
        print("doing inner loop")
        print("p=",p)
        if p==3:
            print("breaking from inner loop")
            break
    print("doing some code in outer loop")

回答 5

解决此类问题的另一种方法是使用Exception()。

for ii in range(200):
    try:
        for jj in range(200, 400):
            ...block0...
            if something:
                raise Exception()
    except Exception:
        continue
    ...block1...

例如:

for n in range(1,4):
    for m in range(1,4):
        print n,'-',m

结果:

    1-1
    1-2
    1-3
    2-1
    2-2
    2-3
    3-1
    3-2
    3-3

假设如果m = 3,我们想从m循环跳转到外部n循环:

for n in range(1,4):
    try:
        for m in range(1,4):
            if m == 3:
                raise Exception()            
            print n,'-',m
    except Exception:
        continue

结果:

    1-1
    1-2
    2-1
    2-2
    3-1
    3-2

参考链接:http : //www.programming-idioms.org/idiom/42/continue-outer-loop/1264/python

Another way to deal with this kind of problem is to use Exception().

for ii in range(200):
    try:
        for jj in range(200, 400):
            ...block0...
            if something:
                raise Exception()
    except Exception:
        continue
    ...block1...

For example:

for n in range(1,4):
    for m in range(1,4):
        print n,'-',m

result:

    1-1
    1-2
    1-3
    2-1
    2-2
    2-3
    3-1
    3-2
    3-3

Assuming we want to jump to the outer n loop from m loop if m =3:

for n in range(1,4):
    try:
        for m in range(1,4):
            if m == 3:
                raise Exception()            
            print n,'-',m
    except Exception:
        continue

result:

    1-1
    1-2
    2-1
    2-2
    3-1
    3-2

Reference link:http://www.programming-idioms.org/idiom/42/continue-outer-loop/1264/python


回答 6

我们想找到一些东西,然后停止内部迭代。我使用标志系统。

for l in f:
    flag = True
    for e in r:
        if flag==False:continue
        if somecondition:
            do_something()
            flag=False

We want to find something and then stop the inner iteration. I use a flag system.

for l in f:
    flag = True
    for e in r:
        if flag==False:continue
        if somecondition:
            do_something()
            flag=False

回答 7

我只是做了这样的事情。我对此的解决方案是用列表理解替换内部for循环。

for ii in range(200):
    done = any([op(ii, jj) for jj in range(200, 400)])
    ...block0...
    if done:
        continue
    ...block1...

其中op是作用于ii和jj组合的布尔运算符。就我而言,如果任何操作返回true,我就完成了。

这实际上与将代码分解为一个函数没有什么不同,但是我认为使用“ any”运算符对布尔值列表进行逻辑或,然后全部执行逻辑是很有趣的。它还避免了函数调用。

I just did something like this. My solution for this was to replace the interior for loop with a list comprehension.

for ii in range(200):
    done = any([op(ii, jj) for jj in range(200, 400)])
    ...block0...
    if done:
        continue
    ...block1...

where op is some boolean operator acting on a combination of ii and jj. In my case, if any of the operations returned true, I was done.

This is really not that different from breaking the code out into a function, but I thought that using the “any” operator to do a logical OR on a list of booleans and doing the logic all in one line was interesting. It also avoids the function call.


Python在一个列表中查找不在另一个列表中的元素[重复]

问题:Python在一个列表中查找不在另一个列表中的元素[重复]

我需要比较两个列表,以便创建在一个列表中找到但不在另一个列表中找到的特定元素的新列表。例如:

main_list=[]
list_1=["a", "b", "c", "d", "e"]
list_2=["a", "f", "c", "m"] 

我想遍历list_1,并将list_2中所有在list_1中找不到的元素附加到main_list。

结果应为:

main_list=["f", "m"]

如何使用python做到这一点?

I need to compare two lists in order to create a new list of specific elements found in one list but not in the other. For example:

main_list=[]
list_1=["a", "b", "c", "d", "e"]
list_2=["a", "f", "c", "m"] 

I want to loop through list_1 and append to main_list all the elements from list_2 that are not found in list_1.

The result should be:

main_list=["f", "m"]

How can I do it with python?


回答 0

TL; DR:
解决方案(1)

import numpy as np
main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`

解决方案(2) 您需要一个排序列表

def setdiff_sorted(array1,array2,assume_unique=False):
    ans = np.setdiff1d(array1,array2,assume_unique).tolist()
    if assume_unique:
        return sorted(ans)
    return ans
main_list = setdiff_sorted(list_2,list_1)




说明:
(1)可以使用与NumPy的setdiff1darray1array2assume_unique= False)。

assume_unique询问用户数组是否已经唯一。
如果为False,则首先确定唯一元素。
如果为True,则函数将假定元素已经是唯一的,并且函数将跳过确定唯一元素的操作。

这产生了独特的值array1不是array2assume_uniqueFalse默认。

如果您担心 唯一元素(基于Chinny84响应),则只需使用(其中assume_unique=False=>默认值):

import numpy as np
list_1 = ["a", "b", "c", "d", "e"]
list_2 = ["a", "f", "c", "m"] 
main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`


(2) 对于想要对答案进行排序的人,我做了一个自定义函数:

import numpy as np
def setdiff_sorted(array1,array2,assume_unique=False):
    ans = np.setdiff1d(array1,array2,assume_unique).tolist()
    if assume_unique:
        return sorted(ans)
    return ans

要获得答案,请运行:

main_list = setdiff_sorted(list_2,list_1)

旁注:
(a)解决方案2(自定义函数setdiff_sorted)返回一个列表(与解决方案1中的数组相比)。

(b)如果不确定这些元素是否唯一,则只需setdiff1d在解决方案A和B中都使用NumPy的默认设置。并发症的例子是什么?见注释(c)。

(c)如果两个列表中的任何一个都不唯一,情况将有所不同。
list_2的不是唯一的:list2 = ["a", "f", "c", "m", "m"]。保持list1原样:list_1 = ["a", "b", "c", "d", "e"]
设置assume_uniqueyields 的默认值["f", "m"](在两种解决方案中)。但是,如果您设置了assume_unique=True,两种解决方案都可以["f", "m", "m"]。为什么?这是因为用户认为元素是唯一的)。因此,最好保持assume_unique为其默认值。请注意,两个答案均已排序。

TL;DR:
SOLUTION (1)

import numpy as np
main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`

SOLUTION (2) You want a sorted list

def setdiff_sorted(array1,array2,assume_unique=False):
    ans = np.setdiff1d(array1,array2,assume_unique).tolist()
    if assume_unique:
        return sorted(ans)
    return ans
main_list = setdiff_sorted(list_2,list_1)




EXPLANATIONS:
(1) You can use NumPy’s setdiff1d (array1,array2,assume_unique=False).

assume_unique asks the user IF the arrays ARE ALREADY UNIQUE.
If False, then the unique elements are determined first.
If True, the function will assume that the elements are already unique AND function will skip determining the unique elements.

This yields the unique values in array1 that are not in array2. assume_unique is False by default.

If you are concerned with the unique elements (based on the response of Chinny84), then simply use (where assume_unique=False => the default value):

import numpy as np
list_1 = ["a", "b", "c", "d", "e"]
list_2 = ["a", "f", "c", "m"] 
main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`


(2) For those who want answers to be sorted, I’ve made a custom function:

import numpy as np
def setdiff_sorted(array1,array2,assume_unique=False):
    ans = np.setdiff1d(array1,array2,assume_unique).tolist()
    if assume_unique:
        return sorted(ans)
    return ans

To get the answer, run:

main_list = setdiff_sorted(list_2,list_1)

SIDE NOTES:
(a) Solution 2 (custom function setdiff_sorted) returns a list (compared to an array in solution 1).

(b) If you aren’t sure if the elements are unique, just use the default setting of NumPy’s setdiff1d in both solutions A and B. What can be an example of a complication? See note (c).

(c) Things will be different if either of the two lists is not unique.
Say list_2 is not unique: list2 = ["a", "f", "c", "m", "m"]. Keep list1 as is: list_1 = ["a", "b", "c", "d", "e"]
Setting the default value of assume_unique yields ["f", "m"] (in both solutions). HOWEVER, if you set assume_unique=True, both solutions give ["f", "m", "m"]. Why? This is because the user ASSUMED that the elements are unique). Hence, IT IS BETTER TO KEEP assume_unique to its default value. Note that both answers are sorted.


回答 1

您可以使用集:

main_list = list(set(list_2) - set(list_1))

输出:

>>> list_1=["a", "b", "c", "d", "e"]
>>> list_2=["a", "f", "c", "m"]
>>> set(list_2) - set(list_1)
set(['m', 'f'])
>>> list(set(list_2) - set(list_1))
['m', 'f']

根据@JonClements的评论,这是一个更简洁的版本:

>>> list_1=["a", "b", "c", "d", "e"]
>>> list_2=["a", "f", "c", "m"]
>>> list(set(list_2).difference(list_1))
['m', 'f']

You can use sets:

main_list = list(set(list_2) - set(list_1))

Output:

>>> list_1=["a", "b", "c", "d", "e"]
>>> list_2=["a", "f", "c", "m"]
>>> set(list_2) - set(list_1)
set(['m', 'f'])
>>> list(set(list_2) - set(list_1))
['m', 'f']

Per @JonClements’ comment, here is a tidier version:

>>> list_1=["a", "b", "c", "d", "e"]
>>> list_2=["a", "f", "c", "m"]
>>> list(set(list_2).difference(list_1))
['m', 'f']

回答 2

不知道为什么当您拥有本机方法时,上述说明为何如此复杂:

main_list = list(set(list_2)-set(list_1))

Not sure why the above explanations are so complicated when you have native methods available:

main_list = list(set(list_2)-set(list_1))

回答 3

使用这样的列表理解

main_list = [item for item in list_2 if item not in list_1]

输出:

>>> list_1 = ["a", "b", "c", "d", "e"]
>>> list_2 = ["a", "f", "c", "m"] 
>>> 
>>> main_list = [item for item in list_2 if item not in list_1]
>>> main_list
['f', 'm']

编辑:

就像下面的注释中提到的那样,如果列表很大,则以上并不是理想的解决方案。在这种情况下,更好的选择是转换list_1set第一个:

set_1 = set(list_1)  # this reduces the lookup time from O(n) to O(1)
main_list = [item for item in list_2 if item not in set_1]

Use a list comprehension like this:

main_list = [item for item in list_2 if item not in list_1]

Output:

>>> list_1 = ["a", "b", "c", "d", "e"]
>>> list_2 = ["a", "f", "c", "m"] 
>>> 
>>> main_list = [item for item in list_2 if item not in list_1]
>>> main_list
['f', 'm']

Edit:

Like mentioned in the comments below, with large lists, the above is not the ideal solution. When that’s the case, a better option would be converting list_1 to a set first:

set_1 = set(list_1)  # this reduces the lookup time from O(n) to O(1)
main_list = [item for item in list_2 if item not in set_1]

回答 4

如果您想要一种单线解决方案(忽略导入),该解决方案仅需要O(max(n, m))长度n和长度输入工作,m而不需要O(n * m)工作,则可以使用以下itertools模块

from itertools import filterfalse

main_list = list(filterfalse(set(list_1).__contains__, list_2))

这利用了功能函数在构造上采用回调函数的优势,从而允许它创建一次回调并在每个元素中重用它,而无需将其存储在某个位置(因为filterfalse在内部存储);列表推导和生成器表达式可以做到这一点,但这很丑陋。†

在一行中得到与以下结果相同的结果:

main_list = [x for x in list_2 if x not in list_1]

速度:

set_1 = set(list_1)
main_list = [x for x in list_2 if x not in set_1]

当然,如果比较是按位置进行的,则:

list_1 = [1, 2, 3]
list_2 = [2, 3, 4]

应该生成:

main_list = [2, 3, 4]

(因为in list_2中的值与in 中的相同索引相匹配list_1),您绝对应该使用Patrick的答案,该答案不涉及临时lists或sets(即使sets大致相同O(1),它们每张支票的“常数”因数也比简单的等式支票高) )并且涉及O(min(n, m))工作,比其他任何答案都要少,并且如果您的问题对位置敏感,则是唯一正确的答案当匹配元素以不匹配的偏移量出现时解决方案。

†:使用列表理解来做与单行代码相同的方法是滥用嵌套循环以在“最外层”循环中创建和缓存值,例如:

main_list = [x for set_1 in (set(list_1),) for x in list_2 if x not in set_1]

这也给Python 3带来了次要的性能优势(因为现在set_1它在理解代码中处于本地范围内,而不是从每次检查的嵌套范围中查找;在Python 2上则没有关系,因为Python 2并未使用闭包列出理解;它们的作用范围与所使用的作用域相同)。

If you want a one-liner solution (ignoring imports) that only requires O(max(n, m)) work for inputs of length n and m, not O(n * m) work, you can do so with the itertools module:

from itertools import filterfalse

main_list = list(filterfalse(set(list_1).__contains__, list_2))

This takes advantage of the functional functions taking a callback function on construction, allowing it to create the callback once and reuse it for every element without needing to store it somewhere (because filterfalse stores it internally); list comprehensions and generator expressions can do this, but it’s ugly.†

That gets the same results in a single line as:

main_list = [x for x in list_2 if x not in list_1]

with the speed of:

set_1 = set(list_1)
main_list = [x for x in list_2 if x not in set_1]

Of course, if the comparisons are intended to be positional, so:

list_1 = [1, 2, 3]
list_2 = [2, 3, 4]

should produce:

main_list = [2, 3, 4]

(because no value in list_2 has a match at the same index in list_1), you should definitely go with Patrick’s answer, which involves no temporary lists or sets (even with sets being roughly O(1), they have a higher “constant” factor per check than simple equality checks) and involves O(min(n, m)) work, less than any other answer, and if your problem is position sensitive, is the only correct solution when matching elements appear at mismatched offsets.

†: The way to do the same thing with a list comprehension as a one-liner would be to abuse nested looping to create and cache value(s) in the “outermost” loop, e.g.:

main_list = [x for set_1 in (set(list_1),) for x in list_2 if x not in set_1]

which also gives a minor performance benefit on Python 3 (because now set_1 is locally scoped in the comprehension code, rather than looked up from nested scope for each check; on Python 2 that doesn’t matter, because Python 2 doesn’t use closures for list comprehensions; they operate in the same scope they’re used in).


回答 5

main_list=[]
list_1=["a", "b", "c", "d", "e"]
list_2=["a", "f", "c", "m"]

for i in list_2:
    if i not in list_1:
        main_list.append(i)

print(main_list)

输出:

['f', 'm']
main_list=[]
list_1=["a", "b", "c", "d", "e"]
list_2=["a", "f", "c", "m"]

for i in list_2:
    if i not in list_1:
        main_list.append(i)

print(main_list)

output:

['f', 'm']

回答 6

我会将zip这些列表放在一起,以逐个元素比较它们。

main_list = [b for a, b in zip(list1, list2) if a!= b]

I would zip the lists together to compare them element by element.

main_list = [b for a, b in zip(list1, list2) if a!= b]

回答 7

我使用了两种方法,发现一种方法比其他方法有用。这是我的答案:

我的输入数据:

crkmod_mpp = ['M13','M18','M19','M24']
testmod_mpp = ['M13','M14','M15','M16','M17','M18','M19','M20','M21','M22','M23','M24']

方法1:np.setdiff1d我喜欢这种方法,因为它保留了位置

test= list(np.setdiff1d(testmod_mpp,crkmod_mpp))
print(test)
['M15', 'M16', 'M22', 'M23', 'M20', 'M14', 'M17', 'M21']

方法2:尽管给出的答案与方法1相同,但扰乱了顺序

test = list(set(testmod_mpp).difference(set(crkmod_mpp)))
print(test)
['POA23', 'POA15', 'POA17', 'POA16', 'POA22', 'POA18', 'POA24', 'POA21']

方法1完全np.setdiff1d符合我的要求。此答案仅供参考。

I used two methods and I found one method useful over other. Here is my answer:

My input data:

crkmod_mpp = ['M13','M18','M19','M24']
testmod_mpp = ['M13','M14','M15','M16','M17','M18','M19','M20','M21','M22','M23','M24']

Method1: np.setdiff1d I like this approach over other because it preserves the position

test= list(np.setdiff1d(testmod_mpp,crkmod_mpp))
print(test)
['M15', 'M16', 'M22', 'M23', 'M20', 'M14', 'M17', 'M21']

Method2: Though it gives same answer as in Method1 but disturbs the order

test = list(set(testmod_mpp).difference(set(crkmod_mpp)))
print(test)
['POA23', 'POA15', 'POA17', 'POA16', 'POA22', 'POA18', 'POA24', 'POA21']

Method1 np.setdiff1d meets my requirements perfectly. This answer for information.


回答 8

如果应该考虑发生的次数,则可能需要使用类似以下内容的方法collections.Counter

list_1=["a", "b", "c", "d", "e"]
list_2=["a", "f", "c", "m"] 
from collections import Counter
cnt1 = Counter(list_1)
cnt2 = Counter(list_2)
final = [key for key, counts in cnt2.items() if cnt1.get(key, 0) != counts]

>>> final
['f', 'm']

如所承诺的,这也可以将不同的出现次数称为“差异”:

list_1=["a", "b", "c", "d", "e", 'a']
cnt1 = Counter(list_1)
cnt2 = Counter(list_2)
final = [key for key, counts in cnt2.items() if cnt1.get(key, 0) != counts]

>>> final
['a', 'f', 'm']

If the number of occurences should be taken into account you probably need to use something like collections.Counter:

list_1=["a", "b", "c", "d", "e"]
list_2=["a", "f", "c", "m"] 
from collections import Counter
cnt1 = Counter(list_1)
cnt2 = Counter(list_2)
final = [key for key, counts in cnt2.items() if cnt1.get(key, 0) != counts]

>>> final
['f', 'm']

As promised this can also handle differing number of occurences as “difference”:

list_1=["a", "b", "c", "d", "e", 'a']
cnt1 = Counter(list_1)
cnt2 = Counter(list_2)
final = [key for key, counts in cnt2.items() if cnt1.get(key, 0) != counts]

>>> final
['a', 'f', 'm']

回答 9

从ser1中删除ser2中存在的项目。

输入项

ser1 = pd.Series([1、2、3、4、5])ser2 = pd.Series([4、5、6、7、8])

ser1 [〜ser1.isin(ser2)]

From ser1 remove items present in ser2.

Input

ser1 = pd.Series([1, 2, 3, 4, 5]) ser2 = pd.Series([4, 5, 6, 7, 8])

Solution

ser1[~ser1.isin(ser2)]


有趣好用的Python教程

退出移动版
微信支付
请使用 微信 扫码支付