我遇到了python脚本桥的问题
我正在尝试列出iTunes对象的属性
iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
使用
>>> from pprint import pprint
>>> from Foundation import *
>>> from ScriptingBridge import *
>>> iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
>>> pprint (vars(iTunes))
我回来了
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: vars() argument must have __dict__ attribute
任何人都知道如何解决这个问题?
答案 0 :(得分:7)
试试dir(iTunes)
。它与vars
类似,但更直接与对象一起使用。
答案 1 :(得分:3)
类似于vars(obj),当obj无法作为dict访问时,我使用这样的kludge:
>>> obj = open('/tmp/test.tmp')
>>> print vars(obj)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: vars() argument must have __dict__ attribute
>>> print dict([attr, getattr(obj, attr)] for attr in dir(obj) if not attr.startswith('_'))
{'softspace': 0, 'encoding': None, 'flush': <built-in method flush of file object at 0xf7472b20>, 'readlines': <built-in method readlines of file object at 0xf7472b20>, 'xreadlines': <built-in method xreadlines of file object at 0xf7472b20>, 'close': <built-in method close of file object at 0xf7472b20>, 'seek': <built-in method seek of file object at 0xf7472b20>, 'newlines': None, 'errors': None, 'readinto': <built-in method readinto of file object at 0xf7472b20>, 'next': <method-wrapper 'next' of file object at 0xf7472b20>, 'write': <built-in method write of file object at 0xf7472b20>, 'closed': False, 'tell': <built-in method tell of file object at 0xf7472b20>, 'isatty': <built-in method isatty of file object at 0xf7472b20>, 'truncate': <built-in method truncate of file object at 0xf7472b20>, 'read': <built-in method read of file object at 0xf7472b20>, 'readline': <built-in method readline of file object at 0xf7472b20>, 'fileno': <built-in method fileno of file object at 0xf7472b20>, 'writelines': <built-in method writelines of file object at 0xf7472b20>, 'name': '/tmp/test.tmp', 'mode': 'r'}
我确信可以对其进行改进,例如使用if not callable(getattr(obj, attr)
过滤掉函数:
>>> print dict([attr, getattr(obj, attr)] for attr in dir(obj) if not attr.startswith('_') and not callable(getattr(obj, attr)))
{'errors': None, 'name': '/tmp/test.tmp', 'encoding': None, 'softspace': 0, 'mode': 'r', 'closed': False, 'newlines': None}
答案 2 :(得分:2)
这很晚了,但是对于另一个问题(但同样的错误),以下内容对我有用:
json.dumps(your_variable)
确保在此之前已在脚本中导入JSON。
import json
您需要找到一种以干净的格式阅读JSON的方法。
答案 3 :(得分:0)
def dump(obj):
if hasattr(obj, '__dict__'):
return vars(obj)
else:
return {attr: getattr(obj, attr, None) for attr in obj.__slots__}
使用而不是vars()
:)