我试图理解Python中的线程.我看过文档和示例,但坦率地说,很多例子都过于复杂,我很难理解它们.
你如何清楚地展示为多线程划分的任务?
我需要一些方法来在pool.map()中使用一个接受多个参数的函数.根据我的理解,pool.map()的目标函数只能有一个iterable作为参数,但有没有办法可以传递其他参数?在这种情况下,我需要传递一些配置变量,比如我的Lock()和记录信息到目标函数.
我试图做一些研究,我认为我可以使用部分功能来使其工作?但是我不完全理解这些是如何工作的.任何帮助将不胜感激!这是我想要做的一个简单示例:
def target(items, lock):
for item in items:
# Do cool stuff
if (... some condition here ...):
lock.acquire()
# Write to stdout or logfile, etc.
lock.release()
def main():
iterable = [1, 2, 3, 4, 5]
pool = multiprocessing.Pool()
pool.map(target(PASS PARAMS HERE), iterable)
pool.close()
pool.join()
Run Code Online (Sandbox Code Playgroud) 使用map和有map_async什么区别?将项目从列表分发到4个进程后,它们是否没有运行相同的功能?
那么假设两者都在运行异步和并行是错误的吗?
def f(x):
return 2*x
p=Pool(4)
l=[1,2,3,4]
out1=p.map(f,l)
#vs
out2=p.map_async(f,l)
Run Code Online (Sandbox Code Playgroud) 我试图在我的代码中实现多处理,所以,我想我会开始学习一些例子.我使用了本文档中的第一个示例.
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
with Pool(5) as p:
print(p.map(f, [1, 2, 3]))
Run Code Online (Sandbox Code Playgroud)
当我运行上面的代码时,我得到了一个AttributeError: can't get attribute 'f' on <module '__main__' (built-in)>.我不知道为什么我会收到这个错误.如果有帮助,我也使用Python 3.5.
我试图将列表作为参数传递给pool.map(co_refresh, input_list).但是,pool.map没有触发功能co_refresh.并且没有错误返回.看起来这个过程就在那里.
原始代码:
from multiprocessing import Pool
import pandas as pd
import os
account='xxx'
password='xxx'
threads=5
co_links='file.csv'
input_list=[]
pool = Pool(processes=threads)
def co_refresh(url, account, password, outputfile):
print(url + ' : ' + account + ' : ' + password + ' : ' + outputfile)
return;
link_pool = pd.read_csv(co_links, skipinitialspace = True)
for i, row in link_pool.iterrows():
ln = (row.URL, account, password, os.path.join('e:/', row.File_Name.split('.')[0] + '.csv'))
input_list.append(ln)
pool.map(co_refresh, input_list)
pool.close()
Run Code Online (Sandbox Code Playgroud)
但是,它从未触发过该功能co_refresh.如何将列表作为参数传递给我的函数?
旧问题(简体): …
我对 Python 有点陌生,所以如果这是一个愚蠢的问题,我想道歉。
我目前正在开发一项执行多项数据检查的开发。
简而言之,我有一个主数据框,需要根据其他数据框的数据进行验证。
我所做的代码在单核上正常工作,但由于体积的原因,我需要实现多核处理。问题是我找不到如何将多个 pandas 数据帧作为参数传递给函数模块。
请注意,主数据集purchase_orders已经在进程之间进行了分割,因此每个进程将收到1/4的数据。其他数据帧应该更小并且完全相同,因此如果有一种方法可以使生成的进程访问在主进程上创建的数据帧也很好,因为我只会从中读取数据。
数据帧change_log和参数将在apply方法中使用。
代码如下:
# this is the code I would like to call for multi processing
def apply_scores_test(purchase_orders, change_log, parameters):
print('Running multicore')
size = 1
g_first = 'X'
g_results = 'START'
g_temp_lifnr = 'X'
purchase_orders = purchase_orders.apply(calculate_scores, axis=1)
return purchase_orders
# Starting the multi-core processing (locked to 4 process to make it easier to test)
p = multiprocessing.Pool(4)
args = [(g_purchase_orders_1, change_log, parameters), (g_purchase_orders_2, change_log, parameters), (g_purchase_orders_3, change_log, parameters),(g_purchase_orders_4, change_log, parameters),]
res …Run Code Online (Sandbox Code Playgroud) 我有一个 for 循环,它会从一组 URL 中获取一个 URL 并访问该 URL 并执行其他一些操作,但它花费了很长时间,所以我想我可以通过一些多重处理来加速它,但我很挣扎这样做。
感谢您的帮助。
def accessAndSaveFiles(urlSet, user, verboseFlag):
with multiprocessing.Pool(os.cpu_count()) as pool:
pool.starmap(processURL, zip(itertools.repeat(urlSet), user, verboseFlag))
def processURL(url, user, verboseFlag):
filePath = some_path
img_data = requests.get(url, allow_redirects=True)
open(filePath, 'wb').write(img_data.content)
def main():
...
accessAndSaveFiles(urlSet, user, verboseFlag)
...
Run Code Online (Sandbox Code Playgroud)
我在“pool.starmap(processURL, zip(itertools.repeat(urlSet), user, verboseFlag))”行上收到错误,提示“TypeError: zip argument #3 must support iteration”。我不想迭代这个项目,我只想每次发送相同的值。
我正在尝试将代码中的线程切换到多处理以衡量其性能,并希望实现更好的暴力破解潜力,因为我的程序旨在暴力破解受密码保护的 .zip 文件。但是每当我尝试运行该程序时,我都会得到以下信息:
BruteZIP2.py -z "Generic ZIP.zip" -f Worm.txt
Traceback (most recent call last):
File "C:\Users\User\Documents\Jetbrains\PyCharm\BruteZIP\BruteZIP2.py", line 40, in <module>
main(args.zip, args.file)
File "C:\Users\User\Documents\Jetbrains\PyCharm\BruteZIP\BruteZIP2.py", line 34, in main
p.start()
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 112, in start
self._popen = self._Popen(self)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 223, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 322, in _Popen
return Popen(process_obj)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__
reduction.dump(process_obj, to_child)
File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\multiprocessing\reduction.py", line 60, in dump
ForkingPickler(file, protocol).dump(obj)
TypeError: cannot serialize '_io.BufferedReader' object
Run Code Online (Sandbox Code Playgroud)
我确实找到了与我有相同问题的线程,但它们都没有得到答复/未解决。我也尝试Pool在上面插入,p.start()因为我相信这是由于我在基于 …
我已经在 Windows 上成功实现了一个多处理脚本,但同一个脚本在 linux 上启动了一个“运行时错误:已经启动”并停止执行。该脚本由以下“main.py”组成(为了可读性省略了一些部分):
from multiprocessing import freeze_support
if __name__ == '__main__':
#MULTIPROCESSING STUFF
freeze_support()
#DO SOME STUFF
#Call my multiprocessing-function in other module
mod2.func(tileTS[0], label, areaconst)
Run Code Online (Sandbox Code Playgroud)
和“mod2.py”模块:
import numpy as np
from multiprocessing import Pool
from functools import partial
import os, time
def func(ts, label, areaconst):
#SETTING UP/LOADING SOME VARIABLES
for idx in totImgs:
img_ = myList[idx]
p = Pool(2)
result = p.map( partial(_mp_avg, var1=var1_, img=img_), range(totObjs) )
p.close()
p.join()
#MANAGE RESULTING VARIABLES
return None
def _mp_avg(idx, img, …Run Code Online (Sandbox Code Playgroud) 因此,我查看了多处理模块的文档,也查看了此处提出的其他问题,但似乎没有一个与我的情况相似,因此我开始了一个新问题。
为了简单起见,我有一段如下形式的代码:
# simple dataframe of some users and their properties.
data = {'userId': [1, 2, 3, 4],
'property': [12, 11, 13, 43]}
df = pd.DataFrame.from_dict(data)
# a function that generates permutations of the above users, in the form of a list of lists
# such as [[1,2,3,4], [2,1,3,4], [2,3,4,1], [2,4,1,3]]
user_perm = generate_permutations(nr_perm=4)
# a function that computes some relation between users
def comp_rel(df, permutation, user_dict):
df1 = df.userId.isin(permutation[0])
df2 = df.userId.isin(permutation[1])
user_dict[permutation[0]] += permutation[1]
return user_dict
# and …Run Code Online (Sandbox Code Playgroud) python ×8
python-3.x ×3
pool ×2
concurrency ×1
dataframe ×1
dictionary ×1
linux ×1
map-function ×1
pandas ×1
python-2.7 ×1
python-pool ×1
windows ×1