Python多线程,当项目从文件排队时,工作人员表现出异常

问题描述 投票:0回答:1

下面是我的测试程序。我的numberfile.txt包含一列从1到50的数字。我的期望是不应该打印1,但它正在被打印。如果我将输入更改为从1到50的整数列表,而不是从文件中读取,则不会打印1。有人可以帮助我维持这种奇怪的行为。

from threading import Thread
from Queue import Queue

inputfile = "numberfile.txt"

NUM_WORKERS = 5
q = Queue()

def test(item):
    if item == '1':
        return
    print item

def worker():
    while True:
        item = q.get()
        test(item)
        q.task_done()

def main():

    for _ in range(NUM_WORKERS):
        t = Thread(target=worker)
        t.daemon = True
        t.start()
    with open(inputfile,'r') as f:
        line = f.readline()
        while line:
            q.put(line)
            line = f.readline()

    q.join()

输出:

1
2


3
.
.
.
50
python multithreading
1个回答
1
投票

Readline(或for ln in f)返回字符串include行尾字符。例如:

> cat foo
1
2
3
4
5

所以:

In [7]: with open('foo') as f: 
   ...:     for ln in f: 
   ...:         for c in ln: 
   ...:             print(ord(c), end=' ') 
   ...:         print() 
   ...:                                                                                                  
49 10 
50 10 
51 10 
52 10 
53 10 

In [8]: chr(10)                                                                                          
Out[8]: '\n'

一种可能的解决方法是在比较之前先行strip()

© www.soinside.com 2019 - 2024. All rights reserved.