我想使用 py.test 测试函数的线程安全性我的努力:
def function_to_be_tested(arg1,arg2):
some functionality
class Test:
def setup()
def teardown()
def test_conc()
p1=Process(taget=function_to_be_tested,args(arg1,arg2,))
p2=Process (taget=function_to_be_tested,args(arg1,arg3,))
p1.start()
p2.start()
p1.join()
p2.join()
Run Code Online (Sandbox Code Playgroud)
使用 py.test 命令执行上面的文件。这显示以下错误。
ExceptionPexpect: isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?
Run Code Online (Sandbox Code Playgroud)
你能帮我解码这个错误,并就如何做到这一点提供指导吗?
谢谢这是我正在尝试的实际代码和堆栈跟踪:
import pytest
from multiprocessing import Process
from pexpect import pxssh
def func(cls,b):
cls.s.sendline("bteq")
cls.s.prompt()
print b
#some operations inside the bteq session
class Test:
@classmethod
def setup_class(cls):
cls.s=pxssh.pxssh()
cls.s.login("IP",'Username','Pwd')
@classmethod
def …Run Code Online (Sandbox Code Playgroud) python concurrency pytest python-multithreading python-multiprocessing
基于这个优秀的 SO 答案,我可以在 RxPy 中并行处理多个任务,我的问题是你如何等待它们全部完成?我知道我可以使用线程,.join()但是 Rx 调度器似乎没有任何这样的选项。.to_blocking()也无济于事, MainThread 在触发所有通知并调用完整处理程序之前完成。下面是一个例子:
from __future__ import print_function
import os, sys
import time
import random
from rx import Observable
from rx.core import Scheduler
from threading import current_thread
def printthread(val):
print("{}, thread: {}".format(val, current_thread().name))
def intense_calculation(value):
printthread("calc {}".format(value))
time.sleep(random.randint(5, 20) * .1)
return value
if __name__ == "__main__":
Observable.range(1, 3) \
.select_many(lambda i: Observable.start(lambda: intense_calculation(i), scheduler=Scheduler.timeout)) \
.observe_on(Scheduler.event_loop) \
.subscribe(
on_next=lambda x: printthread("on_next: {}".format(x)),
on_completed=lambda: printthread("on_completed"),
on_error=lambda err: printthread("on_error: {}".format(err))) …Run Code Online (Sandbox Code Playgroud) 我正在玩 Python 的新(ish)asyncio东西,试图将其事件循环与传统线程结合起来。我编写了一个在自己的线程中运行事件循环的类,以隔离它,然后提供一个(同步)方法,该方法在该循环上运行协程并返回结果。(我意识到这使它成为一个有点毫无意义的例子,因为它必须序列化所有内容,但这只是一个概念验证)。
import asyncio
import aiohttp
from threading import Thread
class Fetcher(object):
def __init__(self):
self._loop = asyncio.new_event_loop()
# FIXME Do I need this? It works either way...
#asyncio.set_event_loop(self._loop)
self._session = aiohttp.ClientSession(loop=self._loop)
self._thread = Thread(target=self._loop.run_forever)
self._thread.start()
def __enter__(self):
return self
def __exit__(self, *e):
self._session.close()
self._loop.call_soon_threadsafe(self._loop.stop)
self._thread.join()
self._loop.close()
def __call__(self, url:str) -> str:
# FIXME Can I not get a future from some method of the loop?
future = asyncio.run_coroutine_threadsafe(self._get_response(url), self._loop)
return future.result()
async def _get_response(self, url:str) -> str: …Run Code Online (Sandbox Code Playgroud) 问题与标题一样,如何通过示例模拟 select.select 以测试我的线程运行功能。测试功能失败
ready = select.select([self.sock], [], [], 5)
TypeError: fileno() returned a non-integer
Run Code Online (Sandbox Code Playgroud)
和类型打印给出
输入'builtin_function_or_method'
所以很明显 select.select 在线程的范围内没有被模拟,而在测试中它是......(assert isinstance)
import select
import threading
RECEIVE_BYTES = 256
class Bar(threading.Thread):
def __init__(self, sock):
threading.Thread.__init__(self)
self.sock = sock
def run(self):
print type(select.select)
ready = select.select([self.sock],[],[],5)
if ready[0]:
print self.sock.recv(RECEIVE_BYTES)
Run Code Online (Sandbox Code Playgroud)
在另一个模块中测试如下
def test_run(self):
with patch("select.select"):
select.select.return_value = [True]
mock_sock = MagicMock()
foo = Bar(mock_sock)
assert isinstance(select.select, MagicMock)
foo.start()
Run Code Online (Sandbox Code Playgroud)
测试通过鼻子运行
python unit-testing mocking python-multithreading python-2.7
在看了比斯利书中的例子后,我正在和我的朋友交谈
class ActorExit(Exception):
pass
class Actor:
def __init__(self):
self._mailbox = Queue()
def send(self, msg):
self._mailbox.put(msg)
def recv(self):
msg = self._mailbox.get()
if msg is ActorExit:
raise ActorExit()
return msg
def close(self):
self.send(ActorExit)
def start(self):
self._terminated = Event()
t = Thread(target=self._bootstrap)
t.daemon = True
t.start()
def _bootstrap(self):
try:
self.run()
except ActorExit:
pass
finally:
self._terminated.set()
def join(self):
self._terminated.wait()
def run(self):
while True:
msg = self.recv()
class PrintActor(Actor):
def run(self):
while True:
msg = self.recv()
print('Got:', msg)
Run Code Online (Sandbox Code Playgroud)
我的朋友认为 Event 的唯一目的是阻塞主线程,直到另一个线程执行设置操作。真的吗?我们如何观察线程执行?
python queue concurrency multithreading python-multithreading
下面的脚本是抽象的。我的问题是关于使用threading.Lock()
锁定限制了对“共享资源”的访问,但我对这能走多远感到紧张。我有对象属性,它们是在这个例子中具有数组属性的对象列表。在某些情况下,依赖会走得更远。
是否Lock()“知道”需要锁定的所有内容?
还显示了下面脚本的输出。脚本的目的主要是为了讨论 - 它不会失败,但我不相信它会锁定它需要的一切。
start: [array([0, 1]), array([0, 1, 2]), array([0, 1, 2, 3])]
append an object
done!
finish: [array([505, 605]), array([10, 11, 12]), array([10, 11, 12, 13]), array([5])]
import time
from threading import Thread, Lock
import numpy as np
class Bucket(object):
def __init__(self, objects):
self.objects = objects
class Object(object):
def __init__(self, array):
self.array = array
class A(Thread):
def __init__(self, bucket):
Thread.__init__(self)
self.bucket = bucket
def run(self):
nloop = 0
locker …Run Code Online (Sandbox Code Playgroud) 我创建了一个简单的脚本,它遍历我需要 ping 和 nslookup 的服务器列表。问题是,ping 可能需要一些时间,尤其是 ping 比一天中的秒数更多的服务器。
我对编程相当陌生,我知道多处理或多线程可能是使我的工作运行得更快的解决方案。
我的计划是获取我的服务器列表和 1. 将它分成大小均匀的列表,列表的数量与线程/进程匹配,或者 2. 如果这些选项之一支持它,则遍历单个列表,每个列表都传递一个新的在完成之前的 ping 和 nslookup 后,线程或进程的服务器名称。这是可取的,因为它确保我花费最少的时间,就好像列表 1 有 200 个离线服务器而列表 6 有 2000 个,它需要等待使用列表 6 的过程完成,即使所有其他人在那个时候都是免费的观点。
哪一个更适合这项任务,为什么?
如果可能,我将如何确保每个线程或进程具有基本相同的运行时
代码片段即使现在相当简单
import subprocess
import time
server_file = open(r"myfilepath", "r")
initial_time = time.time()
for i in range(1000):
print(server_file.readline()[0:-1]+ ' '+str(subprocess.run('ping '+server_file.readline()[0:-1]).returncode)) #This returns a string with the server name, and return code,
print(time.time()-initial_time)
Run Code Online (Sandbox Code Playgroud)
出现此问题是因为每次失败的 ping 平均需要 3 秒以上。此外,我知道不放置打印语句会使它更快,但我想监视它的一个小案例。我正在对 100,000 台服务器的影响进行 ping 操作,这将需要定期执行,并且该列表将继续增长
python multithreading ping python-multithreading python-multiprocessing
我想在线程中调用一个函数。使用传统 API 调用它看起来像:
from threading import Thread
import numpy as np
a = np.random.rand(int(1e8),1)
Thread(target=np.savez_compressed, args=('/tmp/values.a', dict(a=a))).start()
Run Code Online (Sandbox Code Playgroud)
我想知道是否有一个 pythonic 是使用更干净的 API 进行这个线程调用,而不定义一个特定于np.savez_compressed.
例如(伪代码)风格的东西:
@make_threaded
np.savez_compressed('/tmp/values.a', dict(a=a))
Run Code Online (Sandbox Code Playgroud)
不幸的是,装饰器只能应用于函数定义,所以上面的伪代码是不合法的。
编辑:我不是专门寻找装饰器 API。相反,一种使函数调用线程化的更简洁的方法
我的请求是从调试器和 pycharm 提示符中获取调试数据:
假设我有一个带有错误的旧式 python 同步程序:
def listdir(self, remote_path):
with ssh.connect(self.connection_settings['host'], username=self.connection_settings['username'],
password=self.connection_settings['password']) as conn:
with conn.start_sftp_client() as sftp:
sftp.chdir(remote_path) # breakpoint here
files = sftp.readdir()
files_name = [file.filename for file in files]
return files_name
Run Code Online (Sandbox Code Playgroud)
我会停止它,转到调试器,单击调试器控制台-> 显示 python 提示,然后在运行时调试我的问题:
> sftp.getcwd()
bad_user_location
> sftp.chdir(good_base_location)
> sftp.readdir()
Run Code Online (Sandbox Code Playgroud)
只需即时重写代码并测试状态和运行时即可。(这一直是我调试的方式,使用immediate windowMicrosoft 语言开发中的,以及 Python 和其他脚本语言中的 REPL。
现在我有一个异步程序:
async def listdir(self, remote_path):
async with asyncssh.connect(self.connection_settings['host'], username=self.connection_settings['username'],
password=self.connection_settings['password']) as conn:
async with conn.start_sftp_client() as sftp:
await sftp.chdir(remote_path) # breakpoint here
files = await sftp.readdir() …Run Code Online (Sandbox Code Playgroud) python debugging asynchronous python-multithreading python-asyncio
我在网上经历了多种解决方案,但它们需要大量代码,一旦您扩展,这些代码可能会令人困惑。是否有一种简单的方法可以停止线程并避免RuntimeError: threads can only be started once, 以便无限次调用线程。这是我的代码的简单版本:
import tkinter
import time
import threading
def func():
entry.config(state='disabled')
label.configure(text="Standby for seconds")
time.sleep(3)
sum = 0
for i in range(int(entry.get())):
time.sleep(0.5)
sum = sum+i
label.configure(text=str(sum))
entry.config(state='normal')
mainwindow = tkinter.Tk()
mainwindow.title('Sum up to any number')
entry = tkinter.Entry(mainwindow)
entry.pack()
label = tkinter.Label(mainwindow, text = "Enter an integer",font=("Arial",33))
label.pack()
print(entry.get())
button = tkinter.Button(mainwindow, text="Press me", command=threading.Thread(target=func).start)
button.pack()
Run Code Online (Sandbox Code Playgroud) python multithreading tkinter software-design python-multithreading
python ×10
concurrency ×2
python-2.7 ×2
asynchronous ×1
debugging ×1
mocking ×1
ping ×1
pytest ×1
python-3.x ×1
queue ×1
reactivex ×1
rx-py ×1
tkinter ×1
unit-testing ×1