作者keitheis (无)
看板Python
标题Re: [问题] os.popen有办法将一个模组物件化 重复 …
时间Sat Apr 11 03:24:26 2009
※ 引述《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)
1F:→ keitheis:rrr... 第二次得到了 string, 应该要用 return int(data) 04/11 05:40
2F:推 richtrf:真是感谢你阿 你的解说真是清楚又详尽 真是太感激你了! 04/13 16:59