我试图改变一个函数内的变量,并访问另一个函数内的变量,但第一个函数不会改变全局变量。
我想让我的代码做什么:当我按下startkey时它应该会打开,并开始按下"每0.5秒一次
它的作用:我在
下面用注释解释了它。我代码:
from multiprocessing.dummy import freeze_support
import time
switch = None
kofteEkmek = "guzel"
needToCheck = False
start = time.perf_counter()
import concurrent.futures
import keyboard
from pynput.keyboard import Key, Controller
with open("config.txt", "r") as con:
conContent = con.read()
startKey = str(conContent[11])
print(startKey)
def writeCon():
with open("config.txt", "w") as con:
con.write("startKey = " + startKey)
if startKey == ",":
startKey = input("Lutfen Programi Calistirmak İcin Kullanacaginiz Tusu Girinizn")
writeCon()
def check():
global switch
switch = False
while True:
while needToCheck == True:
if keyboard.is_pressed(startKey):
if switch == False:
switch = True #doesn't change the switch variable globally
print(switch)
time.sleep(0.5)
continue
if switch == True:
switch = False
print(switch)
time.sleep(0.7)
#switch only changes inside the functions even though there is a global statement
print("switch= ", switch) #"switch= None"
def move():
global switch
print("switch inside of move: ", switch) #equals "None" always
while True:
while switch == True: #switch == None so it doesn't work :C
for _ in range(10):
print("pressinA")
keyboard.press("a")
time.sleep(0.5)
needToCheck = True
if __name__ == "__main__":
freeze_support()
with concurrent.futures.ProcessPoolExecutor() as executor:
fMove = executor.submit(move)
fCheck = executor.submit(check)
finish = time.perf_counter()
print(round(finish-start, 2))
您可以尝试在代码中打印'switch's的id,您可以发现它们是不同的。(换句话说,它们不共享内存)全局变量在多进程中不能正常工作。
这些链接提供了很多你需要的信息。
如何更新全局变量在python中多处理
Python:如何使用pprocess 修改函数中的全局变量多进程全局变量更新未返回到父进程
您可以使用以下代码替换代码的相应部分。应该可以。
def check():
print(switch.value)
print(id(switch))
while True:
while needToCheck == True:
# global switch
if keyboard.is_pressed(startKey):
if switch.value == 0:
switch.value = 1
time.sleep(0.5)
continue
if switch.value == 1:
switch.value = 0
time.sleep(0.7)
def move():
# global switch
print("switch inside of move: ", switch.value) #equals "None" always
while True:
while switch.value == 1: #switch == None so it doesn't work :C
for _ in range(10):
# print("pressinA")
keyboard.press("a")
time.sleep(0.5)
time.sleep(0.1)
# print(id(switch))
needToCheck = True
def running_shared():
# consider lock if you need
return switch.value
def set_global(args):
global switch
switch = args
if __name__ == "__main__":
freeze_support()
switch = Value('b', 0)
print(id(switch))
with concurrent.futures.ProcessPoolExecutor(initializer=set_global, initargs=(switch,)) as executor:
fMove = executor.submit(move)
fCheck = executor.submit(check)
futures = [fMove , fCheck]
results = [x.result() for x in futures]
我认为您在def check()
中创建的本地变量开关会干预顶部初始化为none的全局变量开关。试着移除check
中的一个。