一半君的总结纸

听话只听一半君

from PyQt4.QtCore import * 自动转换script乱搞?

一般自己写简短的例子的时候,总是会

from PyQt4.QtCore import *
from PyQt4.QtGui import *

这样虽然省事(下面每次不用输入QtCore.xxx QtGui.xxx),但是这样一般来说是不太好的,最好是能

from PyQt4 import QtCore, QtGui

但是这样,下面每次敲命令的时候都要QtGui.xxx,很神烦,所以lz准备用中庸的方法,在写的时候还是用第一种import *的写法,最后完成前把他改成

from PyQt4.QtCore import Qt
from PyQt4.QtGui import QDialog, QPushButton

等等,用到哪些就把哪些全加上去,但有个脑残的地方是总不能运行一下,看哪里出错,就把哪个class的名字加上去,如果用到很多class的话,这样要累死了

脑残解法:

  • 使用python自带的2to3 lib里,自定义一个fixer(好像比较复杂)
  • 用regex搜索所有QXxx开头的字符串(好像很乱搞)
  • 创建AST,找到所有QXxx开头的变量名(这个似乎听起来合理一些)

先试试看起来最容易的方法2,lz用的测试文件是前几天给Maya script editor加快捷键的代码

import re
code = open('qtextedit_test_maya.py').read()
classes = re.findall('Q[A-Z][^\.\(\)]*',code)
classes = list(set(classes))
print classes

因为Qt的class名字全都是QXxx这样的,所以这样大概还算可以勉强蒙混过关?结果如下

['QTextCursor', 'QEvent', 'QObject']

下面还需要知道他们在QtCore还是QtGui里

from PyQt4 import QtCore,QtGui

QtCore_class = dir(QtCore)
QtGui_class = dir(QtGui)

core_class=[c for c in classes if c in QtCore_class]
gui_class=[c for c in classes if c in QtGui_class]

if core_class:
	print 'from PyQt4.QtCore import %s' % ', '.join(core_class)
if gui_class:
	print 'from PyQt4.QtGui import %s' % ', '.join(gui_class)

结果:

from PyQt4.QtCore import QEvent, QObject
from PyQt4.QtGui import QTextCursor

貌似很脑残,下面试试方法3:

import ast

code = open('qtextedit_test_maya.py').read()
root = ast.parse(code)
names = sorted({node.id for node in ast.walk(root) if isinstance(node, ast.Name)})

names = filter(lambda x: re.match('Q[A-Z][^\.\(\)]*',x),names)
names= list(set(names))
print names

为了使用方便,要么把这个做成个命令行工具,或者弄成sublime插件

待续…

参考:

Porting to Python 3 — A Guide
How to get all variable and method names used in script

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: