编辑
我尝试使用管理器在进程之间共享我的信件.但我现在唯一拥有的是在Python Shell中打印的Value(‘ctypes.c_char_p’,'(你在这里点击的键)’),但仍然没有声音.
使用管理器时,控制台似乎比平常慢一点.在我按下键和屏幕上显示值之间有几乎一秒的延迟.
我的代码现在看起来像这样:
#Import from tkinter import * import wave import winsound import multiprocessing #Functions def key(event): temp = event.char manager = multiprocessing.Manager() manager.Value(ctypes.c_char_p,temp) hitkey = manager.Value(ctypes.c_char_p,temp) instance = multiprocessing.Process(target=player,args=(hitkey,)) instance.start() def player(hitkey): print(hitkey + "1") winsound.PlaySound(hitkey + '.wav',winsound.SND_FILENAME|winsound.SND_NOWAIT|winsound.SND_ASYNC) if __name__ == "__main__": #Initialisation fenetre = Tk() frame = Frame(fenetre,width=200,height=100) #TK frame.focus_set() frame.bind("<Key>",key) frame.pack() fenetre.mainloop()
解决方法
multiprocessing.Value
没有特殊的语法,它只是一个类似于任何其他的类. Value构造函数的签名描述得非常好:
multiprocessing.Value(typecode_or_type,*args[,lock])
Return a
ctypes
object allocated from shared memory. By default the return value is actually a synchronized wrapper for the object.
typecode_or_type
determines the type of the returned object: it is either actypes
type or a one character typecode of the kind used
by thearray
module.*args
is passed on to the constructor for the
type.If
lock
isTrue
(the default) then a new lock object is created to synchronize access to the value. If lock is aLock
or
RLock
object then that will be used to synchronize access to the
value. Iflock
isFalse
then access to the returned object will
not be automatically protected by a lock,so it will not necessarily
be “process-safe”.
你甚至有一些使用它的例子afterwards.具体来说,typecode_or_type可以是array
模块文档中列出的一个类型代码(例如’i’代表有符号整数,’f’代表float等)或ctypes类型,如ctypes.c_int等.
如果您想要包含单个字母的值,您可以执行以下操作:
>>> import multiprocessing as mp >>> letter = mp.Value('c','A') >>> letter <Synchronized wrapper for c_char('A')> >>> letter.value 'A'
更新
您的代码的问题是类型代码’c’表示字符不是字符串.
如果要保存字符串,可以使用ctypes.c_char_p类型:
>>> import multiprocessing as mp >>> import ctypes >>> v = mp.Value('c',"Hello,World!") Traceback (most recent call last): File "<stdin>",line 1,in <module> File "/usr/lib/python2.7/multiprocessing/__init__.py",line 253,in Value return Value(typecode_or_type,*args,**kwds) File "/usr/lib/python2.7/multiprocessing/sharedctypes.py",line 99,in Value obj = RawValue(typecode_or_type,*args) File "/usr/lib/python2.7/multiprocessing/sharedctypes.py",line 73,in RawValue obj.__init__(*args) TypeError: one character string expected >>> v = mp.Value(ctypes.c_char_p,World!") >>> v <Synchronized wrapper for c_char_p(166841564)> >>> v.value 'Hello,World!'