Jump to content
新域网络技术论坛

Search the Community

Showing results for tags 'Python'.



More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • 论坛服务
    • 公告栏
  • 技术讨论
    • IPB相关讨论
    • PHP技术探讨
    • FREEBSD讨论
    • 其它技术
    • 软件分享
  • 业余无线电
    • 使用指南
    • 设备讨论

Blogs

There are no results to display.

Product Groups

There are no results to display.


Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


位置


兴趣


呼号

Found 4 results

  1. apache中有ab压力测试工具,但是无法自定义参数,并且无法分析最终结果,特写此文,共勉之。 我们先在服务端创建一个有10%概率成功的PHP脚本,由于高并发使用默认的随机数算法可能有些问题,所以采用了自定义的随机数种子算法。这里接收id用以区分请求顺序号。 $rate = 10; $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '0'; $seed = sRandSeed(); mt_srand($seed); if (mt_rand(1, 100) <= $rate) { $code = 0; $msg = 'success'; } else { $code = 1; $msg = 'busy'; } header('Content-type: application/json'); echo json_encode(['code' => $code, 'msg' => $msg, 'id' => $id, 'seed' => $seed,]); function sRandSeed() { $hash = md5(session_create_id()); $result = 0x003F; foreach (str_split($hash, 8) as $v) { $result ^= hexdec($v); } return $result & 0x7FFFFFFF; } 由于windows最大同时打开文件只能是512个,我这里限制最大并发数为500了,如果非windows可以适当增加此值,否则会报错,无法执行下去。由于高并发的时候,有可能http服务会报错,如果返回的值不是标准json串,设置此次请求为失效(code = -1),并统计各code的数量。 # -*- Coding: UTF-8 -*- import time import sys import getopt import asyncio from aiohttp import ClientSession import json import codecs sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach()) url = "http://192.168.0.200/cli/asynctest.php" tasks = [] result = {} async def run(cid=0, obj=None): global cols if obj is None: obj = asyncio.Semaphore(cols) async with obj: async with ClientSession() as session: async with session.post(url, data={"id": cid}) as response: try: text = await response.text() j = json.loads(text) except json.JSONDecodeError: if -1 not in result: result[-1] = 0 result[-1] += 1 else: if j["code"] not in result: result[j["code"]] = 0 result[j["code"]] += 1 # print(j) if __name__ == "__main__": nums = 10 cols = 500 if len(sys.argv) > 1: opts, args = getopt.getopt(sys.argv[1:], "hn:c:") for op, value in opts: if op == "-h": print("python " + sys.argv[0] + " -n 100 -c 500") sys.exit() elif op == "-n": nums = int(value) elif op == '-c': cols = int(value) loop = asyncio.get_event_loop() start_time = time.time() semaphore = asyncio.Semaphore(cols) tasks = [run(cid, semaphore) for cid in range(nums)] loop.run_until_complete(asyncio.wait(tasks)) loop.close() end_time = time.time() print(result) print("Loop Nums:", str(nums)) print("Start Time:", str(start_time)) print("End Time:", str(end_time)) print("Running Time:", str(end_time - start_time))
  2. 一个简单的封装,自行安装hashlib,hashlib中有一些函数定义的,但实际使用起来比较麻烦,特意用这个来尝试使用Class封装一下。 封装文件:tools.py # -*- Coding: UTF-8 -*- import hashlib class tools: def md5(self, str): return hashlib.md5(str).hexdigest() def sha1(self, str): return hashlib.sha1(str).hexdigest() def sha512(self, str): return hashlib.sha512(str).hexdigest() if __name__ == '__main__': t = tools() print t.md5('admin') 正常情况,我们可以在命令行测试一下:python tools.py 会显示'admin'的MD5值,简单封装完成了,调用吧 调用文件demo.py #!/usr/local/bin/python # -*- Coding: UTF-8 -*- import sys from tools import * str = 'admin' if len(sys.argv)>1: str = "" for i in range(1, len(sys.argv)): str += sys.argv[i]+' ' t = tools() print('Str: %s,Md5: %s' % (str, t.md5(str))) print('Str: %s,Sha1: %s' % (str, t.sha1(str))) print('Str: %s,sha512: %s' % (str, t.sha512(str)))
  3. 由于系统没字体,所以没使用中文的title # -*- coding: UTF-8 -*- import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties x = [[0], [1], [2]] y = [[0], [1], [2]] if ((x[0][0] == x[1][0] and x[0][0] == x[2][0]) or (y[0][0] == y[1][0] and y[0][0] == y[2][0]) or ((x[0][0]-x[1][0])/(y[0][0]-y[1][0]) == (x[0][0]-x[2][0])/(y[0][0]-y[2][0]))): online = True else: online = False #title = u'三点是否在一条直线上?:'+str(online) title = 'Is the three point in a straight line? '+str(online) plt.figure() plt.title(title) plt.xlabel('x') plt.ylabel('y') plt.axis([-2, 10, -2, 10]) plt.grid(True) plt.plot(x, y, 'k.') plt.plot(x, y, 'g-') plt.show()
  4. python里有个结巴分词工具,看着还不错,我们PHP上能够尝试用它么? 先来分词py脚本 : # -*- coding: UTF-8 -*- import sys import jieba import json str = "" for i in range(1, len(sys.argv)): str += sys.argv[i]+' ' if (str == ""): str = "他来到了网易杭研大厦" t = "jieba V"+jieba.__version__ out = {"TITLE":t} seg_list = jieba.cut(str, cut_all=True) #print("Full Mode: " + "/ ".join(seg_list)) # 全模式 out['FULL'] = "||".join(seg_list) seg_list = jieba.cut(str, cut_all=False) #print("Default Mode: " + "/ ".join(seg_list)) # 精确模式 out['DEF'] = "||".join(seg_list) #seg_list = jieba.cut(str) # 默认是精确模式 #print(", ".join(seg_list)) seg_list = jieba.cut_for_search(str) # 搜索引擎模式 #print(", ".join(seg_list)) out['SEARCH'] = "||".join(seg_list) print json.dumps(out) 再来PHP脚本: <?php //路径请自行定义 $script = '/usr/local/www/apache24/data/py/tst.py'; $str = "我家住在黄土高坡"; if (isset($_REQUEST['str'])) $str = $_REQUEST['str']; header('Content-Type:application/json;charset:UTF-8'); system("python {$script} {$str}"); 现在只有一个问题,运行速度有点慢,同样的文字,python端只需要0.2秒,但PHP请求需要2-3秒。。看样子后续还是要改成直接用python返回相应请求。
×
×
  • Create New...