简体   繁体   English

如何线程化两个函数,其中一个 output 影响其他动作

[英]How to thread two functions where one output effect the others actions

Here's my code:这是我的代码:

import time
import keyboard #pip install keyboard - could use pynput listener instead.
from threading import Thread

hshtag = int(0)
done = False
fire = False


def StopStart(fire):
    while not done:
        global fire
        if keyboard.is_pressed('#'):
            hshtag = hshtag + 1
            if hshtag % 2 ==0:
                fire = False
            else:
                fire = True
        return fire


def NormalFire():
    while not done:
        global fire
        if fire == True:
            #do x        
        else:
            pass

t1 = Thread(target = StopStart)
t2 = Thread(target = NormalFire(fire))
t1.start()
t2.start()

The problem is function StopStart (should) effect what function Normalfire does but as the function only accepts a value for fire when it starts running (so it doesn't work). 问题是 function StopStart (应该)影响 function Normalfire 的作用,但正如 function 开始运行时只接受工作值。 What I want is change what function normalfire does with function stopstart. 我想要的是改变 function normalfire 对 function stopstart 所做的事情。 and if you're wondering why I am using threading it because '#do x' actually takes a while to work so as one continuous script if I clicked hash at the wrong time it wouldn't stop. 如果您想知道为什么我使用线程化它,因为如果我在错误的时间单击 hash,“#do x”实际上需要一段时间才能作为一个连续脚本工作,它不会停止。 Maybe I could do this with classes instead but im not good with classes so if someone could either help with that or fix the above code that would be great thanks. 也许我可以用类来做到这一点,但我对类不擅长,所以如果有人可以帮助解决这个问题或修复上面的代码,那将非常感谢。

New attempt at explaining what's wrong with the top code - Ok, so both functions should be running simultaneously (which they are) - so no problems there.解释顶部代码有什么问题的新尝试 - 好的,所以两个函数应该同时运行(它们是) - 所以那里没有问题。 but as the function StopStart changes the boolean fire to true/false I want that to cause my NormalFire function to change what it is doing - nothing when I haven't clicked hash yet and something if I've clicked hash once but if I then click hash while its running it will finish whats its running then do nothing waiting for hash to be clicked again. but as the function StopStart changes the boolean fire to true/false I want that to cause my NormalFire function to change what it is doing - nothing when I haven't clicked hash yet and something if I've clicked hash once but if I then在运行时单击 hash,它将完成其运行,然后什么也不做,等待再次单击 hash。

Sorry, my question wasn't clear take this code as a simplification of my core question.抱歉,我的问题不清楚,请将此代码简化为我的核心问题。

##imports
import time
import keyboard #pip install keyboard - could use pynput listener instead.
from threading import Thread

##variable assigning
hshtag = int(0)
done = False
fire = False


def x():
    while not done:
        fire = True
        return fire

def y(fire):
    while not done:
        if fire:
            print('ok')                   
        else:
            pass

t1 = Thread(target = x)
t2 = Thread(target = y(fire))
t1.start()
t2.start()

Currently, the above code outputs nothing even though I've set 'fire = true' in function x and returned it how would I edit this code so that when boolean fire changes to true the function y starts printing ok?目前,即使我在 function x 中设置了 'fire = true' 并返回它,上面的代码也没有输出任何内容

Editing like Nair suggested also returns nothing and after 15 second the program stops running edited code:像 Nair 建议的编辑也不会返回任何内容,并且在 15 秒后程序停止运行已编辑的代码:

##imports
import time
import keyboard #pip install keyboard - could use pynput listener instead.
from threading import Thread

##variable assigning
hshtag = int(0)
done = False
fire = False


def StopStart():
    while not done:
        fire = True
        return fire

def NormalFire():
    while not done:
        if fire:
            print('ok')                   
        else:
            pass

t1 = Thread(target = StopStart)
t2 = Thread(target = NormalFire)
t1.start()
t2.start()

I'm unable to comment so I apologize in advanced.我无法发表评论,所以我提前道歉。 I'm having trouble understanding your question above, but I reworked your code - fix/add whatever you need and get back to me!我无法理解您上面的问题,但我重新编写了您的代码 - 修复/添加您需要的任何内容并回复我!

import time
import keyboard #pip install keyboard - could use pynput listener instead.
from threading import Thread

hshtag = int(0)
done = False
fire = False


def StopStart():
    while not done:
        # global fire - You're setting StopStart up for a param that needs passed, that also is named another variable
        # So it will just over write it (Also, no arg is passed for StopStart(fire))
        if keyboard.is_pressed('#'):
            hshtag = hshtag + 1
            if hshtag % 2 == 0 : fire = False
            else : fire = true
        return fire


def NormalFire():
    while not done:
        #global fire   - Don't need to global it, you would've had to global done if that was the case
        if fire: # don't need == true, just need if fire (if true)
            print("x")       

t1 = Thread(target=StopStart)
t2 = Thread(target=NormalFire)
t1.start()
t2.start()

Not sure that this is exactly what you're asking for.不确定这正是您所要求的。 I would maybe listen for keyboard events outside of either thread.我可能会在任一线程之外监听键盘事件。 Instead, just bind keyboard events to a callback which set a threading.Event object.相反,只需将键盘事件绑定到设置threading.Event object 的回调。 Sorry for the weird and slightly morbid example:抱歉,这个奇怪且有点病态的例子:

from pynput import keyboard
from threading import Thread, Event

plate_dropped = Event()

def on_press(key):
    if key is keyboard.Key.enter:
        plate_dropped.set()

listener = keyboard.Listener(on_press=on_press)

def poll_plate_status():
    from time import sleep
    from random import choice
    messages = [
        "It sure is tempting, eh?",
        "Are you gonna do it?"
    ]
    print("It'd be a shame if someone would drop this plate and scare grandpa!")
    while not plate_dropped.is_set():
        print(choice(messages))  
        sleep(0.5)
    print("The plate has been dropped!")

def poll_grandpa_status():
    from time import sleep
    from random import choice
    messages = [
        "*zzzZZZzzz*",
        "*Snoooreee*"
    ]
    print("Grandpa is sound asleep.")
    while not plate_dropped.is_set():
        print(choice(messages))
        sleep(0.5)
    print("HUH!?")


plate_thread = Thread(target=poll_plate_status, daemon=True)
grandpa_thread = Thread(target=poll_grandpa_status, daemon=True)

plate_thread.start()

grandpa_thread.start()

listener.start()
##imports
import time
import keyboard #pip install keyboard - could use pynput listener instead.
from threading import Thread

##variable assigning
hshtag = int(0)
done = False
fire = False


def StopStart(self, interval=1):
    hshtag = 0
    self.interval = interval
    while not done:
        if keyboard.is_pressed('#'):
            hshtag = hshtag + 1
            if hshtag % 2 ==0:
                fire = False
            else:
                fire = True

def NormalFire():
    while not done:
        print('NormalFire Runs')
        time.sleep(1)
        if fire:
            print('*fires*')                   
        else:
            print('*does nothing*')

#t1 = Thread(target = StopStart, daemon=True)
t2 = Thread(target = NormalFire, daemon=True)
#t1.start()
t2.start()
while not done:
    #time.sleep()
    if keyboard.is_pressed('#'):
        hshtag = hshtag + 1
        time.sleep(0.1)
        if hshtag % 2 ==0:
            fire = False
            print(fire)
        else:
            fire = True
            print(fire)

I realised my problem was my ides of threading (im new to it) this achieves what I wanted thanks for all the help.我意识到我的问题是我的线程想法(我是新手)这实现了我想要的感谢所有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python中一一执行两个函数并获得所需的输出 - How to execute two functions one by one in python and get the desired output 通过两个函数运行循环,将彼此输出作为输入 - running loop through two functions taking each others output as input 如何将一个列表的元素与其他两个列表的元素进行比较,并为 python 中的每个元素生成 output? - How to compare the elements of one list with those of two others and generate an output for every element in python? Python 脚本中的架构最佳实践 - 一个 function 调用所有其他脚本,还是一棵“树”,其中一个 function 调用调用其他函数的函数? - Architecture best practice in Python script - one function calling all the others, or a "tree" where one function calls functions that call others? 如何求解函数的一个变量,首先给出其他变量(Fsolve) - How to solve to one variable of the functions, giving the others first (Fsolve) 如何在 matplotlib 中绘制 3D 绘图,其中仅使用一个变量评估两个函数? - How to do a 3D plot in matplotlib where two functions are evaluated with only one variable? 一个线程不会影响另一个线程? - One thread does not effect another other thread? 如何模拟单元测试的功能之一的输出? - How to mock the output of one of my functions for unittests? 一次调用两个定义的函数时输出矛盾 - contradictory output while calling two defined functions at one time 在一个脚本中有两个if语句和动作? - Two if statements and actions in one script?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM