标签: python-multiprocessing

Python多处理。您如何从孩子那里获得父母的身份?

我正在使用多处理模块编写一个应用程序(Linux),该模块产生多个子级。当孩子去世时,我可以使用以下类似方法从父母那里检测到它:

process = multiprocessing.Process(...)
if process.is_alive():
  print "Process died"
Run Code Online (Sandbox Code Playgroud)

但是,我也希望能够从孩子那里检测出父母是否还活着,如果有人去了并杀死-9的父母进程来进行清理。

从上面的示例中,我可以使用以下任一方法获取父ID:

process._parent_pid
Run Code Online (Sandbox Code Playgroud)

要么:

os.getppid()
Run Code Online (Sandbox Code Playgroud)

但是我找不到一种简单的方法来获取流程状态。我宁愿不使用子过程向grep / regex ps列表中写一些东西。有没有更清洁的方法?

python linux pid python-multiprocessing

1
推荐指数
1
解决办法
2493
查看次数

python:使用多处理时访问变量的问题

我是 python 中多处理概念的新手,当我尝试在我的代码中包含多处理时,我在访问变量时遇到了问题。对不起,如果我听起来很天真,但我就是想不通。下面是我的场景的一个简单版本。

class Data:
    def __init__(self):
        self.data = "data"
    def datameth(self):
        print self.data
        print mainvar

class First:
    def __init__(self):
        self.first = "first"
    def firstmeth(self):
        d = Data()
        d.datameth()
        print self.first

def mymethod():
    f = First()
    f.firstmeth()

if __name__ == '__main__':
    mainvar = "mainvar"
    mymethod()
Run Code Online (Sandbox Code Playgroud)

当我运行它时,它运行良好并给出输出:

data
mainvar
first
Run Code Online (Sandbox Code Playgroud)

但是当我尝试mymethod()作为一个进程运行时

from multiprocessing import Process
class Data:
    def __init__(self):
        self.data = "data"
    def datameth(self):
        print self.data
        print mainvar

class First:
    def __init__(self):
        self.first = "first"
    def firstmeth(self):
        d = …
Run Code Online (Sandbox Code Playgroud)

python class multiprocessing python-2.7 python-multiprocessing

1
推荐指数
1
解决办法
1040
查看次数

无法 conda 安装多处理

我正在尝试在我的 conda 环境中安装多处理。从 anaconda 的网站:https ://anaconda.org/auto/multiprocessing 安装多处理我在我的 conda 环境中运行:

conda install -c auto multiprocessing=2.6.2.1
Run Code Online (Sandbox Code Playgroud)

但是,我收到此错误:

UnsatisfiableError: The following specifications were found to be in conflict:
  - multiprocessing 2.6.2.1*
  - python 3.5*
Run Code Online (Sandbox Code Playgroud)

为什么会这样?多处理不兼容python 3.5吗?如果是这样,有没有办法在与 python 3 兼容的 conda 环境中安装特定版本的多处理?

提前致谢。

python python-3.x conda python-multiprocessing

1
推荐指数
1
解决办法
7316
查看次数

Python Multiprocessing - 修改共享字典中的值

我正在处理一个项目,我将一个进程中的数据解析为一个 python 字典,然后由另一个 python 进程读取,从而创建不同的数据视图。解析的数据来自 worker1 进程处理的传感器。

到目前为止,我可以使用共享字典创建两个进程,并且我最终可以毫无问题地向其中添加值。但是,当我想修改现有值时,我碰到了砖墙。我已经阅读了几个小时的“许多”答案并尝试了解决方案,例如创建一个包含密钥的新对象。例如x = d["key"][1];x = 'newvalue'。只是不起作用。我在 python 3.6 中运行代码,但问题在 2.7 中似乎相似。这是简化版本的代码:

#!/usr/bin/python3
import subprocess,time
from multiprocessing import Process, Manager

