我正在尝试创建一个像object这样的文件,它在测试期间分配给sys.stdout/sys.stderr以提供确定性输出.它并不意味着快速,可靠.到目前为止我几乎可以工作,但我需要一些帮助摆脱最后几个边缘错误.
这是我目前的实施.
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from os import getpid
class MultiProcessFile(object):
"""
helper for testing multiprocessing
multiprocessing poses a problem for doctests, since the strategy
of replacing sys.stdout/stderr with file-like objects then
inspecting the results won't work: the child processes will
write to the objects, but the data will not be reflected
in the parent doctest-ing process.
The solution is to create file-like objects which will interact with
multiprocessing in …Run Code Online (Sandbox Code Playgroud) python multithreading python-2.6 multiprocessing python-multithreading
我正在使用python 2.7在gae上开发应用程序,ajax调用从API请求一些数据,单个请求可能需要大约200毫秒,但是当我打开两个浏览器并在非常接近的时间发出两个请求时,他们需要的不仅仅是其中两倍,我已经尝试将所有东西都放在线程中,但它不起作用..(这种情况发生在应用程序在线时,而不仅仅是在开发服务器上)
所以我写了这个简单的测试来看看这是否是python中的一个问题(如果忙等待),这里是代码和结果:
def work():
t = datetime.now()
print threading.currentThread(), t
i = 0
while i < 100000000:
i+=1
t2 = datetime.now()
print threading.currentThread(), t2, t2-t
if __name__ == '__main__':
print "single threaded:"
t1 = threading.Thread(target=work)
t1.start()
t1.join()
print "multi threaded:"
t1 = threading.Thread(target=work)
t1.start()
t2 = threading.Thread(target=work)
t2.start()
t1.join()
t2.join()
Run Code Online (Sandbox Code Playgroud)
结果在mac os x,core i7(4核,8个线程),python2.7:
single threaded:
<Thread(Thread-1, started 4315942912)> 2011-12-06 15:38:07.763146
<Thread(Thread-1, started 4315942912)> 2011-12-06 15:38:13.091614 0:00:05.328468
multi threaded:
<Thread(Thread-2, started 4315942912)> 2011-12-06 15:38:13.091952
<Thread(Thread-3, started 4323282944)> 2011-12-06 15:38:13.102250 …Run Code Online (Sandbox Code Playgroud) python google-app-engine multithreading python-multithreading python-2.7
难道Event和Lock做这些场景是一回事吗?
class MyThread1(threading.Thread):
def __init__(event):
self.event = event
def run(self):
self.event.wait()
# do something
self.event.clear()
Run Code Online (Sandbox Code Playgroud)
另一个:
class MyThread2(threading.Thread):
def __init__(lock):
self.lock = lock
def run(self):
self.lock.acquire()
# do something
self.lock.release()
Run Code Online (Sandbox Code Playgroud) 我试图创建一个python进程,读取一些输入,处理它并打印出结果.处理由子流程(斯坦福大学的NER)完成,对于ilustration,我将使用'cat'.我不确切知道NER会给出多少输出,所以我使用一个单独的线程来收集它并打印出来.以下示例说明.
import sys
import threading
import subprocess
# start my subprocess
cat = subprocess.Popen(
['cat'],
shell=False, stdout=subprocess.PIPE, stdin=subprocess.PIPE,
stderr=None)
def subproc_cat():
""" Reads the subprocess output and prints out """
while True:
line = cat.stdout.readline()
if not line:
break
print("CAT PROC: %s" % line.decode('UTF-8'))
# a daemon that runs the above function
th = threading.Thread(target=subproc_cat)
th.setDaemon(True)
th.start()
# the main thread reads from stdin and feeds the subprocess
while True:
line = sys.stdin.readline()
print("MAIN PROC: %s" % line)
if not …Run Code Online (Sandbox Code Playgroud) 简介:我想在命令行上编写类似于bash脚本的python脚本,但是我还想在python中轻松地将它们连接在一起.我遇到麻烦的地方是制造后者的胶水.
所以,想象一下我写了两个剧本,script1.py和script2.py我能管他们在一起就像这样:
echo input_string | ./script1.py -a -b | ./script2.py -c -d
Run Code Online (Sandbox Code Playgroud)
如何从另一个python文件中获取此行为? 这是我所知道的方式,但我不喜欢:
arg_string_1 = convert_to_args(param_1, param_2)
arg_string_2 = convert_to_args(param_3, param_4)
output_string = subprocess.check_output("echo " + input_string + " | ./script1.py " + arg_string_1 + " | ./script2.py " + arg_string_2)
Run Code Online (Sandbox Code Playgroud)
如果我不想利用多线程,我可以做这样的事情(?):
input1 = StringIO(input_string)
output1 = StringIO()
script1.main(param_1, param_2, input1, output1)
input2 = StringIO(output1.get_value())
output2 = StringIO()
script2.main(param_3, param_4, input2, output2)
Run Code Online (Sandbox Code Playgroud)
这是我尝试的方法,但我坚持写胶水.我很感激学习如何完成下面的方法,或建议更好的设计/方法!
我的方法:我写了script1.py,script2.py看起来像:
#!/usr/bin/python3
... # import sys and …Run Code Online (Sandbox Code Playgroud) Keras fit_generator()有一个pickle_safe默认参数False.
如果是 pickle_safe,训练可以更快地运行,并相应地将标志设置为True?
根据Kera的文档:
pickle_safe:如果为True,则使用基于进程的线程.请注意,由于此实现依赖于多处理,因此不应将非可选参数传递给生成器,因为它们无法轻松传递给子进程.
我不明白这是什么意思.
我怎样才能确定我的论点是否pickle_safe存在?
如果它是相关的:
- 我传入一个自定义生成器
- 生成器函数接受参数:X_train,y_train,batch_size,p_keep;
它们的类型为np.array,int,float)
- 我没有使用GPU
- 而且,我使用的是Keras 1.2.1,但我相信这个参数与keras 2的行为相同
我想运行一个使用协同程序和多线程请求URL的服务.但是我无法将协同程序传递给执行程序中的工作程序.有关此问题的最小示例,请参阅下面的代码:
import time
import asyncio
import concurrent.futures
EXECUTOR = concurrent.futures.ThreadPoolExecutor(max_workers=5)
async def async_request(loop):
await asyncio.sleep(3)
def sync_request(_):
time.sleep(3)
async def main(loop):
futures = [loop.run_in_executor(EXECUTOR, async_request,loop)
for x in range(10)]
await asyncio.wait(futures)
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
Run Code Online (Sandbox Code Playgroud)
导致以下错误:
Traceback (most recent call last):
File "co_test.py", line 17, in <module>
loop.run_until_complete(main(loop))
File "/usr/lib/python3.5/asyncio/base_events.py", line 387, in run_until_complete
return future.result()
File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
raise self._exception
File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "co_test.py", line 10, in main
futures …Run Code Online (Sandbox Code Playgroud) 我知道这threading.Lock()等于threading.Semaphore(1).
是threading.Lock()等于threading.BoundedSemaphore(1)?
我刚接触过threading.BoundedSemaphore(),这些有什么区别?例如以下代码段(对于线程的应用限制):
import threading
sem = threading.Semaphore(5)
sem = threading.BoundedSemaphore(5)
Run Code Online (Sandbox Code Playgroud) 我有这个非常简单的python代码:
Test = 1;
def para():
while(True):
if Test > 10:
print("Test is bigger than ten");
time.sleep(1);
para(); # I want this to start in parallel, so that the code below keeps executing without waiting for this function to finish
while(True):
Test = random.randint(1,42);
time.sleep(1);
if Test == 42:
break;
...#stop the parallel execution of the para() here (kill it)
..some other code here
Run Code Online (Sandbox Code Playgroud)
基本上,我想要将函数para()与其他代码并行运行,以便它下面的代码不必等待para()结束.但是,我希望能够在并行运行时访问para()内部的Test变量的当前值(如上面的代码示例所示).后来,当我决定,我完成了并行运行的para()时,我想知道如何从主线程中杀死它,还要从并行运行的para()本身(自我 - 终止).
我已经阅读了一些关于线程的教程,但是几乎每个教程都以不同的方式处理它,而且我很难理解其中的一些,所以我想知道,并行运行一段代码的最简单方法是什么.
谢谢.
据我了解,GIL使得不可能拥有分别利用内核的线程。
这是一个基本问题,但是threading库的意义是什么?如果线程代码的速度与普通程序相当,这似乎没有用。
python multithreading python-multithreading python-multiprocessing
python ×8
python-3.x ×2
async-await ×1
blocking ×1
keras ×1
mutex ×1
pickle ×1
pipeline ×1
process ×1
python-2.6 ×1
python-2.7 ×1
semaphore ×1
stanford-nlp ×1
subprocess ×1