我想知道如何在Python中每10毫秒执行一个函数。我尝试使用线程(使用threading.Timer(0.001, fun)),但threading.Timer只能正确执行最多几秒钟。是否有在毫秒(毫秒)内执行任务/函数的方法?
代码如下。
def task():
print "called every 10ms"
print time.ctime()
threading.Timer(0.01,task).start()
task()
Run Code Online (Sandbox Code Playgroud) 我正在Python中使用线程类...变量设备是一个对象列表。我是否能够以某种方式将变量的“字符串”转换为线程类可以理解的方法?
def thread():
var_string = 'some_func'
index = 0
some_thread = threading.Thread(target=device[index].<var_string> , args=())
Run Code Online (Sandbox Code Playgroud)
所以本质上,我想打电话device[index].somefunc()
任何帮助将不胜感激!
我对开发网络应用程序还比较陌生。
我希望收到您对以下架构考虑因素的意见和改进建议。
我使用 CLIPS 开发了一个专家系统 ES。现在我计划将其作为 Web 应用程序提供给我们公司的各种用户。在开始讨论更多细节之前,我目前正在考虑应该涉及哪些技术。
目标是网络应用程序的用户面对一个类似聊天的动画,引导他或她向 ES 提供越来越多的输入,从而获得最终结果。
经过我自己的一些研究后,我提出了以下想法
在后端我使用 PyCLIPS 作为 Python 和 CLIPS 之间的接口
然后我使用 DJANGO 将我的 python 代码集成到网页中,动态改变用户和 ES 之间的聊天。
有一件事情至今仍然困扰着我:如何管理众多并发用户?我应该使用一个 ES,每个用户都有一组单独的事实,还是每个用户都应该有他或她自己的 ES 实例?
对于这个问题,您还有其他比这个更好的高级方法吗?
我期待您就此事提供经验和意见。
最好的
考虑这个threading.Thread类:
class Sleeper(threading.Thread):
def __init__(self, sleep=5.0):
threading.Thread.__init__(self)
self.event = threading.Event()
self.sleep = sleep
def run(self):
while self.sleep > 0 and not self.event.is_set():
self.event.wait(1.0)
self.sleep -= 1
def stop(self):
self.event.set()
Run Code Online (Sandbox Code Playgroud)
它会休眠一定的时间,并在达到该时间之前退出或停止。
我用它作为:
sleeper = Sleeper()
try:
sleeper.start()
# do stuffs here
except:
# handle possible exceptions here
finally:
sleeper.stop()
Run Code Online (Sandbox Code Playgroud)
我更愿意像上下文管理器一样使用它:
with Sleeper():
# do stuffs here
Run Code Online (Sandbox Code Playgroud)
然后线程在退出with块时停止。
我尝试过添加__enter__和__exit__方法,它似乎有效,但我不确定这是正确的方法:
def __enter__(self):
self.start()
return self
Run Code Online (Sandbox Code Playgroud)
和
def __exit__(self, type, value, traceback):
self.stop()
Run Code Online (Sandbox Code Playgroud)
但我真的不确定我在这里做什么。应该如何正确进行呢?
join()如果我调用一个已经完成的线程会发生什么?
例如
import threading
import time
def fn():
time.sleep(1)
t = threading.Thread(target=fn)
t.start()
time.sleep(2)
t.join()
Run Code Online (Sandbox Code Playgroud)
该文档似乎没有对这个问题提供任何说明
我编写的代码似乎可以实现我想要的功能,但我不确定这是否是一个好主意,因为它混合了线程和事件循环以在主线程外运行无限循环。这是一个最小的代码片段,它体现了我正在做的事情的想法:
import asyncio
import threading
msg = ""
async def infinite_loop():
global msg
while True:
msg += "x"
await asyncio.sleep(0.3)
def worker():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
asyncio.get_event_loop().run_until_complete(infinite_loop())
t = threading.Thread(target=worker, daemon=True)
t.start()
Run Code Online (Sandbox Code Playgroud)
主要思想是我有一个无限循环,每 0.3 秒操作一个全局变量。我希望这个无限循环在主线程之外运行,这样我仍然可以访问主线程中的共享变量。这在 jupyter 中特别有用,因为如果我run_until_complete在主线程中调用,我就无法再与 jupyter 交互。我希望主线程可用于交互式访问和修改msg. 在我的示例中,使用异步似乎没有必要,但我正在使用一个具有异步代码的库来运行服务器,因此这是必要的。我对 python 中的异步和线程很陌生,但我记得在某处读过/听到过,使用异步线程会带来麻烦......这是一个坏主意吗?我的方法是否存在潜在的并发问题?
我一直在寻找以下多处理问题的解决方案。
我在 record.py 模块中有一个 Record 类。记录类的职责是处理输入数据并将其保存到 JSON 文件中。Record 类有 put() 方法来更新 JSON 文件。
记录类在类装饰器中初始化。装饰器应用于各个子模块的大多数类。Decorator 提取它所装饰的每个方法的信息,并将数据发送到 Record 类的 put() 方法。Record 类的 put() 方法然后更新 JSON 文件。
问题是当不同的进程运行时,每个进程都会创建自己的记录对象实例,并且由于多个进程尝试更新相同的 json 文件,Json 数据会被损坏。此外,每个进程可能都有运行的线程尝试访问和更新相同的 JSON 文件。请让我知道如何解决这个问题。
class Record():
def put(data):
# read json file
# update json file with new data
# close json file
def decorate_method(theMethod):
# Extract method details
data = extract_method_details(theMethod)
# Initialize record object
rec = Record()
rec.put(data)
class ClassDeco(cls):
# This class decorator decorates all methods of the target class
for …Run Code Online (Sandbox Code Playgroud) 我正在学习多处理和多线程。
据我了解,线程在同一个核心上运行,所以我想知道如果我在子线程中创建多个进程,它们也会被限制在该单个核心上吗?
我正在使用 python,所以这是一个关于该特定语言的问题,但我想知道它与其他语言是否相同?
python multithreading multiprocessing python-multithreading python-multiprocessing
按下按钮后我的界面冻结了。我正在使用线程,但我不确定为什么仍然挂起。任何帮助将不胜感激。提前致谢
class magic:
def __init__(self):
self.mainQueue=queue.Queue()
def addItem(self,q):
self.mainQueue.put(q)
def startConverting(self,funcName):
if(funcName=="test"):
while not self.mainQueue.empty():
t = Thread(target = self.threaded_function)
t.start()
t.join()
def threaded_function(self):
time.sleep(5)
print(self.mainQueue.get())
m=magic()
def helloCallBack():
m.addItem("asd")
m.startConverting("test") //this line of code is freezing
B = tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
top.mainloop()
Run Code Online (Sandbox Code Playgroud) python multithreading tkinter python-multithreading python-3.x
我的目标是实现一个 Python 3 方法,该方法将支持运行系统命令(使用子进程),并满足以下几个要求:
为了支持实时日志记录,我使用了 2 个线程来处理 stdout 和 stderr 输出。
我的挑战是强制线程和子进程进程超时。
我尝试使用信号处理程序实现超时,似乎在调用处理程序后立即冻结解释器。
我的实施有什么问题吗?
还有其他方法可以实现我的要求吗?
这是我当前的实施尝试:
def run_live_output(cmd, timeout=900, **kwargs):
full_output = StringIO()
def log_popen_pipe(p, log_errors=False):
while p.poll() is None:
output = ''
if log_errors:
output = p.stderr.readline()
log.warning(f"{output}")
else:
output = p.stdout.readline()
log.info(f"{output}")
full_output.write(output)
if p.poll():
log.error(f"{cmd}\n{p.stderr.readline()}")
class MyTimeout(Exception):
pass
def handler(signum, frame):
log.info(f"Signal handler called with signal {signum}")
raise MyTimeout
with subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
universal_newlines=True,
**kwargs
) as sp:
with …Run Code Online (Sandbox Code Playgroud)