LoginSignup
0
1

More than 5 years have passed since last update.

cron,pythonで自動スピードテストを作成する

Last updated at Posted at 2017-12-04

いつもお世話になっております。

フリーランスエンジニアの永田です。

iOS,Androidは少しpython,php,も実施しています。デザインも勉強中です。

今回はプログラミングで通信レスポンスと実装スピードを自動で設定するロジックを紹介いたします。

環境

mac

corn

python3

が必要になります。各インストール方法は、割愛します。

詳細リンクは
https://github.com/daisukenagata/PythonFile

cronとは

お馴染みだと思いますが、Unix系OSにおいて、コマンドの定時実行のスケジュール管理を行うために用いられるコマンドであります。

crontab -eで編集を実施コマンドです。

分 時 日 月 曜日 コマンド
*  *  *  *  *  some_command

pythonで読める日本語がcronでは読めないので、この設定が必要になります。

import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

1分以内に自動スクリプトを呼び出す処理を記入しています。

*/1 * * * * /Users/nagatadaisuke/.pyenv/shims/python $HOME/PythonFile/postPython.py

編集が成功すると、ターミナルに表示される処理がこちらになります。

crontab: installing new crontab

cronの内容を確認するコマンドです。

crontab -l

cronが実行されると、表示されるメッセージがこちらで、catでcronの内容を確認できます。

You have new mail in /var/mail/nagatadaisuke
↓

cat /var/mail/nagatadaisuke

python3

pythonはとてもシンプルなコードで、できてしまいます。
大掛かりなツールは必要ないけど、自動でテストしたい場合など、
自分で自作しても良いかもしれませんね。

pythonの実装コード

time.time()を2回呼びその差分を出力するロジックです。

r = requests.get('URLSettings')のURLSettingsにURLを設定すると
レスポンス情報と、通信時間が計測できます。

import requests
import time
from datetime import datetime
# -*- coding: utf-8 -*-
import sys
import io

def main():
    #cron対応
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

    start = time.time()

    r = requests.get('https://github.com/daisukenagata/PythonFile/blob/master/postPython.py')

    elapsed_time =  time.time() - start
    text = datetime.now().strftime("%Y/%m/%d %H:%M:%S")+" "+"StatusCode"+str(r.status_code)+" "+"経過時間"+str(elapsed_time)+"\n"


    f = open('file.text', 'a')
    f.writelines(text)
    f.close()


if __name__=='__main__':
    main()

昼休憩中に作成させていただきました。
以上が紹介になります。github上では動くソースをアップデートしときました。

午後も作業頑張ります。よろしくお願い致します。
来年も宜しくお願い致します。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1