Python3 memory_profiler,同时使用lambda表达式连接PyQt5中的插槽

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python3 memory_profiler,同时使用lambda表达式连接PyQt5中的插槽相关的知识,希望对你有一定的参考价值。

我正在以下Python3中试验memory_profiler

https://medium.com/zendesk-engineering/hunting-for-memory-leaks-in-python-applications-6824d0518774

感谢@eyllanesc在这里PyQt5 designer gui and iterate/loop over QPushButton [duplicate]

我刚刚创建了一个带有21个按钮a到z的主窗口;每次按其中一个,我都会打印代表的字母。

同时阅读:Using lambda expression to connect slots in pyqt我碰到:

“提防!一旦您将信号连接到具有self引用的lambda插槽,您的小部件就不会被垃圾收集!这是因为lambda创建了一个闭包,并带有另一个无法收集的小部件引用。

因此,self.someUIwidget.someSignal.connect(lambda p:self.someMethod(p))非常邪恶:)“

这里是我的剧情:memory_profiler plot while pressing buttons

同时按下按钮。

我的剧情显示了这种行为吗?还是看起来是直线的直线?

然后有什么替代方法?给我:

use for letter in "ABCDE": getattr(self, letter).clicked.connect(lambda checked, letter=letter: foo(letter))

main.py:hangman_pyqt5-muppy.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May  5 19:21:27 2020

@author: Pietro

"""

import sys

from PyQt5 import QtWidgets, uic

from PyQt5.QtWidgets import QDesktopWidget

import hangman005

#from pympler import muppy, summary #########################################
#
#from pympler import tracker

#import resource


WORDLIST_FILENAME = "words.txt"

wordlist = hangman005.load_words(WORDLIST_FILENAME)



def main():


    def center(self):                     
        qr = self.frameGeometry()   
        cp = QDesktopWidget().availableGeometry().center()    
        qr.moveCenter(cp)    
        self.move(qr.topLeft())


    class MainMenu(QtWidgets.QMainWindow):


        def __init__(self):        
            super(MainMenu, self).__init__()            
            uic.loadUi('main_window2.ui', self)                       
#                self.ButtonQ.clicked.connect(self.QPushButtonQPressed)             
            self.centro = center(self)             
            self.centro                      
#            self.show() 
            self.hangman()



        def closeEvent(self, event): #Your desired functionality here         
            close = QtWidgets.QMessageBox.question(self,
                                         "QUIT",
                                         "Are you sure want to stop process?",
                                         QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
            if close == QtWidgets.QMessageBox.Yes:
                event.accept()
            else:
                event.ignore()

        def printo(self, i):
            print('oooooooooooooooooooooo :', i)   
#            all_objects = muppy.get_objects()
#            sum1 = summary.summarize(all_objects)# Prints out a summary of the large objects
#            summary.print_(sum1) from pympler import tracker
#           
#
#            self.memory_tracker = tracker.SummaryTracker()
#            self.memory_tracker.print_diff()

        def hangman(self):
            letters_guessed=[]
            max_guesses = 6
            secret_word = hangman005.choose_word(wordlist)
            secret_word_lenght=len(secret_word)
            secret_word=hangman005.splitt(secret_word)
            vowels=('a','e','i','o','u')
            secret_word_print=('_ '*secret_word_lenght )
            self.word_to_guess.setText(secret_word_print )
            letters=hangman005.splitt('ABCDEFGHIJKLMNOPQRSTYVWXXYZ')
            print(letters )
            for i in letters:
                print('lllllllllllllll : ' ,i)
#                 button = "self.MainMenu."+i
#                 self.[i].clicked.connect(self.printo(i))
#                 button = getattr(self, i)
#                button.clicked.connect((lambda : self.printo(i for i in letters) )    )
#                 button.clicked.connect(lambda j=self.printo(i) : j )
#                 button.clicked.connect(lambda : self.printo(i))
#                button.clicked.connect(lambda: self.printo(i))
#            button.clicked.connect(lambda j=self.printo(i) : j   for i in letters )
#                 getattr(self, i).clicked.connect(lambda checked, i=i: self.printo(i))
#                 getattr(self, i).clicked.connect(lambda checked, j=i: self.printo(j))
                getattr(self, i).clicked.connect(lambda pippo, j=i: self.printo(j))
#            self.A.clicked.connect(self.printo)
# Add to leaky code within python_script_being_profiled.py

                 # Get references to certain types of objects such as dataframe
#                dataframes = [ao for ao in all_objects if isinstance(ao, pd.DataFrame)]
#                
#                for d in dataframes:
#                    print (d.columns.values)
#                    print (len(d))                







    app = QtWidgets.QApplication(sys.argv)

#    sshFile="coffee.qss"
#    with open(sshFile,"r") as fh:
#        app.setStyleSheet(fh.read())

    window=MainMenu()
    window.show()

    app.exec_()

#all_objects = muppy.get_objects()
#sum1 = summary.summarize(all_objects)# Prints out a summary of the large objects
#summary.print_(sum1)# Get references to certain types of objects such as dataframe

if __name__ == '__main__':
    main()

hangman005.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 29 19:36:32 2020

@author: Pietro
"""