def worker1(d):
    d["key"] = []    #Creating empty dict item
    d["key"]+=["hellostack"] #Adding first value
    d["key"]+=[1]    #Adding second value
    print ("from worker1:",d)
    d["key"][1]+=2 #<<<< ISSUE HERE - Modifying second value does nothing
    print ("Now value should be upped!..",d)

def worker2(d):
    while True:
        time.sleep(1)
        print ("from worker 2:",d)

manager = Manager()
d = manager.dict()

worker1 = …
Run Code Online (Sandbox Code Playgroud)

python dictionary python-multiprocessing

1
推荐指数
1
解决办法
4130
查看次数

如何使用 concurrent.futures.ThreadPoolExecutor 或 multiprocessing.pool.ThreadPool 将一些变量绑定到线程?

我想做的是这样的:

class MyThread(threading.Thread):
    def __init__(self, host, port):
        threading.Thread.__init__(self)
        # self._sock = self.initsocket(host, port)
        self._id = random.randint(0, 100)

    def run(self):
        for i in range(3):
            print("current id: {}".format(self._id))

def main():
    ts = []
    for i in range(5):
        t = MyThread("localhost", 3001)
        t.start()
        ts.append(t)

    for t in ts:
        t.join()
Run Code Online (Sandbox Code Playgroud)

我得到了这些输出:

current id: 10
current id: 10
current id: 13
current id: 43
current id: 13
current id: 10
current id: 83
current id: 83
current id: 83
current id: 13
current id: 98 …
Run Code Online (Sandbox Code Playgroud)

python threadpoolexecutor python-multiprocessing

1
推荐指数
1
解决办法
3228
查看次数

如何使用多处理来循环浏览一个大的 URL 列表?

问题:检查超过 1000 个 url 的列表并获取 url 返回码 (status_code)。

我的脚本有效,但速度很慢。

