小编Sun*_*ear的帖子

如果OS Python版本是3.5,如何设置pipenv Python 3.6项目?

我的Ubuntu 16.04.03安装了Python 3.5.2.当我的系统没有python 3.6时,如何设置pipenv以使用Python 3.6?

$ pipenv --python 3.6
Warning: Python 3.6 was not found on your system…
You can specify specific versions of Python with:
  $ pipenv --python path/to/python
Run Code Online (Sandbox Code Playgroud)

python pipenv

31
推荐指数
4
解决办法
3万
查看次数

python concurrent.futures.ProcessPoolExecutor:.submit()vs .map()的性能

我使用concurrent.futures.ProcessPoolExecutor来查找数字范围内的数字的出现.目的是调查从并发中获得的加速性能的数量.为了测试性能,我有一个控件 - 一个执行所述任务的串行代码(如下所示).我编写了2个并发代码,一个使用concurrent.futures.ProcessPoolExecutor,另一个concurrent.futures.ProcessPoolExecutor.submit()用于执行相同的任务.它们如下所示.关于起草前者和后者的建议可分别在这里这里看到.

发给所有三个代码的任务是在0到1E8的数字范围内找到数字5的出现次数.无论concurrent.futures.ProcessPoolExecutor.map().submit()被指派6名工人,并.map()有10000 CHUNKSIZE.在并发代码中,分离工作负载的方式是相同的.但是,用于在两个代码中查找出现的函数是不同的.这是因为参数传递给.submit()和.map()调用的函数的方式不同.

所有3个代码报告的发生次数相同,即56,953,279次.但是,完成任务所需的时间非常不同..map()执行速度比控制快2倍,同时控制时间.submit()是控制完成任务的两倍.

问题:

  1. 我想知道.map()我的编码是否是一个神器,或者它本身就很慢?"如果是前者,我怎么能改进它.我只是惊讶它表现得比控制慢,因为没有多少激励使用它.
  2. 我想知道是否还有.submit()更快的代码执行.我有一个条件是函数.map()必须返回一个包含数字5的数字/出现次数的iterable.

基准测试结果
基准结果

concurrent.futures.ProcessPoolExecutor.submit()

#!/usr/bin/python3.5
# -*- coding: utf-8 -*-

import concurrent.futures as cf
from time import time
from traceback import print_exc

