- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
作为一名对 Python 几乎一无所知的 Pascal 程序员,我正在尝试利用 pyicloud https://github.com/picklepete/pyicloud/ 编写一个小而简单的 Python 脚本。每隔几秒通过 UDP 套接字重定向所有设备的位置数据 json,并提供所需的输出,如底部所示。python 脚本应该类似于:
from pyicloud import PyiCloudService
api = []
api.append(PyiCloudService('JAppleseedAppleIdEmailHere', 'password'))
api.append(PyiCloudService('SomeOtherAppleIdEmailHere', 'psadfsdfassword'))
# more accounts here if desired...
#PeerIp = '10.0.0.5'
PeerIp = '127.0.0.1'
PeerPort = 2028
import time, threading, socket, json, struct
ContinueDevicesPostionUpdate = True
def DevicesPostionUpdate():
if ContinueDevicesPostionUpdate:
# print(time.ctime())
threading.Timer(10, DevicesPostionUpdate).start()
# Code for generating json from api.devices and api.devices[].location()
# This is where i get all sort of errors in my shotgun programming
MESSAGE = bytes(smsg, 'utf-8')
sock.sendto(MESSAGE, (PeerIp, PeerPort))
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
DevicesPostionUpdate()
例如:
for k, v in api:
for key, value in api[k].devices.items():
print (api[k].devices[key].location())
#results in:
Exception in thread Thread-4:
Traceback (most recent call last):
File "C:\Python33\lib\threading.py", line 901, in _bootstrap_inner
self.run()
File "C:\Python33\lib\threading.py", line 1142, in run
self.function(*self.args, **self.kwargs)
File "test.py", line 17, in DevicesPostionUpdate
for k, v in api:
TypeError: 'PyiCloudService' object is not iterable
或者
MESSAGE = json.dumps([dict(device=device, location=device.location()) for a in api for device in a.devices.values()]).encode()
#results in:
Traceback (most recent call last):
File "test.py", line 23, in <module>
DevicesPostionUpdate()
File "test.py", line 17, in DevicesPostionUpdate
MESSAGE = json.dumps([dict(device=device, location=device.location()) for a in api for device in a.devices.values()]).encode()
File "C:\Python33\lib\json\__init__.py", line 236, in dumps
return _default_encoder.encode(obj)
File "C:\Python33\lib\json\encoder.py", line 191, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python33\lib\json\encoder.py", line 249, in iterencode
return _iterencode(o, 0)
File "C:\Python33\lib\json\encoder.py", line 173, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <AppleDevice(iPhone 4S: Johnny Appleseed's iPhone)> is not JSON serializable
所需的输出应该类似于:
{
{
u'i9vbKRGIcLYqJnXMd1b257kUWnoyEBcEh6yM+IfmiMLh7BmOpALS+w==': <AppleDevice(iPhone 4S: Johnny Appleseed's iPhone)>,
{
u'timeStamp': 1357753796553,
u'locationFinished': True,
u'longitude': -0.14189,
u'positionType': u'GPS',
u'locationType': None,
u'latitude': 51.501364,
u'isOld': False,
u'horizontalAccuracy': 5.0
}
}
,
{
u'reGYDh9XwqNWTGIhNBuEwP1ds0F/Lg5t/fxNbI4V939hhXawByErk+HYVNSUzmWV': <AppleDevice(MacBook Air 11": Johnny Appleseed's MacBook Air)>
{
u'timeStamp': 1357753796553,
u'locationFinished': True,
u'longitude': -0.14189,
u'positionType': u'GPS',
u'locationType': None,
u'latitude': 51.501364,
u'isOld': False,
u'horizontalAccuracy': 5.0
}
}
,
{
u'reGYDh9XwqNWTGIhNBuEwP1ds0F/Lg5t/fxNbI4V939hhXawByErk+HYVNSUzmWV': <AppleDevice(iPhone 4S: Some Other's iPhone)>
{
u'timeStamp': 1357753796553,
u'locationFinished': True,
u'longitude': -0.14189,
u'positionType': u'GPS',
u'locationType': None,
u'latitude': 51.501364,
u'isOld': False,
u'horizontalAccuracy': 5.0
}
}
}
如果您不想在这里帮助我,您可以通过在 freelancer.com 展示您的解决方案来赚取 30 美元。
最佳答案
没有什么比提出问题并在几个小时后自己得到答案更有趣的了。感谢您的帮助Totem
你是个天才J.F. Sebastian !
from pyicloud import PyiCloudService
api = []
api.append(PyiCloudService('JAppleseedAppleIdEmailHere', 'password'))
api.append(PyiCloudService('SomeOtherAppleIdEmailHere', 'psadfsdfassword'))
PeerIp = '127.0.0.1'
PeerPort = 2028
ThreadRunCount = -1
InfoEveryRunTime = 10
import time, threading, socket, json
def update_device_position():
smsg = '{\n'
global ThreadRunCount
ThreadRunCount += 1
MESSAGE = json.dumps([dict(device=str(device), location=device.location()) for a in api for device in a.devices.values()]).encode()
DevCount = 0
for a in api:
for key, value in a.devices.items():
DevCount += 1
sock.sendto(MESSAGE, (PeerIp, PeerPort))
tmst = time.strftime('%H:%M:%S')
if (ThreadRunCount % InfoEveryRunTime) == 0:
ThreadRunCount = 1
print('[' + tmst+ '] JSON of ' + str(len(MESSAGE)) +' bytes from ' + str(DevCount) + ' devices sent to ' + PeerIp + ':' + str(PeerPort))
# Internet # UDP
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
stopped = threading.Event()
while not stopped.wait(10):
update_device_position()
关于PYTHON for 循环通过 dict_keys 和 UDP 发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20456759/
>>> d = {'m': 'mango', 'f': 'fish', 'a': 'apple'} >>> d {'m': 'mango', 'f': 'fish', 'a': 'apple'} >>
我正在使用 Learn Python the Hard Way 来学习 Python,当我运行以下作为示例: import random from urllib.request import urlo
如何直接在 dict_keys 类上获取引用?目前我能找到的唯一方法是创建一个临时 dict 对象并对其进行类型检查。 >>> the_class = type({}.keys()) >>> the_
这个问题已经有答案了: How do I return dictionary keys as a list in Python? (13 个回答) 已关闭 5 年前。 当我这样做时: d = {'x'
我是 Python 的新手,我只是在练习和“复制”一些 github 代码。这样做的时候,我意识到我使用的是最新版本的 Python,而视频中的人使用的是 Python 2.7,所以他使用的代码与我的
我想弄清楚为什么在 Jinja2 中以下代码不起作用。我在 Jinja2 中设置字典的键这个字典只有一个键,我想访问键名但是在 Jinja2 中调用 tc_class_name 变量只返回以下 dic
我想弄清楚为什么在 Jinja2 中以下代码不起作用。我在 Jinja2 中设置字典的键这个字典只有一个键,我想访问键名但是在 Jinja2 中调用 tc_class_name 变量只返回以下 dic
我正在使用 Python 3,尽管转换为列表,但我似乎无法运行我的程序。 这是函数调用: path = euleriancycle(edges) 这就是我使用 keys 方法的地方: def eule
我在以下位置收到“dict_key object does not support indexing”错误消息: return len(G[G.keys()[0]]) 我意识到它曾经在 python
我正在尝试将字典列表转换为 lambda 函数的 csv 字符串。我在下面编写的代码将数据作为键值。我正在尝试重写它,以便它基于 dict_keys 工作。 import io import csv
我正在尝试通过索引访问 dict_key 的元素: test = {'foo': 'bar', 'hello': 'world'} keys = test.keys() # dict_keys ob
作为一名对 Python 几乎一无所知的 Pascal 程序员,我正在尝试利用 pyicloud https://github.com/picklepete/pyicloud/ 编写一个小而简单的 P
由于 dict.keys(以及 dict.items 和 dict.values 类似)返回字典对象的 View ,我假设删除生成它们的字典实际上会对我们从中获取它们的 dict_keys 产生影响。
我正在尝试使用一个名为 bidi 的 Python 包。在此包 (algorithm.py) 的模块中,有些行会给我错误,尽管它是包的一部分。 这是几行: _LEAST_GREATER_ODD = l
我在使用 collections.Counter 的 viewkeys()、viewitems() 和 viewvalues() 方法时遇到了这三种类型。 这三个方法返回的值是dict_keys、di
我正在尝试通过索引访问 dict_key 的元素: test = {'foo': 'bar', 'hello': 'world'} keys = test.keys() # dict_keys ob
def shuffle(self, x, random=None, int=int): """x, random=random.random -> shuffle list x in plac
dict = {'a':1, 'b':2} dict.keys 给出 dict_keys(['a', 'b']) dict.values 给出 dict_values([1, 2])。 有人可以举例说
在Python3中,我应该使用什么类型来检查字典键是否属于它? >>> d = {1 : 2} >>> type(d.keys()) 所以我很自然地尝试了这个: >>> isinstance(d.k
我在 Python 2.7.3 和 Python 3.2.3 中运行以下代码: test_dict = {'foo':'bar'} type(test_dict.keys()) 在 Python 2
我是一名优秀的程序员,十分优秀!