2013-12-08 66 views
1

作爲一個Pascal程序員,幾乎沒有關於Python的線索我正在嘗試編寫一個小而簡單的Python腳本,利用pyicloud https://github.com/picklepete/pyicloud/重定向所有設備的位置數據json每隔幾秒鐘通過具有所需輸出的UDP套接字,如底部所示。 的Python腳本應該是這樣的:PYTHON循環通過dict_keys和UDP發送

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 
     } 
    } 
} 

如果你不想幫我在這裏,你總是可以賺到$ 30憑你的解決方案在freelancer.com

回答

2

沒有什麼比問幾個小時問自己幾個小時後回答問題更有趣了。謝謝你的幫助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() 
+0

嘗試'MESSAGE = json.dumps([dict(device = device,location = device.location())爲a.devices.values()]中的設備的api)。encode()'If' device' '.location()'不是json可編碼的,然後將它們首先轉換爲可執行的類型(例如'str')。 – jfs

+0

您是否嘗試了一個簡單的while循環而不是線程:'while not stopped.wait(10):update_device_position()'where stopped = threading.Event()'從控制線程傳遞。或者你可以[使用事件循環,重複運行一個函數](http://stackoverflow.com/a/14040516/4279) – jfs

+0

查看MESSAGE = json.dumps([dict(device = device, ()))。)encode() 如何不等於停止。等待(10)等等工作相比threading.Timer() 10,DevicesPostionUpdate).start()解決方案,即有什麼不同? – wittrup

0

你似乎是使用python 3. .iteritems()方法類型的字典不再存在,它是由.items()取代。嘗試替換它,看看是否有幫助。

+0

它有助於一些。然而,只是遇到新的問題:D – wittrup

+0

有什麼新問題? – Totem

+0

查看更新問題。 – wittrup