2010-06-18 33 views
1

我需要從stdin中吸取數據並創建一個對象。Python訪問對象byref /需要標記

傳入的數據長度在5到10行之間。每行都有一個進程號和一個IP地址或一個哈希。 例如:

pid=123 ip=192.168.0.1 - some data 
pid=123 hash=ABCDEF- more data 
hash=ABCDEF123 - More data 
ip=192.168.0.1 - even more data 

我需要把這個數據放到一個類,如:

class MyData(): 
    pid = None 
    hash = None 
    ip = None 
    lines = [] 

我需要能夠通過IP,HASH,或PID查找的對象。

困難的部分是有多個數據流混合來自標準輸入。 (可能有數百或數千個進程同時寫入數據。)

我有拉出我需要的PID,IP和HASH的正則表達式,但是如何通過任何這些值訪問對象?

我的想法是做這樣的事情:

myarray = {} 

for each line in sys.stdin.readlines(): 
    if pid and ip: #If we can get a PID out of the line 
    myarray[pid] = MyData().pid = pid #Create a new MyData object, assign the PID, and stick it in myarray accessible by PID. 
    myarray[pid].ip = ip #Add the IP address to the new object 
    myarray[pid].lines.append(data) #Append the data 

    myarray[ip] = myarray[pid] #Take the object by PID and create a key from the IP. 
    <snip>do something similar for pid and hash, hash and ip, etc...</snip> 

這使我有兩個鍵(一個PID和IP),它們都指向同一個對象的數組。 但在循環的下一次迭代,如果我發現(例如)的IP和HASH做:

myarray[hash] = myarray[ip] 

以下是假:

myarray[hash] == myarray[ip] 

希望這是顯而易見的。 我討厭承認在VB日waaay回來,我記得能夠處理對象byref而不是byval。 Python中有類似的東西嗎?或者我剛剛接近這個錯誤?

回答

2

兩個單獨類型的字典(不叫他們陣!),byipbyhash - 爲什麼你需要smoosh都在一起和風險的衝突?

BTW,you't可能可以有以下兩行背靠背:

myarray[hash] = myarray[ip] 
assert not(myarray[hash] == myarray[ip]) 

爲了使assert抱着你必須做一些在別的之間(地干擾名不副實myarray)。

順便說一句,在Python中的任務總是通過引用一個對象 - 如果你想要一個副本,你必須明確地要求一個副本。

2

Python only has references。

創建一次對象,並將其一次添加到所有相關的鍵。

class MyData(object): 
    def __init__(self, pid, ip, hash): 
    self.pid = pid 
    ... 

for line in sys.stdin: 
    pid, ip, hash = process(line) 
    obj = MyData(pid=pid, ip=ip, hash=hash) 
    if pid: 
    mydict[pid] = obj 
    if ip: 
    mydict[ip] = obj 
    if hash: 
    mydict[hash] = obj 
+0

我無法一次添加全部。每次我經歷循環時,我都會得到不同的pid,ip和hash組合。每次通過循環時,我都知道我有什麼組合,並通過數組來查看對象。然後我將它與新發現的pid,ip或hash關聯起來。 例如,第一行可能只是一個pid。第二行可能是一個PID和散列。第三行可能是散列和ip。 似乎Python正在創建MyData的副本,例如我做了 mydict [ip] = mydict [hash]。 如果我然後做mydict [hash] .blah = 1,那麼mydict [ip]不會改變。 – 2010-06-19 03:41:16

+0

這就是爲什麼'process()'返回它沒有的位的None。不,它不會複製。 – 2010-06-19 07:02:03