zoukankan      html  css  js  c++  java
  • Pyqt清空Win回收站

         Pyqt清空回收站其实的调用Python的第三方库,通过第三方库调用windows的api删除回收站的数据

    一. 准备工作

    先下载第三方库winshell

    下载地址: https://github.com/tjguk/winshell/tree/stable

    关于winshell的文档: http://winshell.readthedocs.org/en/latest/recycle-bin.html#winshell.ShellRecycleBin.versions

    该库依赖于win32con (自行下载安装)

    安装winshell

    1 python setup.py install

    使用的时候  import winshell

    二. 创建UI

    用Py Designer 设计出UI,本部分主要用到pyqt的 QTableWidget

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <ui version="4.0">
     3  <class>recycleBin</class>
     4  <widget class="QWidget" name="recycleBin">
     5   <property name="geometry">
     6    <rect>
     7     <x>0</x>
     8     <y>0</y>
     9     <width>640</width>
    10     <height>422</height>
    11    </rect>
    12   </property>
    13   <property name="windowTitle">
    14    <string>Form</string>
    15   </property>
    16   <widget class="QGroupBox" name="groupBox">
    17    <property name="geometry">
    18     <rect>
    19      <x>30</x>
    20      <y>20</y>
    21      <width>561</width>
    22      <height>311</height>
    23     </rect>
    24    </property>
    25    <property name="title">
    26     <string>回收站列表</string>
    27    </property>
    28    <widget class="QTableWidget" name="tableWidget">
    29     <property name="geometry">
    30      <rect>
    31       <x>10</x>
    32       <y>20</y>
    33       <width>541</width>
    34       <height>271</height>
    35      </rect>
    36     </property>
    37     <column>
    38      <property name="text">
    39       <string>名称</string>
    40      </property>
    41      <property name="font">
    42       <font>
    43        <pointsize>12</pointsize>
    44        <weight>50</weight>
    45        <bold>false</bold>
    46       </font>
    47      </property>
    48     </column>
    49     <column>
    50      <property name="text">
    51       <string>路径</string>
    52      </property>
    53      <property name="font">
    54       <font>
    55        <pointsize>12</pointsize>
    56       </font>
    57      </property>
    58     </column>
    59    </widget>
    60   </widget>
    61   <widget class="QPushButton" name="pushButtonok">
    62    <property name="geometry">
    63     <rect>
    64      <x>470</x>
    65      <y>360</y>
    66      <width>75</width>
    67      <height>23</height>
    68     </rect>
    69    </property>
    70    <property name="text">
    71     <string>清空</string>
    72    </property>
    73   </widget>
    74  </widget>
    75  <resources/>
    76  <connections/>
    77 </ui>

    预览: 

    然后 将Ui转换为py文件

    三. 逻辑的实现

    选引入winshell

    1 import winshell

    获取 回收站里面的对象

    1 All_files = winshell.recycle_bin()
    winshell.recycle_bin()

    Returns a ShellRecycleBin object representing the system Recycle Bin

    winshell.undelete(filepath)

    Find the most recent version of filepath to have been recycled and restore it to its original location on the filesystem. If a file already exists at that filepath, the copy will be renamed. The resulting filepath is returned.

    classwinshell.ShellRecycleBin

    An object which represents the union of all the recycle bins on this system. The Shell subsystem doesn’t offer any way to access drive-specific bins (except by coming across them “accidentally” as shell folders within their specific drives).

    The object (which is returned from a call to recycle_bin()) is iterable, returning the deleted items wrapped in ShellRecycledItem objects. It also exposes a couple of common-need convenience methods: versions() returns a list of all recycled versions of a given original filepath; andundelete() which restores the most-recently binned version of a given original filepath.

    The object has the following methods:

    empty(confirm=Trueshow_progress=Truesound=True)

    Empty all system recycle bins, optionally prompting for confirmation, showing progress, and playing a sort of crunching sound.

    undelete(filepath)

    cf undelete() which is a convenience wrapper around this method.

    versions(filepath)

    Return a (possibly empty) list of all recycled versions of a given filepath. Each item in the list is a ShellRecycledItem.

    获取对象的名称和路径
     1 self.dicFile = {}
     2         if All_files:
     3             for fileitem in All_files:
     4                 Fpath = str(fileitem.name())  # 获取文件的路径
     5                 FsplitName = Fpath.split('\')
     6                 Fname=FsplitName[-1]  # 获取文件的名称
     7                 self.dicFile[Fname] = Fpath
     8         else:
     9             # self.initUi.tableWidget.hide()  # 回收站没有东西,隐藏tableWidget    不同电脑系统有的不执行该方法
    10             self.emptytable()

    将获取的数据保存在dicFile中,循环dicFile输出在 tableWidget 

     1 if self.dicFile:
     2             Rowcount = len(self.dicFile)  # 求出回收站项目的个数
     3             self.initUi.tableWidget.setColumnCount(2)  # 列数固定为2
     4             self.initUi.tableWidget.setRowCount(Rowcount)  # 行数为项目的个数
     5             self.initUi.tableWidget.setColumnWidth(1,400)  # 设置第2列宽度为400像素
     6             i = 0
     7             for datakey,datavalue in self.dicFile.items():
     8                 newItem = QtGui.QTableWidgetItem(unicode(datakey))
     9                 newItemPath = QtGui.QTableWidgetItem(unicode(datavalue))
    10                 self.initUi.tableWidget.setItem(i, 0, newItem)
    11                 self.initUi.tableWidget.setItem(i, 1, newItemPath)
    12                 i += 1
    13  else:
    14        self.emptytable()

    判断回收站是否有数据对象

     1         self.initUi.tableWidget.setColumnCount(2)
     2         self.initUi.tableWidget.setRowCount(8)
     3         self.initUi.tableWidget.setColumnWidth(1,400)
     4         self.initUi.tableWidget.verticalHeader().setVisible(False)
     5         self.initUi.tableWidget.horizontalHeader().setVisible(False)
     6         textfont = QtGui.QFont("song",  17, QtGui.QFont.Bold)
     7         empinfo=QtGui.QTableWidgetItem(u'回收站内容为空,无需清理!')
     8         empinfo.setFont(textfont)
     9         self.initUi.tableWidget.setItem(0, 0, empinfo)
    10         self.initUi.tableWidget.setSpan(0, 0, 8, 2)
    11         self.initUi.pushButtonok.hide()

    完整代码:

      1 # -*- coding: utf-8 -*-
      2 
      3 # Form implementation generated from reading ui file 'recycle.ui'
      4 #
      5 # Created: Thu Jan 15 19:14:32 2015
      6 #      by: PyQt4 UI code generator 4.10.3
      7 #
      8 # WARNING! All changes made in this file will be lost!
      9 
     10 from PyQt4 import QtCore, QtGui
     11 
     12 try:
     13     _fromUtf8 = QtCore.QString.fromUtf8
     14 except AttributeError:
     15     def _fromUtf8(s):
     16         return s
     17 
     18 try:
     19     _encoding = QtGui.QApplication.UnicodeUTF8
     20     def _translate(context, text, disambig):
     21         return QtGui.QApplication.translate(context, text, disambig, _encoding)
     22 except AttributeError:
     23     def _translate(context, text, disambig):
     24         return QtGui.QApplication.translate(context, text, disambig)
     25 
     26 class Ui_recycleBin(object):
     27     def setupUi(self, recycleBin):
     28         recycleBin.setObjectName(_fromUtf8("recycleBin"))
     29         recycleBin.resize(640, 422)
     30         self.groupBox = QtGui.QGroupBox(recycleBin)
     31         self.groupBox.setGeometry(QtCore.QRect(30, 20, 561, 311))
     32         self.groupBox.setObjectName(_fromUtf8("groupBox"))
     33         self.tableWidget = QtGui.QTableWidget(self.groupBox)
     34         self.tableWidget.setGeometry(QtCore.QRect(10, 20, 541, 271))
     35         self.tableWidget.setObjectName(_fromUtf8("tableWidget"))
     36         self.tableWidget.setColumnCount(2)
     37         self.tableWidget.setRowCount(0)
     38         item = QtGui.QTableWidgetItem()
     39         font = QtGui.QFont()
     40         font.setPointSize(12)
     41         font.setBold(False)
     42         font.setWeight(50)
     43         item.setFont(font)
     44         self.tableWidget.setHorizontalHeaderItem(0, item)
     45         item = QtGui.QTableWidgetItem()
     46         font = QtGui.QFont()
     47         font.setPointSize(12)
     48         item.setFont(font)
     49         self.tableWidget.setHorizontalHeaderItem(1, item)
     50         self.pushButtonok = QtGui.QPushButton(recycleBin)
     51         self.pushButtonok.setGeometry(QtCore.QRect(470, 360, 75, 23))
     52         self.pushButtonok.setObjectName(_fromUtf8("pushButtonok"))
     53 
     54         self.retranslateUi(recycleBin)
     55         QtCore.QMetaObject.connectSlotsByName(recycleBin)
     56 
     57     def retranslateUi(self, recycleBin):
     58         recycleBin.setWindowTitle(_translate("recycleBin", "Form", None))
     59         self.groupBox.setTitle(_translate("recycleBin", "回收站列表", None))
     60         item = self.tableWidget.horizontalHeaderItem(0)
     61         item.setText(_translate("recycleBin", "名称", None))
     62         item = self.tableWidget.horizontalHeaderItem(1)
     63         item.setText(_translate("recycleBin", "路径", None))
     64         self.pushButtonok.setText(_translate("recycleBin", "清空", None))
     65 
     66 
     67 
     68 
     69 import winshell
     70 #逻辑class
     71 class Logicpy(QtGui.QWidget):
     72     def __init__(self):
     73         super(Logicpy, self).__init__()
     74         self.initUi = Ui_recycleBin()
     75         self.initUi.setupUi(self)
     76         self.setWindowTitle(u'清空回收站')
     77         self.initUi.tableWidget.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)    # 将表格变为禁止编辑
     78         self.initUi.tableWidget.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)  # 整行选中的方式
     79         self.initUi.tableWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)  #设置为可以选中多个目标
     80         # self.connect(self.initUi.pushButtonok, QtCore.SIGNAL('clicked()'), self.btnempty('sdf'))
     81         self.initUi.pushButtonok.mouseReleaseEvent=self.btnempty
     82         reload(sys)
     83         sys.setdefaultencoding("utf-8")
     84         All_files = winshell.recycle_bin()
     85         self.dicFile = {}
     86         if All_files:
     87             for fileitem in All_files:
     88                 Fpath = str(fileitem.name())  # 获取文件的路径
     89                 FsplitName = Fpath.split('\')
     90                 Fname=FsplitName[-1]  # 获取文件的名称
     91                 self.dicFile[Fname] = Fpath
     92         else:
     93             # self.initUi.tableWidget.hide()  # 回收站没有东西,隐藏tableWidget    不同电脑系统有的不执行该方法
     94             self.emptytable()
     95 
     96         self.interData()
     97     # 插入recycleBin 对象
     98     def interData(self):
     99         if self.dicFile:
    100             Rowcount = len(self.dicFile)  # 求出回收站项目的个数
    101             self.initUi.tableWidget.setColumnCount(2)  # 列数固定为2
    102             self.initUi.tableWidget.setRowCount(Rowcount)  # 行数为项目的个数
    103             self.initUi.tableWidget.setColumnWidth(1,400)  # 设置第2列宽度为400像素
    104             i = 0
    105             for datakey,datavalue in self.dicFile.items():
    106                 newItem = QtGui.QTableWidgetItem(unicode(datakey))
    107                 newItemPath = QtGui.QTableWidgetItem(unicode(datavalue))
    108                 self.initUi.tableWidget.setItem(i, 0, newItem)
    109                 self.initUi.tableWidget.setItem(i, 1, newItemPath)
    110                 i += 1
    111         else:
    112             self.emptytable()
    113     # 运行程序时, 回收站为空
    114     def emptytable(self):
    115         self.initUi.tableWidget.setColumnCount(2)
    116         self.initUi.tableWidget.setRowCount(8)
    117         self.initUi.tableWidget.setColumnWidth(1,400)
    118         self.initUi.tableWidget.verticalHeader().setVisible(False)
    119         self.initUi.tableWidget.horizontalHeader().setVisible(False)
    120         textfont = QtGui.QFont("song",  17, QtGui.QFont.Bold)
    121         empinfo=QtGui.QTableWidgetItem(u'回收站内容为空,无需清理!')
    122         empinfo.setFont(textfont)
    123         self.initUi.tableWidget.setItem(0, 0, empinfo)
    124         self.initUi.tableWidget.setSpan(0, 0, 8, 2)
    125         self.initUi.pushButtonok.hide()
    126     # 触发btn时清空回收站
    127     def btnempty(self,event):
    128         ev=event.button()
    129         OK = winshell.ShellRecycleBin.empty() # 如何判断返回类型?
    130         self.close()
    131 
    132 
    133 
    134 
    135 
    136     #重载keyPressEvent ,  当按下Esc退出
    137     def keyPressEvent(self, event):
    138         if event.key() ==QtCore.Qt.Key_Escape:
    139             self.close()
    140 
    141 
    142 
    143 
    144 if __name__ == "__main__":
    145     import sys
    146     app = QtGui.QApplication(sys.argv)
    147     RecycleLogic = Logicpy()
    148     RecycleLogic.show()
    149     sys.exit(app.exec_())

    五. 运行效果

  • 相关阅读:
    【问题】如何解决sql server链接mysql后,使用分布式事务?
    (4.57)sql server中的like,sql serverlike多个条件,sql server查找字符中出现了任意一个关键字
    prometheus+alertmanager根据配置标签来进行告警分组
    Attempt to fetch logical page (1:164360) in database 17 failed. It belongs to allocation unit 72057594328317952 not to 281474980642816.
    【基本优化实践】【1.7】sql server统计信息优化
    三角函数线
    恰成立命题
    正方体的截面
    构造函数的难点和层次
    例说导数法作函数的图像
  • 原文地址:https://www.cnblogs.com/dcb3688/p/4233190.html
Copyright © 2011-2022 走看看