Re: [問題] os.popen有辦法將一個模組物件化 重複 …

看板Python作者 (無)時間16年前 (2009/04/11 03:24), 編輯推噓1(101)
留言2則, 2人參與, 最新討論串3/3 (看更多)
※ 引述《richtrf (嘉)》之銘言: : 很謝謝你的回應! : 不過可能我表達有些錯誤 : 我舉另外一個例子好了 : result=os.popen("echo 'query_name' | ./phonebook").read() : phonebook是用c寫的程式 : 每次執行他的時候 他都會開始載入背後的資料庫 : 如果我只是單次執行的話 : 像是query_name= "John" : 他就會回傳該人名的電話號碼 : 只不過他每次執行都需要重新載入電話號碼的資料庫 : 如果要執行多次的時候 就變成每次花時間重新載入 : 我的想法是有什麼辦法把result變成物件 : 下次再執行的時候 就不用再重新載入資料庫了? : 感謝感謝! 看來這個問題的解決目標是:如何不要讓phonebook每次執行讀入資料庫 有許多可能的解法,不過似乎都是要暫存到哪裡、哪個等級的問題 你可能會考慮: 把資料暫存於記憶體、檔案,或另一個更有效率的資料庫 並自己寫一個更有效率的query 因這個程式免不了的事就是 query data 所以可以改善效能的點大概是: 更有效率的query 更有效的data sctructure(可以想成更有效的database) 舉例而言 假設資料是從試算表檔讀出,把資料轉進database(如sqlite)應該可以提升不少效能 假設 query 是這麼讀入: def query_phonebook(query_name): users = database.get_all_users() # 先從資料庫讀出所有的 user for user in users: if user['name'] == query_name: # 再自己來比對 user 的資料 return user['phone_number'] return None 可以改讓 database 先做(較有效率的query)通常可得效率的改善: def query_phonebook(query_name): user = database.get_the_user(name=query_name) # 資料庫找到就傳回那個 user data if user: return user['phone_number'] return None 如果不能(或不想)改那個 c 語言的 phonebook 程式 可以考慮用 python 把資料存到 sqlite 然後做更有效的 query 若你想存像 [('john', 38389438), ('mary', 4949449), ...] 這樣的物件 你可能會考慮 python 的 pickle 模組 http://docs.python.org/library/pickle.html (註:它有用c寫的 cPickle,也就是 Pickle 的效能最佳化版,但因此有它使用上的限制 詳見 http://0rz.tw/8xxNM ) 但基本上它也是把資料寫入另一個檔案以便將來程式再次執行時讀入 假設你說的是連 query 的名字都一樣(雖然不是這樣吧) 那簡單解: Python 2.5.4 (r254:67917, Dec 23 2008, 14:57:27) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> def fake_phonebook(query_name): ... fake_result = 24681357 ... return fake_result ... >>> def get_user_number(): ... username = 'jack' ... try: ... f = open('cache_file', 'r') ... data = f.read() ... print 'just read the data from file' ... except IOError, e: ... f = open('cache_file', 'w') ... data = fake_phonebook(username) ... f.write(str(data)) ... print 'put result data into file' ... return data ... >>> get_user_number() put result data into file 24681357 >>> get_user_number() just read the data from file '24681357' 不知這樣子描述這個問題有沒有比較清楚?;) 關於 IO 亦可見 http://docs.python.org/tutorial/inputoutput.html : ※ 引述《keitheis (無)》之銘言: : : 這個問題有點模糊 : : 試著跑一次: : : Python 2.5.4 (r254:67917, Dec 23 2008, 14:57:27) : : In [1]: import os : : In [2]: c=os.popen("echo '1+1' | ./counter").read() : : In [3]: c : : Out[3]: '3\n' : : In [4]: type(c) : : Out[4]: <type 'str'> : : 不論 counter 幹了什麼,假設最後是輸出一個數 : : 那麼讀入該輸出的 c 已經是一個 (string) 物件 : : 如果程式的功能就是每次執行一次 counter : : 且 counter 的功能就是每次讀入最新的資料 : : 那問題大概就是怎麼把 counter 的程式最佳化了? -- keitheis ") -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 122.121.153.84 ※ 編輯: keitheis 來自: 122.121.153.84 (04/11 03:25)

04/11 05:40, , 1F
rrr... 第二次得到了 string, 應該要用 return int(data)
04/11 05:40, 1F

04/13 16:59, , 2F
真是感謝你阿 你的解說真是清楚又詳盡 真是太感激你了!
04/13 16:59, 2F
文章代碼(AID): #19tvpmcd (Python)
文章代碼(AID): #19tvpmcd (Python)