Python-如何为不同的函数赋值

时间:2018-12-13 10:56:15

标签: python multithreading for-loop

我一直试图在每个函数之间发送值。我创建了一个代码:

def filter(thread, i):

    text = "NAME".lower()

    has_good = False
    positive_keywords = i

    for ch in ['&', '#', '“', '”', '"', '*', '`', '*', '’', '-']:
        if ch in text:
            text = text.replace(ch, "")

    sentences = [text]

    def check_all(sentence, ws):
        return all(re.search(r'\b{}\b'.format(w), sentence) for w in ws)

    for sentence in sentences:
        if any(check_all(sentence, word.split('+')) for word in positive_keywords):
            has_good = True
            break

    if not has_good:
        sys.exit()

def testscript(thread, i):
    filter(thread, i)

def script():
    old_list = []

    old_names_list = []

    while True:
        new_names_list = [line.rstrip('\n') for line in open('names.txt')]

        for new_thread in get_random_names(): #A function that contians 100 random names

            if not new_names_list == old_names_list: 
                for i in new_names_list:
                    if not i in old_names_list:
                        threading.Thread(target=testscript, args=(new_thread, i)).start()
                old_names_list = new_names_list


            elif new_thread not in old_list: #If the names are not added in old_list. start new thread.
                threading.Thread(target=testscript, args=(new_thread,)).start()
                old_list.append(new_thread)

        else:
            randomtime = random.randint(1, 3)
            time.sleep(randomtime)

代码如下:它以script()开始。它会检查我的txt文件是否变大,是否可以threading.Thread(target=testscript, args=(new_thread, i)).start()-如果文本文件中找不到任何内容,则应该做elif new_thread not in old_list:

但是我现在的问题是,在elif中,它不包含名称(在我们的情况下为I),而在if not new_names_list == old_names_list:中,它包含i。意味着我有时需要发送i,有时不需要。问题是没有名字时。它会给我一个missing 1 required positional argument: 'i'的错误,这是由于没有名称。如果没有值,我该如何向线程发送值?

1 个答案:

答案 0 :(得分:1)

如果将def testscript(thread,i):更改为

def testscript(thread, i=""): 

然后,您可以调用testscript,并且如果不传递第二个参数,则第二个参数将默认为空字符串(您可以将其默认为任意值):

threading.Thread(target=testscript, args=(new_thread)).start() # when testscript receives this, it will just default i="" and pass that to filter

然后它将传递空字符串进行过滤,在这种情况下,我认为您是

if any(check_all(sentence, word.split('+')) for word in positive_keywords):

如果为positive_keywords提供空字符串(否则选择一个始终导致返回false的值),它将返回false,它将继续到sys.exit。

或者,您也可以使用args *或kwargs **并检查testscript中是否有第二个输入,如果没有,请检查sys.exit或调整过滤器以仅分配肯定关键字并在有提示时输入该句子块我。