import random
import string



#WORDLIST_FILENAME = "words.txt"


def load_words(WORDLIST_FILENAME):
    """
    Returns a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
#    print(line)
#    for elem in line:
#        print (elem)
#    print(wordlist)
#    for elem in wordlist:
#        print ('
' , elem) 
    return wordlist



def choose_word(wordlist):
    """
    wordlist (list): list of words (strings)

    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

# end of helper code

# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program

#wordlist = load_words()



def splitt(word): 
    return [char for char in word]   


def is_word_guessed(secret_word, letters_guessed):
    '''
    secret_word: string, the word the user is guessing; assumes all letters are
      lowercase
    letters_guessed: list (of letters), which letters have been guessed so far;
      assumes that all letters are lowercase
    returns: boolean, True if all the letters of secret_word are in letters_guessed;
      False otherwise
    '''
    prova =all(item in letters_guessed for item in secret_word )    
    print(' prova : ' , prova )
    return prova 

#secret_word='popoli'
#letters_guessed=['p','o','p','o','l','i']
#letters_guessed=['p','i','l']    
#print('

is_word_guessed : ', is_word_guessed(secret_word,letters_guessed))
#letters_guessed = []


def get_guessed_word(secret_word, letters_guessed):
    '''
    secret_word: string, the word the user is guessing
    letters_guessed: list (of letters), which letters have been guessed so far
    returns: string, comprised of letters, underscores (_), and spaces that represents
      which letters in secret_word have been guessed so far.
    '''
    print('

secret_word_split' , secret_word)
    print('letters_guessed', letters_guessed )
    results=[]
    for val in range(0,len(secret_word)):
            if secret_word[val] in letters_guessed:
                results.append(secret_word[val])
            else:
                results.append('_')
    print('
results : ' , ' '.join(results ))        
    return results


def get_available_letters(letters_guessed):
    '''secret_word_split
    letters_guessed: list (of letters), which letters have been guessed so far
    returns: string (of letters), comprised of letters that represents which letters have not
      yet been guessed.
    '''
    entire_letters='abcdefghijklmnopqrstuvwxyz'
    entire_letters_split=splitt(entire_letters)
    entire_letters_split = [x for x in entire_letters_split if x not in letters_guessed]
    return entire_letters_split




def hangman(secret_word):
    '''
    secret_word: string, the secret word to guess.

    Starts up an interactive game of Hangman.

    * At the start of the game, let the user know how many 
      letters the secret_word contains and how many guesses s/he starts with.

    * The user should start with 6 guesses

    * Before each round, you should display to the user how many guesses
      s/he has left and the letters that the user has not yet guessed.

    * Ask the user to supply one guess per round. Remember to make
      sure that the user puts in a letter!

    * The user should receive feedback immediately after each guess 
      about whether their guess appears in the computer's word.

    * After each guess, you should display to the user the 
      partially guessed word so far.
    secret_word_split
    Follows the other limitations detailed in the problem write-up.
    '''

    letters_guessed=[]
    max_guesses = 6
    secret_word_lenght=len(secret_word)
    secret_word=splitt(secret_word)
    vowels=('a','e','i','o','u')

    print('
Welcome to HANGMAN ;-) ')
    print('
secret_word_lenght : ' , secret_word_lenght  ) 
    print('
'+' _ '*secret_word_lenght )
    print('
you have ' , max_guesses , ' guesses be carefull choosing')

    while True:
        guess= input('
make your first choice : ' )
        if guess not in get_available_letters(letters_guessed):
                print('You can only choose in' , ' '.join(get_available_letters(letters_guessed)))
                continue
        if guess in get_available_letters(letters_guessed):
                letters_guessed.append(guess)
#                print('
letters_guessed appended : ' , ' '.join(letters_guessed) )
#                max_guesses -= 1
                print(' a che punto sei : ' , ' '.join(get_guessed_word(secret_word, letters_guessed)))
#                print('
you have ' , max_guesses , ' guesses be carefull choosing')
                if guess in secret_word:
                    print('GOOD !!!!!!!!!!!!!')
                    print('
you still have ' , max_guesses , ' guesses be carefull choosing')
                else:
                    print('ERRORE !!!!!!!!!!!!!!!!!!!!!!')
                    if guess in vowels:
                        max_guesses -= 2
                    else:
                        max_guesses -= 1
                    print('
now you have only' , max_guesses , ' guesses be carefull choosing')

        if is_word_guessed(secret_word, letters_guessed) == True:
            print('
HAI VINTO !!!!!!!!!!!!!!!!!!!!!!')
            total_score= max_guesses * len(list(set(secret_word)))

            print('
il tuo punteggio è : ' , total_score)

            break
        if max_guesses <= 0:
            print('
HAI PERSO STUPIDA CAPRA !!!!!!!!!!!!!!!!!!!!!!')
            print('
la parola era : ' , ''.join(secret_word), ' you moron !!')
            break




# When you've completed your hangman function, scroll down to the bottom
# of the file and uncomment the first two lines to test
#(hint: you might want to pick your own
# secret_word while you're doing your own testing)


# -----------------------------------



def match_with_gaps(my_word, other_word):
    '''
    my_word: string with _ characters, current guess of secret word
    other_word: string, regular English word
    returns: boolean, True if all the actual letters of my_word match the 
        corresponding letters of other_word, or the letter is the special symbol
        _ , and my_word and other_word are of the same length;
        False otherwise: 
    '''

    if len(my_word) == len(other_word):

        for val in range(0,len(my_word)):
            if my_word[val] == '_':
#                print('OK')
                prova=True
            elif my_word[val] != '_' and my_word[val]==other_word[val]:
#                print('OK')
                prova=True
            else:
#                print('KO')
                prova=False
                break
    else:
#        print('DIFFERENT LENGHT')
        prova=False
    return prova


def show_possible_matches(my_word):
    '''
    my_word: string with _ characters, current guess of secret word
    returns: nothing, but should print out every word in wordlist that matches my_word
             Keep in mind that in hangman when a letter is guessed, all the positions
             at which that letter occurs in the secret word are revealed.
             Therefore, the hidden letter(_ ) cannot be one of the letters in the word
             that has already been revealed.

    '''
    x=0
    y=0
    for i in range(0,len(wordlist)):
        other_word=splitt(wordlist[i])
        if match_with_gaps(my_word, other_word):
            print(wordlist[i], end = ' ')
            x += 1
        else:
            y += 1
    print('
parole trovate : ' , x)
    print('parole saltate : ' , y)
    print('parole totali  : ' , x+y)
    print('lenght wordlist :' , len(wordlist))
    return


end = ''
def hangman_with_hints(secret_word):
    '''
    secret_word: string, the secret word to guess.

    Starts up an interactive game of Hangman.

    * At the start of the game, let the user know how many 
      letters the secret_word contains and how many guesses s/he starts with.

    * The user should start with 6 guesses
    # FILL IN YOUR CODE HERE AND DELETE "pass"
    pass
    * Before each round, you should str display to the user how many guesses
      s/he has left and the letters that the user has not yet guessed.

    * Ask the user to supply one guess per round. Make sure to check that the user guesses a letter

    * The user should receive feedback immediately after each guess 
      about whether their guess appears in the computer's word.

    * After each guess, you should display to the user the 
      partially guessed word so far.

    * If the guess is the symbol *, print out all words in wordlist that
      matches the current guessed word. 

    Follows the other limitations detailed in the problem write-up.
    '''

#    secret_word_lenght=len(secret_word)
#    print('secret_word_lenght : ' , secret_word_lenght  )

    letters_guessed=[]
    max_guesses = 6
    secret_word_lenght=len(secret_word)
    secret_word=splitt(secret_word)
    vowels=('a','e','i','o','u')

    print('
Welcome to HANGMAN ;-) ')
    print('
secret_word_lenght : ' , secret_word_lenght  ) 
    print('
 use * for superhelp !!!! ')
    print('
'+' _ '*secret_word_lenght )
    print('
you have ' , max_guesses , ' guesses be carefull choosing')

    while True:
        guess= input('
make your choice : ' )
        if guess == '*' :
                print('ATTENZIONE SUPER BONUS !!!')
                my_word=(get_guessed_word(secret_word, letters_guessed))
                show_possible_matches(my_word)
                continue
        if guess not in get_available_letters(letters_guessed):
                print('You can only choose in' , ' '.join(get_available_letters(letters_guessed)))
                continue
        if guess in get_available_letters(letters_guessed):
                letters_guessed.append(guess)
#                print('
letters_guessed appended : ' , ' '.join(letters_guessed) )
#                max_guesses -= 1
                print(' a che punto sei : ' , ' '.join(get_guessed_word(secret_word, letters_guessed)))
#                print('
you have ' , max_guesses , ' guesses be carefull choosing')
                if guess in secret_word:
                    print('GOOD !!!!!!!!!!!!!')
                    print('
you still have ' , max_guesses , ' guesses be carefull choosing')
                else:
                    print('ERRORE !!!!!!!!!!!!!!!!!!!!!!')
                    if guess in vowels:
                        max_guesses -= 2
                    else:
                        max_guesses -= 1
                    print('
now you have only' , max_guesses , ' guesses be carefull choosing')

        if is_word_guessed(secret_word, letters_guessed) == True:
            print('
HAI VINTO !!!!!!!!!!!!!!!!!!!!!!')
            total_score= max_guesses * len(list(set(secret_word)))

            print('
il tuo punteggio è : ' , total_score)

            break
        if max_guesses <= 0:
            print('
HAI PERSO STUPIDA CAPRA !!!!!!!!!!!!!!!!!!!!!!')
            print('
la parola era : ' , ''.join(secret_word).upper(), ' you moron !!')
            break

# When you've completed your hangman_with_hint function, comment the two similar
# lines above that were used to run the hangman function, and then uncomment
# these two lines and run this file to test!
# Hint: You might want to pick your own secret_word while you're testing.


#if __name__ == "__main__":
    # passui

    # To test part 2, comment out the pass line above and
    # uncomment the following two lines.

#    secret_word = choose_word(wordlist)
#    hangman(secret_word)

###############

    # To test part 3 re-comment out the above lines and 
    # uncomment the following two lines. 

#    secret_word = choose_word(wordlist)
#    hangman_with_hints(secret_word)

ui文件,main_window2.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>863</width>
    <height>687</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>HANGMAN</string>
  </property>
  <property name="styleSheet">
   <string notr="true"/>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QLabel" name="word_to_guess">
    <property name="geometry">
     <rect>
      <x>250</x>
      <y>60</y>
      <width>341</width>
      <height>91</height>
     </rect>
    </property>
    <property name="font">
     <font>
      <pointsize>18</pointsize>
      <weight>75</weight>
      <bold>true</bold>
     </font>
    </property>
    <property name="text">
     <string>word_to_guess</string>
    </property>
    <property name="alignment">
     <set>Qt::AlignCenter</set>
    </property>
   </widget>
   <widget class="QGroupBox" name="groupBox">
    <property name="geometry">
     <rect>
      <x>20</x>
      <y>170</y>
      <width>821</width>
      <height>201</height>
     </rect>
    </property>
    <property name="styleSheet">
     <string notr="true">QPushButton{
    background-color: #9de650;
}


QPushButton:hover{
    background-color: green;
}

</string>
    </property>
    <property name="title">
     <string>GroupBox</string>
    </property>
    <widget class="QPushButton" name="A">
     <property name="geometry">
      <rect>
       <x>30</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="autoFillBackground">
      <bool>false</bool>
     </property>
     <property name="text">
      <string>A</string>
     </property>
    </widget>
    <widget class="QPushButton" name="B">
     <property name="geometry">
      <rect>
       <x>90</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>B</string>
     </property>
    </widget>
    <widget class="QPushButton" name="C">
     <property name="geometry">
      <rect>
       <x>150</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>C</string>
     </property>
    </widget>
    <widget class="QPushButton" name="D">
     <property name="geometry">
      <rect>
       <x>210</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>D</string>
     </property>
    </widget>
    <widget class="QPushButton" name="E">
     <property name="geometry">
      <rect>
       <x>270</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>E</string>
     </property>
    </widget>
    <widget class="QPushButton" name="F">
     <property name="geometry">
      <rect>
       <x>330</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>F</string>
     </property>
    </widget>
    <widget class="QPushButton" name="G">
     <property name="geometry">
      <rect>
       <x>390</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>G</string>
     </property>
    </widget>
    <widget class="QPushButton" name="H">
     <property name="geometry">
      <rect>
       <x>450</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>H</string>
     </property>
    </widget>
    <widget class="QPushButton" name="I">
     <property name="geometry">
      <rect>
       <x>510</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>I</string>
     </property>
    </widget>
    <widget class="QPushButton" name="J">
     <property name="geometry">
      <rect>
       <x>570</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>J</string>
     </property>
    </widget>
    <widget class="QPushButton" name="K">
     <property name="geometry">
      <rect>
       <x>630</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>K</string>
     </property>
    </widget>
    <widget class="QPushButton" name="L">
     <property name="geometry">
      <rect>
       <x>690</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>L</string>
     </property>
    </widget>
    <widget class="QPushButton" name="M">
     <property name="geometry">
      <rect>
       <x>750</x>
       <y>50</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>M</string>
     </property>
    </widget>
    <widget class="QPushButton" name="N">
     <property name="geometry">
      <rect>
       <x>30</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>N</string>
     </property>
    </widget>
    <widget class="QPushButton" name="O">
     <property name="geometry">
      <rect>
       <x>90</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>O</string>
     </property>
    </widget>
    <widget class="QPushButton" name="P">
     <property name="geometry">
      <rect>
       <x>150</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>P</string>
     </property>
    </widget>
    <widget class="QPushButton" name="Q">
     <property name="geometry">
      <rect>
       <x>210</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>Q</string>
     </property>
    </widget>
    <widget class="QPushButton" name="R">
     <property name="geometry">
      <rect>
       <x>270</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>R</string>
     </property>
    </widget>
    <widget class="QPushButton" name="S">
     <property name="geometry">
      <rect>
       <x>330</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>S</string>
     </property>
    </widget>
    <widget class="QPushButton" name="T">
     <property name="geometry">
      <rect>
       <x>390</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>T</string>
     </property>
    </widget>
    <widget class="QPushButton" name="U">
     <property name="geometry">
      <rect>
       <x>450</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>U</string>
     </property>
    </widget>
    <widget class="QPushButton" name="V">
     <property name="geometry">
      <rect>
       <x>510</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>V</string>
     </property>
    </widget>
    <widget class="QPushButton" name="W">
     <property name="geometry">
      <rect>
       <x>570</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>W</string>
     </property>
    </widget>
    <widget class="QPushButton" name="X">
     <property name="geometry">
      <rect>
       <x>630</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>X</string>
     </property>
    </widget>
    <widget class="QPushButton" name="Y">
     <property name="geometry">
      <rect>
       <x>690</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>Y</string>
     </property>
    </widget>
    <widget class="QPushButton" name="Z">
     <property name="geometry">
      <rect>
       <x>750</x>
       <y>120</y>
       <width>41</width>
       <height>41</height>
      </rect>
     </property>
     <property name="text">
      <string>Z</string>
     </property>
    </widget>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>863</width>
     <height>29</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar">
   <property name="sizeGripEnabled">
    <bool>true</bool>
   </property>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

words.txt:

 sinew sings singe sinks sinus sioux sires sired siren sisal sissy sitar sites sited sixes sixty sixth sizes sized skate skeet skein skews skids skied skier skies skiff skill skims skimp skins skink skips skirl skirt skits skulk skull skunk slabs slack slags slain slake slams slang slant slaps slash slats slate slavs slave slaws slays sleds sleek sleep sleet slept slews slice slick slide slier slims slime slimy sling slink slips slits sloes slogs sloop slops slope 

如此处所述:

Using lambda expression to connect slots in pyqt

“使用带有闭包的插槽并不有害。如果您担心对象清理,只需显式断开连接到插槽的所有信号,这些信号会在要删除的对象上形成闭包。”

我什么都不懂。我怎么可能断开信号?

答案

this post中指出的问题与PyQt5无关,而是与lambda函数有关,因为与任何函数一样,它创建了一个作用域并存储了内存,以测试OP指出的内容,我创建了以下示例:

from PyQt5 import QtCore, QtWidgets


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.counter = 0
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.on_timeout)
        self.timer.start(1000)

        self.button = QtWidgets.QPushButton("Press me")
        self.setCentralWidget(self.button)

    @QtCore.pyqtSlot()
    def on_timeout(self):
        self.counter += 1
        if self.counter % 2 == 0:
            self.connect()
        else:
            self.disconnect()

    def connect(self):
        self.button.setText("Connected")
        self.button.clicked.connect(lambda checked: None)
        # or
        # self.button.clicked.connect(lambda checked, v=list(range(100000)): None)

    def disconnect(self):
        self.button.setText("Disconnected")
        self.button.disconnect()


def main():
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()
  • self.button.clicked.connect(lambda checked: None)

enter image description here

  • self.button.clicked.connect(lambda checked, v=list(range(100000)): None)

enter image description here

如在连接和断开时所观察到的,由于lambda保持v=list(range(100000))的信息,因此消耗的内存增加了。>


但是在您的代码中,闭包仅存储最小的变量“ j”:

getattr(self, i).clicked.connect(lambda pippo, j=i: self.printo(j))

除了提供替代方案之外,还要查看此变量如何影响我将消除测试的不必要代码(hangman005.py等):>

  • 不连接:
    class MainMenu(QtWidgets.QMainWindow):
        def __init__(self):
            super(MainMenu, self).__init__()
            uic.loadUi("main_window2.ui", self)
            self.hangman()
    
        def hangman(self):
            letters = "ABCDEFGHIJKLMNOPQRSTYVWXXYZ"
            for i in letters:
                pass
    
        def printo(self, i):
            print("oooooooooooooooooooooo :", i)
    
  • enter image description here

  • 带有lambda:
    class MainMenu(QtWidgets.QMainWindow):
        def __init__(self):
            super(MainMenu, self).__init__()
            uic.loadUi("main_window2.ui", self)
            self.hangman()
    
        def hangman(self):
            letters = "ABCDEFGHIJKLMNOPQRSTYVWXXYZ"
            for i in letters:
                getattr(self, i).clicked.connect(lambda pippo, j=i: self.printo(j))
    
        def printo(self, i):
            print("oooooooooooooooooooooo :", i)
    
  • enter image description here

  • with functools.partial
    class MainMenu(QtWidgets.QMainWindow):
        def __init__(self):
            super(MainMenu, self).__init__()
            uic.loadUi("main_window2.ui", self)
            self.hangman()
    
        def hangman(self):
            letters = "ABCDEFGHIJKLMNOPQRSTYVWXXYZ"
            for i in letters:
                getattr(self, i).clicked.connect(partial(self.printo, i))
    
        def printo(self, i):
            print("oooooooooooooooooooooo :", i)
    
  • enter image description here

  • 一旦连接
    class MainMenu(QtWidgets.QMainWindow):
        def __init__(self):
            super(MainMenu, self).__init__()
            uic.loadUi("main_window2.ui", self)
            self.hangman()
    
        def hangman(self):
            letters = "ABCDEFGHIJKLMNOPQRSTYVWXXYZ"
            for i in letters:
                getattr(self, i).setProperty("i", i)
                getattr(self, i).clicked.connect(self.printo)
    
        def printo(self):
            i = self.sender().property("i")
            print("oooooooooooooooooooooo :", i)
    
  • enter image description here

我们可以看到,所有方法之间没有显着差异,因此,在您的情况下,没有内存泄漏,或者它很小。

结论:每次创建lambda方法时,它都有一个闭包(在您的情况下为j = i),因此OP建议考虑到此情况,例如,在您的情况下,消耗的len(letters) * size_of(i)会变小letters并且i可以忽略不计,但是如果您另外不必要地存储了较重的对象,则将导致问题。

以上是关于Python3 memory_profiler,同时使用lambda表达式连接PyQt5中的插槽的主要内容,如果未能解决你的问题,请参考以下文章

使用 memory_profiler 时无法导入模块

使用 memory_profiler 在 Flask 应用程序中分析行

使用memory_profiler时无法导入模块

如何使用 Python 多处理和 memory_profiler 分析多个子进程?

psutil 是因为该包能提升 memory_profiler 的性能

分析 python 生成器中的内存使用情况