16

我在为 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

有谁知道如何解决这个问题?

4

4 回答 4

16

试试dir(iTunes)。它类似于vars,但更直接地用于对象。

于 2013-01-19T04:16:21.880 回答
9

对于类似于 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}
于 2015-07-05T02:59:46.267 回答
0

这来得很晚,但是对于不同的问题(但相同的错误),以下对我有用:

json.dumps(your_variable)

确保在此之前您已在脚本中导入 JSON。

import json

您将需要找到一种以干净格式读取 JSON 的方法。

于 2013-12-26T09:22:26.183 回答
0
def dump(obj):
    if hasattr(obj, '__dict__'): 
        return vars(obj) 
    else:
        return {attr: getattr(obj, attr, None) for attr in obj.__slots__} 

使用代替vars():)

于 2020-09-14T11:30:31.363 回答