我认为必须有一种更好的、pythonic(更漂亮)的方式来做到这一点,在那里我可以产生 10 或 20 个线程来检查 url 并收集响应。(IE:

200 -> www.yahoo.com
404 -> www.badurl.com
...
Run Code Online (Sandbox Code Playgroud)

输入文件:Url10.txt

www.example.com
www.yahoo.com
www.testsite.com
Run Code Online (Sandbox Code Playgroud)

....

import requests

with open("url10.txt") as f:
    urls = f.read().splitlines()

print(urls)
for url in urls:
    url =  'http://'+url   #Add http:// to each url (there has to be a better way to do this)
    try:
        resp = requests.get(url, timeout=1)
        print(len(resp.content), '->', resp.status_code, '->', resp.url)
    except Exception as e:
        print("Error", url)
Run Code Online (Sandbox Code Playgroud)

挑战: 通过多处理提高速度。


多处理

但它不工作。我收到以下错误:(注意:我不确定我是否正确实现了这一点) …

python multithreading multiprocessing python-multiprocessing

1
推荐指数
1
解决办法
4148
查看次数

如果我在python中使用多处理但是我的函数没有返回任何内容,我是否需要调用get()?

我想利用python的多处理模块来并行化这个简单的例子:

import numpy as np
import h5py
import os
import matplotlib.pyplot as plt
from multiprocessing import Pool

def load_array(path, variable):
    try:
        return np.array(h5py.File(path, "r").get(variable))
    except:
        raise FileNotFoundError("Corrupted file: {}".format(path))

def mat2img(rootdir, save_path, variable):

    fig = plt.figure()

    print("Processing " + rootdir)

    for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            arr = load_array(os.path.join(subdir, file), variable).T

            fig.subplots_adjust(top=1, bottom=0, right=1, left=0)
            plt.pcolormesh(np.arange(0, arr.shape[1]), np.arange(0, arr.shape[0]), arr, cmap="jet")
            plt.axis("off")
            plt.savefig(os.path.join(save_path, subdir.split(os.path.sep)[-1], file + ".jpg"))
            plt.clf()

if __name__ == '__main__':

    with Pool(processes=3) as pool: …
Run Code Online (Sandbox Code Playgroud)

python python-multiprocessing

1
推荐指数
1
解决办法
46
查看次数

将数据传递给 Python multiprocessing.Pool 工作进程

我正在尝试利用Pool.map(func, itr)来提高程序的性能,我需要func访问一个非常大的字典,称为cache以便它可以进行缓存查找。

cache卖场“每一个第一的二进制表示2**16的整数”。

cache = {i: bin(i) for i in range(2**16 - 1)}
Run Code Online (Sandbox Code Playgroud)

的职责func是计算传递给它的二进制表示中的1son-bits的数量int

def func(i: int) -> int:
    return cache[i].count("1")
Run Code Online (Sandbox Code Playgroud)

我想做如下事情:

with Pool(8) as pool:
    counts = pool.map(func, [i for i in range(2**16-1)])
Run Code Online (Sandbox Code Playgroud)

但是如何使cache对象func在每个工作子进程中可用?

python python-multiprocessing

1
推荐指数
1
解决办法
1801
查看次数

是否可以在 Python 的线程中生成一个进程?

我正在编写一个程序,该程序生成一个进程并在某些条件下重新启动该进程。例如,如果子进程在一段时间内不再向母进程发送数据,我希望母进程终止子进程并重新启动它。我以为我可以使用线程从子进程接收数据并重新启动子进程,但它不像我想的那样工作。

import numpy as np
import multiprocessing as mp
import threading
import time
from apscheduler.schedulers.background import BackgroundScheduler

pipe_in, pipe_out = mp.Pipe()

class Mother():
    def __init__(self):
        self.pipe_out = pipe_out

        self.proc = mp.Process(target = self.test_func, args=(pipe_in, ))
        self.proc.start()

        self.thread = threading.Thread(target=self.thread_reciever, args=(self.pipe_out, ))
        self.thread.start()

    def thread_reciever(self, pipe_out):
        while True:
            value = pipe_out.recv()

            print(value)
            if value == 5:
                self.proc.terminate()
                time.sleep(2)
                self.proc = mp.Process(target = self.test_func)
                self.proc.start()

    def test_func(self, pipe_in):
        for i in range(10):
            pipe_in.send(i)
            time.sleep(1)


if __name__ == '__main__':
    r = Mother()
Run Code Online (Sandbox Code Playgroud)

它打印出这个错误。 …

python windows multithreading multiprocessing python-multiprocessing

1
推荐指数
1
解决办法
2478
查看次数

在python中使用多重处理时无法使用所有处理器

我正在研究python,并尝试学习多处理。当我尝试以下代码时,它应该并行运行,但仅使用一个处理器。我无法理解原因。可能是什么问题,为什么它没有使用我PC的所有4个核心。

我尝试的代码如下:

import multiprocessing
import time
start = time.perf_counter()

def do_something():
    print("hello")
    time.sleep(1)
    print("done")

p1 = multiprocessing.Process(target=do_something())
p2 = multiprocessing.Process(target=do_something())
p1.start()
p2.start()
p1.join()
p2.join()
finish = time.perf_counter()
print(f'finished in {round(finish-start,1)} sec')
Run Code Online (Sandbox Code Playgroud)

结果:

hello
done
hello
done
finished in 2.1 sec
Run Code Online (Sandbox Code Playgroud)

它应在1秒钟(大约)内执行

我用来查找内核数的代码:

import multiprocessing
print("Number of cpu : ", multiprocessing.cpu_count())
Run Code Online (Sandbox Code Playgroud)

结果:

Number of cpu :  4
Run Code Online (Sandbox Code Playgroud)

我尝试过的另一段代码是:

from multiprocessing import Lock, Process, Queue, current_process
import time
import queue # imported for using queue.Empty exception


def do_job(tasks_to_accomplish, …
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-multiprocessing

1
推荐指数
1
解决办法
57
查看次数