def _findmatch(nmin, nmax, number):
    '''Function to find the occurrence of number in range nmin to nmax and return
       the found occurrences in a list.'''
    print('\n def _findmatch', …
Run Code Online (Sandbox Code Playgroud)

python concurrency performance python-3.x concurrent.futures

13
推荐指数
2
解决办法
5108
查看次数

如何将具有多个参数的函数传递给python concurrent.futures.ProcessPoolExecutor.map()?

我想concurrent.futures.ProcessPoolExecutor.map()调用一个由2个或更多参数组成的函数.在下面的示例中,我使用了一个lambda函数并将其定义refnumberlist具有相同值的相同大小的数组.

第一个问题:有更好的方法吗?在numberlist的大小可能是数百万到数十亿个元素的情况下,因此ref大小必须遵循numberlist,这种方法不必要地占用宝贵的内存,我想避免.我这样做是因为我读取map函数将终止其映射,直到达到最短的数组结束.

import concurrent.futures as cf

nmax = 10
numberlist = range(nmax)
ref = [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
workers = 3


def _findmatch(listnumber, ref):    
    print('def _findmatch(listnumber, ref):')
    x=''
    listnumber=str(listnumber)
    ref = str(ref)
    print('listnumber = {0} and ref = {1}'.format(listnumber, ref))
    if ref in listnumber:
        x = listnumber
    print('x = {0}'.format(x))
    return x 

a = map(lambda x, y: _findmatch(x, y), numberlist, ref)
for n …
Run Code Online (Sandbox Code Playgroud)

python concurrency lambda python-3.x concurrent.futures

12
推荐指数
3
解决办法
9159
查看次数

我应该什么时候使用 pathlib.Path.mkdir() 与 os.mkdir() 或 os.makedirs()?

根据 python 3.6 文档,可以通过以下方式创建目录:

  1. pathlib.Path.mkdir(mode=0o777, parents=False, exist_ok=False)
  2. os.mkdir(path, mode=0o777, *, dir_fd=None)
  3. os.makedirs(name, mode=0o777, exist_ok=False)

问题:

  1. 它看起来像pathlib.Path.mkdir()做了大部分什么os.mkdir()os.makedirs()做什么。是pathlib.Path.mkdir()一个“现代”的实施两者的os.mkdir()os.makedirs()
  2. 我什么时候应该使用pathlib.Path.mkdir()vsos.mkdir()os.makedirs()? 有什么性能差异吗?

请解释有关 POSIX 的注意事项。谢谢。

python directory subdirectory pathlib

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

Tk 是否提供对 Wayland 显示协议的支持?

视频向我介绍了 X 的问题以及 Wayland 协议的替代方案。多年来,Wayland 协议的采用似乎在不断增长。

我的问题:

  1. tkinter 和 tcl/Tk 是否会遵守 Wayland 协议?如果是这样,预计什么时候发生?已经发生了吗?路线图是什么?
  2. 使用 Wayland Display 协议将如何改变 tkinter 编程?

tk-toolkit wayland

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

有关使用ttk.Style()的问题?

为了使ttk.Style()类的实例可用,这个tkinter 指南中说明了语法是:

import ttk
s=ttk.Style()
Run Code Online (Sandbox Code Playgroud)

在IDLE中输入这些命令时,我注意到ttk.Style()实际上有一个预定义的参数,即

s=ttk.Style(master=None)
Run Code Online (Sandbox Code Playgroud)

我写了以下测试脚本:

import tkinter as tk
import tkinter.ttk as ttk


class App(ttk.Frame):

    def __init__(self, parent):
        ttk.Frame.__init__(self, parent, style='App.TFrame', relief=tk.SUNKEN,
                           border=10)
        self.parent = parent
        self.__createStyle()
        self.__createWidgets()

    def __createStyle(self):
        self.s = ttk.Style()
        self.s.configure('.', background='orange', border=100)
        self.s.configure('App.TFrame', background='yellow')
        self.s.configure('Btn.TButton', background='light blue', border=10)

    def __createWidgets(self):
        self._label = ttk.Label(self.parent, text='Label packed in root.')
        self._label.pack()
        self._btn = ttk.Button(self, style='Btn.TButton', command=self.__click,
            text='Button packed inside self or class App, which is a ttk.Frame')
        self._btn.pack()

    def __click(self):
        return print('Left Button Clicked!')



class …
Run Code Online (Sandbox Code Playgroud)

python tkinter ttk

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

为并发.futures.ProcessPoolExecutor 播种 numpy.random 的 default_rng 和 SeedSequence 对象

我正在学习设置 NumPy 版本 1.19 伪随机数生成器的种子以进行 Python 3.6concurrent.futures.ProcessPoolExecutor分析。在阅读了 NumPy 关于 随机采样并行随机数生成的文档后,我编写了以下脚本来评估我的理解。

我的目标:我想确保每个并发进程使用相同的种子来启动随机进程。

我从结果中学到了什么?

  1. (a) 使用全局种子,(b) 在将种子传递到并发进程之前预定义numpy.random.default_rngnumpy.random.SeedSequence使用种子,以及 (c) 将种子作为参数传递到并发进程中给出相同的结果并确保每个并发进程使用相同的种子开始随机过程。也就是说,不需要为每个并发进程重新创建 BitGenerator。

  2. 使用种子numpy.random.SeedSequence()对象的生成子种子不能确保每个并发进程使用相同的种子来启动随机进程。spawn()对象方法的作用SeedSequence()是确保使用 BitGenerator 结果的不同部分以避免重复?

问:我的结论正确吗?

测试脚本:

import numpy as np
from numpy.random import default_rng, SeedSequence
import concurrent.futures as cf

def random( loop ):
    rg = default_rng()
    return loop, [rg.random() for x in range(5)] 

def random_global( loop ):
    rg = default_rng(SEED)
    return loop, [rg.random() for x in …
Run Code Online (Sandbox Code Playgroud)

python random numpy concurrent.futures

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

如何用图像替换 ttk.Treeview 父节点箭头?

问题:如何在 tkinter.ttk.Treeview 中创建一个节点,其中节点的切换箭头被定义的图像替换?也就是说,我如何从第二张图片转到第一张图片,如下所示。

问题:新墨西哥技术指南显示tkinter.ttk.Treeview可以创建文件夹目录,如下所示:

实现

使用带有“image”关键字的 tkinter.ttk.Treeview .insert() 方法,我只能实现以下目标。图像确实出现在节点文本的左侧,但该图像不会替换切换节点的打开和关闭以显示其后代的箭头。我假设由“image”关键字定义的图像将取代切换箭头。但这并没有发生。

迄今为止已取得的成绩

测试代码:

import os
import tkinter as tk
import tkinter.ttk as ttk
from PIL import Image, ImageTk

class App(ttk.Frame):

    def __init__(self, master, path):

        ttk.Frame.__init__(self, master)
        self.tree = ttk.Treeview(self)
        ysb = ttk.Scrollbar(self, orient='vertical', command=self.tree.yview)
        xsb = ttk.Scrollbar(self, orient='horizontal', command=self.tree.xview)
        self.tree.configure(yscroll=ysb.set, xscroll=xsb.set)
        self.tree.heading('#0', text='Directory', anchor='w')

        abspath = os.path.abspath(path)
        i = './icon/Home-icon_16.gif'
        self.root_pic = tk.PhotoImage(file=i)
        root_node = self.tree.insert('', 'end', text='  Work Folder', open=True, image=self.root_pic)
        l1_node = self.tree.insert(root_node, 'end', text='level 1', open=True)
        l2_node …
Run Code Online (Sandbox Code Playgroud)

image tkinter treeviewitem ttk python-3.x

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

如何删除 pipenv 的 PipFile、PipFile.lock 和关联的 virtualenv?

要创建pipenv一个Python项目,我首先创建一个项目文件夹,进入该文件夹,指示pipenv创建的PipfilePipfile.lock并且像这样相关的虚拟环境:

$ mkdir Project
$ cd Project
$ pipenv --three
Creating a virtualenv for this project…
Using /usr/bin/python3 (3.5.2) to create virtualenv…
?Already using interpreter /usr/bin/python3
Using base prefix '/usr'
New python executable in ~/.local/share/virtualenvs/Projects-jrsJaPdI/bin/python3
Also creating executable in ~/.local/share/virtualenvs/Projects-jrsJaPdI/bin/python
Installing setuptools, pip, wheel...done.

Virtualenv location: ~/.local/share/virtualenvs/Projects-jrsJaPdI
Creating a Pipfile for this project…
$
$ pipenv install --dev
Pipfile.lock not found, creating…
Locking [dev-packages] dependencies…
Locking [packages] dependencies…
Updated Pipfile.lock (711973)!
Installing …
Run Code Online (Sandbox Code Playgroud)

python pipenv

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

如何使用 Python3.6 tarfile 模块从内存中读取?

我想从url内存中下载一个 tarfile,然后将其所有内容提取到文件夹中dst。我该怎么办?

以下是我的尝试,但我无法实现我的计划。

#!/usr/bin/python3.6
# -*- coding: utf-8 -*-

from pathlib import Path
from io import BytesIO
from urllib.request import Request, urlopen
from urllib.error import URLError
from tarfile import TarFile


def get_url_response( url ):
    req = Request( url )
    try:
        response = urlopen( req )
    except URLError as e:
        if hasattr( e, 'reason' ):
            print( 'We failed to reach a server.' )
            print( 'Reason: ', e.reason )
        elif hasattr( e, 'code'):
            print( 'The server couldn\'t fulfill …
Run Code Online (Sandbox Code Playgroud)

python io urllib tarfile

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