我的python工具-快速定位工作目录(二)
时间:2010-08-20 来源:追求、品味、境界
接上一篇继续完成快速定位工作目录的Python工具。按照上一篇提到的设计思路,还剩最后一步即使用PyQt完成工具的图形化设计,上一篇忘记介绍我的开发环境了,主要环境只有两个:Python26 + PyQt-Py2.6-gpl-4.7.4-1.exe
Python26下载地址:http://www.python.org/download,
PyQt4下载地址:http://www.riverbankcomputing.co.uk/software/pyqt/download
下载完成并安装后,如果正常的话即可运行工具,稍后给出源码下载链接
开始编码之前,我们还是简短说下使用QT的实现工具的图形化界面开发过程
1,使用Qt创建托盘图标
2,使用Qt创建托盘图标的右键菜单
3,使用菜单命令打开主窗体
4,根据配置项初始化主窗体
5,使用主窗体操作所需功能
首次接触PyQt,还是遇到了很多麻烦,本来想着使用Qt的QTableView创捷一个表格,使用配置项的数据初始化表格,然后通过选择表格的每一行,根据配置项中给出的路径执行相应命令,可惜调了一个晚上都没有成功,郁闷,于是打开Qt安装后的例子,我本机的路径在:C:\Python26\Lib\site-packages\PyQt4\examples\dialogs\findfiles.pyw,读懂以后,经过改造,顺利的完成了工具的图形化实现,其中核心功能中对配置文件的操作稍有变动,配置内容仅仅包括工作目录,以下是核心代码片段
创建托盘图标代码 1 class MyTray(QtGui.QDialog):2 def __init__(self, parent=None):
3 QtGui.QDialog.__init__(self, parent)
4 self.quit = QtGui.QPushButton("Quit")
5 self.change = QtGui.QPushButton("Change")
6 self.change.setEnabled(False)
7 self.trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon("qp.png"), app)
8
9 self.window = Window("qp.conf");
10 self.menu = QtGui.QMenu()
11 self.openAction = QtGui.QAction("&Open ", self, triggered=self.openDlg)
12 self.exitAction = QtGui.QAction("&Quit ", self, triggered=QtGui.qApp.quit)
13 self.aboutAction = QtGui.QAction("&About ",self,triggered=self.about)
14
15 self.menu.addAction(self.aboutAction)
16 self.menu.addAction(self.exitAction)
17 self.menu.addAction(self.openAction)
18
19 self.trayIcon.setContextMenu(self.menu)
20
21 def openDlg(self):
22 self.window.show()
23
24 def about(self):
25 self.trayIcon.showMessage(u"About...",u"auther:wdong@2010-8-19")
创建主窗体代码
创建主窗体代码 1 class Window(QtGui.QDialog):2 def __init__(self, configFile,parent=None):
3 super(Window, self).__init__(parent)
4
5 self.qp = QpHelper(configFile)
6
7 browseButton = self.createButton("&Add...", self.browse)
8 commandButton = self.createButton("&Command...", self.command)
9 explorerButton = self.createButton("&Explorer...", self.explorer)
10
11 findButton = self.createButton("&Find", self.find)
12
13 self.fileComboBox = self.createComboBox("*")
14 self.textComboBox = self.createComboBox()
15 self.directoryComboBox = self.createComboBox(QtCore.QDir.currentPath())
16
17 fileLabel = QtGui.QLabel("Named:")
18 textLabel = QtGui.QLabel("Containing text:")
19 directoryLabel = QtGui.QLabel("In directory:")
20 self.filesFoundLabel = QtGui.QLabel()
21 self.createFilesTable()
22
23 buttonsLayout = QtGui.QHBoxLayout()
24 buttonsLayout.addStretch()
25 buttonsLayout.addWidget(commandButton)
26 buttonsLayout.addWidget(explorerButton)
27 buttonsLayout.addWidget(findButton)
28
29 mainLayout = QtGui.QGridLayout()
30 mainLayout.addWidget(fileLabel, 0, 0)
31 mainLayout.addWidget(self.fileComboBox, 0, 1, 1, 2)
32 mainLayout.addWidget(textLabel, 1, 0)
33 mainLayout.addWidget(self.textComboBox, 1, 1, 1, 2)
34 mainLayout.addWidget(directoryLabel, 2, 0)
35 mainLayout.addWidget(self.directoryComboBox, 2, 1)
36 mainLayout.addWidget(browseButton, 2, 2)
37 mainLayout.addWidget(self.filesTable, 3, 0, 1, 3)
38 mainLayout.addWidget(self.filesFoundLabel, 4, 0)
39 mainLayout.addLayout(buttonsLayout, 5, 0, 1, 3)
40 self.setLayout(mainLayout)
41
42 self.setWindowTitle("Find Files")
43 self.resize(700, 300)
44
45 def browse(self):
46 directory = QtGui.QFileDialog.getExistingDirectory(self, "Find Files",
47 QtCore.QDir.currentPath())
48
49 if directory:
50 if self.directoryComboBox.findText(directory) == -1:
51 self.directoryComboBox.addItem(directory)
52 self.qp.addConfigItem(directory)
53
54 self.directoryComboBox.setCurrentIndex(self.directoryComboBox.findText(directory))
55
56 def command(self):
57 path = self.directoryComboBox.currentText()
58 self.qp.openCommand(path)
59
60 def explorer(self):
61 path = self.directoryComboBox.currentText()
62 self.qp.openExplorer(path)
63
64 @staticmethod
65 def updateComboBox(comboBox):
66 if comboBox.findText(comboBox.currentText()) == -1:
67 comboBox.addItem(comboBox.currentText())
68
69 def find(self):
70 self.filesTable.setRowCount(0)
71
72 fileName = self.fileComboBox.currentText()
73 text = self.textComboBox.currentText()
74 path = self.directoryComboBox.currentText()
75
76 self.updateComboBox(self.fileComboBox)
77 self.updateComboBox(self.textComboBox)
78 self.updateComboBox(self.directoryComboBox)
79
80 self.currentDir = QtCore.QDir(path)
81 if not fileName:
82 fileName = "*"
83 files = self.currentDir.entryList([fileName],
84 QtCore.QDir.Files | QtCore.QDir.NoSymLinks)
85
86 if text:
87 files = self.findFiles(files, text)
88 self.showFiles(files)
89
90 def findFiles(self, files, text):
91 progressDialog = QtGui.QProgressDialog(self)
92
93 progressDialog.setCancelButtonText("&Cancel")
94 progressDialog.setRange(0, files.count())
95 progressDialog.setWindowTitle("Find Files")
96
97 foundFiles = []
98
99 for i in range(files.count()):
100 progressDialog.setValue(i)
101 progressDialog.setLabelText("Searching file number %d of %d..." % (i, files.count()))
102 QtGui.qApp.processEvents()
103
104 if progressDialog.wasCanceled():
105 break
106
107 inFile = QtCore.QFile(self.currentDir.absoluteFilePath(files[i]))
108
109 if inFile.open(QtCore.QIODevice.ReadOnly):
110 stream = QtCore.QTextStream(inFile)
111 while not stream.atEnd():
112 if progressDialog.wasCanceled():
113 break
114 line = stream.readLine()
115 if text in line:
116 foundFiles.append(files[i])
117 break
118
119 progressDialog.close()
120
121 return foundFiles
122
123 def showFiles(self, files):
124 for fn in files:
125 file = QtCore.QFile(self.currentDir.absoluteFilePath(fn))
126 size = QtCore.QFileInfo(file).size()
127
128 fileNameItem = QtGui.QTableWidgetItem(fn)
129 fileNameItem.setFlags(fileNameItem.flags() ^ QtCore.Qt.ItemIsEditable)
130 sizeItem = QtGui.QTableWidgetItem("%d KB" % (int((size + 1023) / 1024)))
131 sizeItem.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignRight)
132 sizeItem.setFlags(sizeItem.flags() ^ QtCore.Qt.ItemIsEditable)
133
134 row = self.filesTable.rowCount()
135 self.filesTable.insertRow(row)
136 self.filesTable.setItem(row, 0, fileNameItem)
137 self.filesTable.setItem(row, 1, sizeItem)
138
139 self.filesFoundLabel.setText("%d file(s) found (Double click on a file to open it)" % len(files))
140
141 def createButton(self, text, member):
142 button = QtGui.QPushButton(text)
143 button.clicked.connect(member)
144 return button
145
146 def createComboBox(self, text=""):
147 comboBox = QtGui.QComboBox()
148 comboBox.setEditable(True)
149 comboBox.addItem(text)
150
151 if len(self.qp.dirs) > 0:
152 map(comboBox.addItem, self.qp.dirs)
153
154 comboBox.setSizePolicy(QtGui.QSizePolicy.Expanding,
155 QtGui.QSizePolicy.Preferred)
156 return comboBox
157
158 def createFilesTable(self):
159 self.filesTable = QtGui.QTableWidget(0, 2)
160 self.filesTable.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
161
162 self.filesTable.setHorizontalHeaderLabels(("File Name", "Size"))
163 self.filesTable.horizontalHeader().setResizeMode(0, QtGui.QHeaderView.Stretch)
164 self.filesTable.verticalHeader().hide()
165 self.filesTable.setShowGrid(False)
166
167 self.filesTable.cellActivated.connect(self.openFileOfItem)
168
169 def openFileOfItem(self, row, column):
170 item = self.filesTable.item(row, 0)
171
172 QtGui.QDesktopServices.openUrl(QtCore.QUrl(self.currentDir.absoluteFilePath(item.text())))
核心配置项帮助类
核心功能代码 1 class QpHelper(object):2 def __init__(self, configFile):
3 self.file = configFile
4 self.refreshConfig()
5
6 def refreshConfig(self):
7 self.config = ConfigParser.ConfigParser()
8 self.config.read(self.file)
9 self.dirs = []
10 for name,key in self.config.items("dirs"):
11 self.dirs.append(key)
12
13 def addConfigItem(self,path):
14 if not self.dirs.find(path):
15 new_path = "path" + str(len(self.dirs)+1)
16 self.config.set("dirs",new_section,path)
17 self.saveConfig()
18
19 def saveConfig(self):
20 # Writing our configuration file to 'example.cfg'
21 with open(self.file, 'wb') as configfile:
22 self.config.write(configfile)
23 self.refreshConfig()
24
25 def openCommand(self,dest):
26 """
27 Specify the folder to opened by command line
28 """
29 path = str(dest)
30 path = path.replace("\\\\", "\\")
31 path = path.replace("/","\\")
32 cmd = "cmd /k cd \"" + path + "\""
33
34 import subprocess
35 subprocess.Popen(cmd, shell=True)
36
37 def openExplorer(self,dest):
38 """
39 Specify the folder to opened by Explorer
40 """
41 path = str(dest)
42 path = path.replace("\\\\", "\\")
43 path = path.replace("/","\\")
44 cmd = "explorer \"" + path + "\""
45 import subprocess
46 subprocess.Popen(cmd, shell=False)
47
48 def execFile(self,file):
49 """
50 execute the file by system register file type
51 """
52 if os.path.isfile(path):
53 try:
54 os.system(file)
55 except:
56 os.system("file:///" + str(file).replace("\\\\", "/"))
57 else:
58 openExplorer(file)
配置文件
[dirs]
path1 = D:\MyWork\HigoCMR
path2 = D:\MyCode\Python\Pratices
执行程序
执行程序代码 1 # -*- coding: utf-8 -*-
2
3 """
4 #**************************************************************
5 # Quick Position Tools for working directory
6 #
7 # Created by: wdong
8 # History: 2010-8-18 createdby wdong, define configItem
9 #**************************************************************
10 """
11
12 import os, sys
13 import ConfigParser
14 import operator
15 from PyQt4 import QtCore, QtGui
16
17 #。。。。(上边的代码片段)
18
19 if __name__ == '__main__':
20 app = QtGui.QApplication(sys.argv)
21 dialog = MyTray()
22 dialog.trayIcon.show()
23 sys.exit(app.exec_())
源码下载:Qp.rar
至此,完成该工具的第一个版本,待后续对Qt的使用熟悉以后,继续美化和加强该工具的功能,敬请期待...