只需单击一个按钮即可运行该程序.我试图使该按钮在被点击时被禁用,并在5秒后激活,同时不干扰程序的其余部分.(程序的其余部分在代码中称为#这里其余的程序运行)
import time
from tkinter import Tk, Button, SUNKEN, RAISED
from threading import Thread
def tFunc(button):
thread = Thread(target= buttonDisable, args=(button))
thread.start()
# here the rest of the program runs
def buttonDisable(button):
button.config(state='disable',relief=SUNKEN)
time.sleep(5)
button.config(state='active', relief=RAISED)
root = Tk()
button = Button(root, text='Button', command= lambda : tFunc(button))
button.pack()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python33\lib\threading.py", line 637, in _bootstrap_inner
self.run()
File "C:\Python33\lib\threading.py", line 594, in run
self._target(*self._args, **self._kwargs)
TypeError: buttonDisable() argument after * must …Run Code Online (Sandbox Code Playgroud) 我试图用装饰器捕获线程错误:
class cc:
def catch_exceptions(job_func):
@functools.wraps(job_func)
def wrapper(*args, **kwargs):
try:
job_func(*args, **kwargs)
except:
import traceback
print(traceback.format_exc())
return wrapper
@catch_exceptions
def job(self, name, command):
#print("I'm running on thread %s" % threading.current_thread())
os.system(command)
def run_threaded(self, job_func, name, command):
job_thread = threading.Thread(target=job_func, args=(name, command,) )
job_thread.start()
Run Code Online (Sandbox Code Playgroud)
我遇到了这个问题:
File "/usr/local/lib/python2.7/dist-packages/schedule/__init__.py", line 320, in do
self.job_func = functools.partial(job_func, *args, **kwargs)
TypeError: the first argument must be callable
Run Code Online (Sandbox Code Playgroud)
我怎样才能使job_func可调用?
我有一个列表,大号和大字典,d包含键,ķ其中k是在一个特定密钥ķ.D [k]包含确定结果列表所需的一些信息.现在,我通过在每个值搜索ķ如果信息存在的价值给我,我追加k以大号.这是迭代的方式,但我希望我可以通过多线程加快速度.字典永远不会有更新.实现这个目标的好方法是什么?
import threading
def read_file():
f = open('text.txt')
for line in f:
print line.strip() ,' : ', threading.current_thread().getName()
if __name__ == '__main__':
threads = []
for i in range(15):
t = threading.Thread(target=read_file)
threads.append(t)
t.start()
Run Code Online (Sandbox Code Playgroud)
问题:每个线程是否只从上面的文件中读取每一行,或者某个给定的线程有可能最终读取一行两次?
我的理解是,稍后启动的线程将覆盖先前启动的线程的文件句柄,导致较早的线程最终读取几行两次或三次或更多次.
当我运行此代码时,结果与我预期的结果不同.
欢迎任何解释.
首先,我尝试了SocketServer类。然后我知道SocketServer在Python2中可用。对于Python3,您需要使其小写,例如socketserver。我正在尝试实现一个可以响应多个线程并且不阻止调用的套接字服务器。
以下是服务器的代码
class ForkingServer(socketserver.ForkingMixIn, socketserver.TCPServer):
pass
Run Code Online (Sandbox Code Playgroud)
我正在寻找这个问题的解决方案:
我有两个功能:
def foo1():
while True:
print("x")
def foo2():
while True:
print("y")
Run Code Online (Sandbox Code Playgroud)
我想交替运行它们,如:
功能不能同时工作,目前只有其中一个可以工作.
我试图绘制两个更新图,一个是图表,另一个是从相机捕获的图像。
我在这一行收到一个错误:
"current_line.set_data(y_data)" in the "update" function.
The error says: "AttributeError: 'list' object has no attribute 'set_data'".
Run Code Online (Sandbox Code Playgroud)
知道为什么我会收到此错误吗?如果我注释掉这一行,我将从相机中获取不断变化的图像,除第二个图外的所有内容看起来都很好(因为第二个图未更新)但我也需要更新第二个图。
y_data = [0]
# Capture intial frame
ret, initial_frame = lsd.cap.read()
# Function for making the initial figure
def makeFigure():
fig = plt.figure()
# Show frame
ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2)
plot_frame = ax1.imshow(initial_frame, animated=True)
# Set the limits of the plot and plot the graph
ax2 = plt.subplot2grid((2, 2), (1, 0), colspan=2)
ax2.set_title('Title')
ax2.set_ylabel('Y-Label')
ax2.set_ylim(0, 100)
ax2.set_xlim(0, 100)
ax2.grid() …Run Code Online (Sandbox Code Playgroud) 我有这个脚本,它在 tkinter 中的主类/循环之外/之前执行一个长时间运行的函数,并且我创建了一个按钮来使用 root.destroy() 完全退出程序,但它关闭了 gui 并且该函数继续运行创建可执行文件后,控制台甚至作为后台进程。
如何解决这个问题?
我的脚本片段:
from tkinter import *
import threading
def download():
#downloading a video file
def stop(): # stop button to close the gui and should terminate the download function too
root.destroy()
class
...
...
...
def downloadbutton():
threading.Thread(target=download).start()
Run Code Online (Sandbox Code Playgroud) python multithreading tkinter python-multithreading python-2.7
我一直在研究Python编程语言,由于多种因素,Python可以说是一种缓慢的语言,其中包括缺乏多线程功能,如果它不支持多线程,那么为什么它有线程模块呢?
有点令人困惑的问题。我想做的就是加快这一进程。
yt_client = SoundHandler.YouTube(search=search)
download_link_attempt = await yt_client.PlaySongByLink()
search_url = yt_client.SearchURL()
source, video_url = await yt_client.GetTopSearchResultAudioSource(search_url)
yt_info, yt_info_embed = await yt_client.GetYouTubeInformation(video_url)
Run Code Online (Sandbox Code Playgroud)
但在第四行我需要第三行的变量。第四个和第五个也一样。
我已经尝试了我想到的一切,但似乎无法弄清楚。
python multithreading ffmpeg python-multithreading python-3.x
我不明白多处理文档(python.org)的这一部分,我引述:
"将陷入僵局的一个例子如下:
from multiprocessing import Process, Queue
def f(q):
q.put('X' * 1000000)
if __name__ == '__main__':
queue = Queue()
p = Process(target=f, args=(queue,))
p.start()
p.join() # this deadlocks
obj = queue.get()
Run Code Online (Sandbox Code Playgroud)
"首先,它为什么会阻塞?更令人惊讶的是,当我在f的定义中使用一些小于1000000的值时,它可以正常工作(它适用于10,100,1000,10000,但不能使用100000).
非常感谢你的帮助 !
python multithreading multiprocessing python-multithreading python-multiprocessing
我想锁定该方法的一部分(“等待获取锁定”之后的那部分应该仅在第一个线程释放锁定之后才能运行)。发生的情况是两个线程都独立运行,而与lock.acquire()无关。
我不知道为什么这不起作用。stackoverflow中的示例与此类似,但并不完全相同。请看一下我为什么需要这样做:我没有显式的共享资源,我只想防止2个python线程运行相同的代码,因为在我正在开发的系统中,它们可能会将系统置于不稳定的状态。
import threading, time
def test(name):
lock = threading.Lock()
print(name + " - Starting thread")
print(name + " - Waiting to acquire lock")
lock.acquire(True)
try:
print(name + " - Lock acquired!")
for i in range(10):
print(name + " - " + str(i))
print("")
time.sleep(1)
finally:
lock.release()
print(name + " - Lock released")
def main():
t1 = threading.Thread(target=test, args=["#1_Thread"])
t2 = threading.Thread(target=test, args=["#2_Thread"])
t1.start()
time.sleep(3)
t2.start()
main()
Run Code Online (Sandbox Code Playgroud) python ×12
python-3.x ×5
python-2.7 ×2
tkinter ×2
decorator ×1
ffmpeg ×1
matplotlib ×1
opencv ×1
parameters ×1
sockets ×1