figure:last-child { margin-bottom: 0.5rem; }
#write ol, #write ul { position: relative; }
img { max-width: 100%; vertical-align: middle; }
button, input, select, textarea { color: inherit; font: inherit; }
input[type="checkbox"], input[type="radio"] { line-height: normal; padding: 0px; }
*, ::after, ::before { box-sizing: border-box; }
#write h1, #write h2, #write h3, #write h4, #write h5, #write h6, #write p, #write pre { width: inherit; }
#write h1, #write h2, #write h3, #write h4, #write h5, #write h6, #write p { position: relative; }
p { line-height: inherit; }
h1, h2, h3, h4, h5, h6 { break-after: avoid-page; break-inside: avoid; orphans: 2; }
p { orphans: 4; }
h1 { font-size: 2rem; }
h2 { font-size: 1.8rem; }
h3 { font-size: 1.6rem; }
h4 { font-size: 1.4rem; }
h5 { font-size: 1.2rem; }
h6 { font-size: 1rem; }
.md-math-block, .md-rawblock, h1, h2, h3, h4, h5, h6, p { margin-top: 1rem; margin-bottom: 1rem; }
.hidden { display: none; }
.md-blockmeta { color: rgb(204, 204, 204); font-weight: 700; font-style: italic; }
a { cursor: pointer; }
sup.md-footnote { padding: 2px 4px; background-color: rgba(238, 238, 238, 0.7); color: rgb(85, 85, 85); border-radius: 4px; cursor: pointer; }
sup.md-footnote a, sup.md-footnote a:hover { color: inherit; text-transform: inherit; text-decoration: inherit; }
#write input[type="checkbox"] { cursor: pointer; width: inherit; height: inherit; }
figure { overflow-x: auto; margin: 1.2em 0px; max-width: calc(100% + 16px); padding: 0px; }
figure > table { margin: 0px !important; }
tr { break-inside: avoid; break-after: auto; }
thead { display: table-header-group; }
table { border-collapse: collapse; border-spacing: 0px; width: 100%; overflow: auto; break-inside: auto; text-align: left; }
table.md-table td { min-width: 32px; }
.CodeMirror-gutters { border-right: 0px; background-color: inherit; }
.CodeMirror-linenumber { user-select: none; }
.CodeMirror { text-align: left; }
.CodeMirror-placeholder { opacity: 0.3; }
.CodeMirror pre { padding: 0px 4px; }
.CodeMirror-lines { padding: 0px; }
div.hr:focus { cursor: none; }
#write pre { white-space: pre-wrap; }
#write.fences-no-line-wrapping pre { white-space: pre; }
#write pre.ty-contain-cm { white-space: normal; }
.CodeMirror-gutters { margin-right: 4px; }
.md-fences { font-size: 0.9rem; display: block; break-inside: avoid; text-align: left; overflow: visible; white-space: pre; background: inherit; position: relative !important; }
.md-diagram-panel { width: 100%; margin-top: 10px; text-align: center; padding-top: 0px; padding-bottom: 8px; overflow-x: auto; }
#write .md-fences.mock-cm { white-space: pre-wrap; }
.md-fences.md-fences-with-lineno { padding-left: 0px; }
#write.fences-no-line-wrapping .md-fences.mock-cm { white-space: pre; overflow-x: auto; }
.md-fences.mock-cm.md-fences-with-lineno { padding-left: 8px; }
.CodeMirror-line, twitterwidget { break-inside: avoid; }
.footnotes { opacity: 0.8; font-size: 0.9rem; margin-top: 1em; margin-bottom: 1em; }
.footnotes + .footnotes { margin-top: 0px; }
.md-reset { margin: 0px; padding: 0px; border: 0px; outline: 0px; vertical-align: top; background: 0px 0px; text-decoration: none; text-shadow: none; float: none; position: static; width: auto; height: auto; white-space: nowrap; cursor: inherit; -webkit-tap-highlight-color: transparent; line-height: normal; font-weight: 400; text-align: left; box-sizing: content-box; direction: ltr; }
li div { padding-top: 0px; }
blockquote { margin: 1rem 0px; }
li .mathjax-block, li p { margin: 0.5rem 0px; }
li { margin: 0px; position: relative; }
blockquote > :last-child { margin-bottom: 0px; }
blockquote > :first-child, li > :first-child { margin-top: 0px; }
.footnotes-area { color: rgb(136, 136, 136); margin-top: 0.714rem; padding-bottom: 0.143rem; white-space: normal; }
#write .footnote-line { white-space: pre-wrap; }
@media print {
body, html { border: 1px solid transparent; height: 99%; break-after: avoid; break-before: avoid; }
#write { margin-top: 0px; padding-top: 0px; border-color: transparent !important; }
.typora-export * { -webkit-print-color-adjust: exact; }
html.blink-to-pdf { font-size: 13px; }
.typora-export #write { padding-left: 32px; padding-right: 32px; padding-bottom: 0px; break-after: avoid; }
.typora-export #write::after { height: 0px; }
}
.footnote-line { margin-top: 0.714em; font-size: 0.7em; }
a img, img a { cursor: pointer; }
pre.md-meta-block { font-size: 0.8rem; min-height: 0.8rem; white-space: pre-wrap; background: rgb(204, 204, 204); display: block; overflow-x: hidden; }
p > .md-image:only-child:not(.md-img-error) img, p > img:only-child { display: block; margin: auto; }
p > .md-image:only-child { display: inline-block; width: 100%; }
#write .MathJax_Display { margin: 0.8em 0px 0px; }
.md-math-block { width: 100%; }
.md-math-block:not(:empty)::after { display: none; }
[contenteditable="true"]:active, [contenteditable="true"]:focus { outline: 0px; box-shadow: none; }
.md-task-list-item { position: relative; list-style-type: none; }
.task-list-item.md-task-list-item { padding-left: 0px; }
.md-task-list-item > input { position: absolute; top: 0px; left: 0px; margin-left: -1.2em; margin-top: calc(1em - 10px); border: none; }
.math { font-size: 1rem; }
.md-toc { min-height: 3.58rem; position: relative; font-size: 0.9rem; border-radius: 10px; }
.md-toc-content { position: relative; margin-left: 0px; }
.md-toc-content::after, .md-toc::after { display: none; }
.md-toc-item { display: block; color: rgb(65, 131, 196); }
.md-toc-item a { text-decoration: none; }
.md-toc-inner:hover { text-decoration: underline; }
.md-toc-inner { display: inline-block; cursor: pointer; }
.md-toc-h1 .md-toc-inner { margin-left: 0px; font-weight: 700; }
.md-toc-h2 .md-toc-inner { margin-left: 2em; }
.md-toc-h3 .md-toc-inner { margin-left: 4em; }
.md-toc-h4 .md-toc-inner { margin-left: 6em; }
.md-toc-h5 .md-toc-inner { margin-left: 8em; }
.md-toc-h6 .md-toc-inner { margin-left: 10em; }
@media screen and (max-width: 48em) {
.md-toc-h3 .md-toc-inner { margin-left: 3.5em; }
.md-toc-h4 .md-toc-inner { margin-left: 5em; }
.md-toc-h5 .md-toc-inner { margin-left: 6.5em; }
.md-toc-h6 .md-toc-inner { margin-left: 8em; }
}
a.md-toc-inner { font-size: inherit; font-style: inherit; font-weight: inherit; line-height: inherit; }
.footnote-line a:not(.reversefootnote) { color: inherit; }
.md-attr { display: none; }
.md-fn-count::after { content: "."; }
code, pre, samp, tt { font-family: var(--monospace); }
kbd { margin: 0px 0.1em; padding: 0.1em 0.6em; font-size: 0.8em; color: rgb(36, 39, 41); background: rgb(255, 255, 255); border: 1px solid rgb(173, 179, 185); border-radius: 3px; box-shadow: rgba(12, 13, 14, 0.2) 0px 1px 0px, rgb(255, 255, 255) 0px 0px 0px 2px inset; white-space: nowrap; vertical-align: middle; }
.md-comment { color: rgb(162, 127, 3); opacity: 0.8; font-family: var(--monospace); }
code { text-align: left; vertical-align: initial; }
a.md-print-anchor { white-space: pre !important; border-width: initial !important; border-style: none !important; border-color: initial !important; display: inline-block !important; position: absolute !important; width: 1px !important; right: 0px !important; outline: 0px !important; background: 0px 0px !important; text-decoration: initial !important; text-shadow: initial !important; }
.md-inline-math .MathJax_SVG .noError { display: none !important; }
.html-for-mac .inline-math-svg .MathJax_SVG { vertical-align: 0.2px; }
.md-math-block .MathJax_SVG_Display { text-align: center; margin: 0px; position: relative; text-indent: 0px; max-width: none; max-height: none; min-height: 0px; min-width: 100%; width: auto; overflow-y: hidden; display: block !important; }
.MathJax_SVG_Display, .md-inline-math .MathJax_SVG_Display { width: auto; margin: inherit; display: inline-block !important; }
.MathJax_SVG .MJX-monospace { font-family: var(--monospace); }
.MathJax_SVG .MJX-sans-serif { font-family: sans-serif; }
.MathJax_SVG { display: inline; font-style: normal; font-weight: 400; line-height: normal; zoom: 90%; text-indent: 0px; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; overflow-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0px; min-height: 0px; border: 0px; padding: 0px; margin: 0px; }
.MathJax_SVG * { transition: none 0s ease 0s; }
.MathJax_SVG_Display svg { vertical-align: middle !important; margin-bottom: 0px !important; margin-top: 0px !important; }
.os-windows.monocolor-emoji .md-emoji { font-family: "Segoe UI Symbol", sans-serif; }
.md-diagram-panel > svg { max-width: 100%; }
[lang="mermaid"] svg, [lang="flow"] svg { max-width: 100%; height: auto; }
[lang="mermaid"] .node text { font-size: 1rem; }
table tr th { border-bottom: 0px; }
video { max-width: 100%; display: block; margin: 0px auto; }
iframe { max-width: 100%; width: 100%; border: none; }
.highlight td, .highlight tr { border: 0px; }

.CodeMirror { height: auto; }
.CodeMirror.cm-s-inner { background: inherit; }
.CodeMirror-scroll { overflow: auto hidden; z-index: 3; }
.CodeMirror-gutter-filler, .CodeMirror-scrollbar-filler { background-color: rgb(255, 255, 255); }
.CodeMirror-gutters { border-right: 1px solid rgb(221, 221, 221); background: inherit; white-space: nowrap; }
.CodeMirror-linenumber { padding: 0px 3px 0px 5px; text-align: right; color: rgb(153, 153, 153); }
.cm-s-inner .cm-keyword { color: rgb(119, 0, 136); }
.cm-s-inner .cm-atom, .cm-s-inner.cm-atom { color: rgb(34, 17, 153); }
.cm-s-inner .cm-number { color: rgb(17, 102, 68); }
.cm-s-inner .cm-def { color: rgb(0, 0, 255); }
.cm-s-inner .cm-variable { color: rgb(0, 0, 0); }
.cm-s-inner .cm-variable-2 { color: rgb(0, 85, 170); }
.cm-s-inner .cm-variable-3 { color: rgb(0, 136, 85); }
.cm-s-inner .cm-string { color: rgb(170, 17, 17); }
.cm-s-inner .cm-property { color: rgb(0, 0, 0); }
.cm-s-inner .cm-operator { color: rgb(152, 26, 26); }
.cm-s-inner .cm-comment, .cm-s-inner.cm-comment { color: rgb(170, 85, 0); }
.cm-s-inner .cm-string-2 { color: rgb(255, 85, 0); }
.cm-s-inner .cm-meta { color: rgb(85, 85, 85); }
.cm-s-inner .cm-qualifier { color: rgb(85, 85, 85); }
.cm-s-inner .cm-builtin { color: rgb(51, 0, 170); }
.cm-s-inner .cm-bracket { color: rgb(153, 153, 119); }
.cm-s-inner .cm-tag { color: rgb(17, 119, 0); }
.cm-s-inner .cm-attribute { color: rgb(0, 0, 204); }
.cm-s-inner .cm-header, .cm-s-inner.cm-header { color: rgb(0, 0, 255); }
.cm-s-inner .cm-quote, .cm-s-inner.cm-quote { color: rgb(0, 153, 0); }
.cm-s-inner .cm-hr, .cm-s-inner.cm-hr { color: rgb(153, 153, 153); }
.cm-s-inner .cm-link, .cm-s-inner.cm-link { color: rgb(0, 0, 204); }
.cm-negative { color: rgb(221, 68, 68); }
.cm-positive { color: rgb(34, 153, 34); }
.cm-header, .cm-strong { font-weight: 700; }
.cm-del { text-decoration: line-through; }
.cm-em { font-style: italic; }
.cm-link { text-decoration: underline; }
.cm-error { color: red; }
.cm-invalidchar { color: red; }
.cm-constant { color: rgb(38, 139, 210); }
.cm-defined { color: rgb(181, 137, 0); }
div.CodeMirror span.CodeMirror-matchingbracket { color: rgb(0, 255, 0); }
div.CodeMirror span.CodeMirror-nonmatchingbracket { color: rgb(255, 34, 34); }
.cm-s-inner .CodeMirror-activeline-background { background: inherit; }
.CodeMirror { position: relative; overflow: hidden; }
.CodeMirror-scroll { height: 100%; outline: 0px; position: relative; box-sizing: content-box; background: inherit; }
.CodeMirror-sizer { position: relative; }
.CodeMirror-gutter-filler, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-vscrollbar { position: absolute; z-index: 6; display: none; }
.CodeMirror-vscrollbar { right: 0px; top: 0px; overflow: hidden; }
.CodeMirror-hscrollbar { bottom: 0px; left: 0px; overflow: hidden; }
.CodeMirror-scrollbar-filler { right: 0px; bottom: 0px; }
.CodeMirror-gutter-filler { left: 0px; bottom: 0px; }
.CodeMirror-gutters { position: absolute; left: 0px; top: 0px; padding-bottom: 30px; z-index: 3; }
.CodeMirror-gutter { white-space: normal; height: 100%; box-sizing: content-box; padding-bottom: 30px; margin-bottom: -32px; display: inline-block; }
.CodeMirror-gutter-wrapper { position: absolute; z-index: 4; background: 0px 0px !important; border: none !important; }
.CodeMirror-gutter-background { position: absolute; top: 0px; bottom: 0px; z-index: 4; }
.CodeMirror-gutter-elt { position: absolute; cursor: default; z-index: 4; }
.CodeMirror-lines { cursor: text; }
.CodeMirror pre { border-radius: 0px; border-width: 0px; background: 0px 0px; font-family: inherit; font-size: inherit; margin: 0px; white-space: pre; overflow-wrap: normal; color: inherit; z-index: 2; position: relative; overflow: visible; }
.CodeMirror-wrap pre { overflow-wrap: break-word; white-space: pre-wrap; word-break: normal; }
.CodeMirror-code pre { border-right: 30px solid transparent; width: fit-content; }
.CodeMirror-wrap .CodeMirror-code pre { border-right: none; width: auto; }
.CodeMirror-linebackground { position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px; z-index: 0; }
.CodeMirror-linewidget { position: relative; z-index: 2; overflow: auto; }
.CodeMirror-wrap .CodeMirror-scroll { overflow-x: hidden; }
.CodeMirror-measure { position: absolute; width: 100%; height: 0px; overflow: hidden; visibility: hidden; }
.CodeMirror-measure pre { position: static; }
.CodeMirror div.CodeMirror-cursor { position: absolute; visibility: hidden; border-right: none; width: 0px; }
.CodeMirror div.CodeMirror-cursor { visibility: hidden; }
.CodeMirror-focused div.CodeMirror-cursor { visibility: inherit; }
.cm-searching { background: rgba(255, 255, 0, 0.4); }
@media print {
.CodeMirror div.CodeMirror-cursor { visibility: hidden; }
}

:root { --side-bar-bg-color: #fafafa; --control-text-color: #777; }
html { font-size: 16px; }
body { font-family: "Open Sans", "Clear Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; color: rgb(51, 51, 51); line-height: 1.6; }
#write { max-width: 860px; margin: 0px auto; padding: 30px 30px 100px; }
#write > ul:first-child, #write > ol:first-child { margin-top: 30px; }
a { color: rgb(65, 131, 196); }
h1, h2, h3, h4, h5, h6 { position: relative; margin-top: 1rem; margin-bottom: 1rem; font-weight: bold; line-height: 1.4; cursor: text; }
h1:hover a.anchor, h2:hover a.anchor, h3:hover a.anchor, h4:hover a.anchor, h5:hover a.anchor, h6:hover a.anchor { text-decoration: none; }
h1 tt, h1 code { font-size: inherit; }
h2 tt, h2 code { font-size: inherit; }
h3 tt, h3 code { font-size: inherit; }
h4 tt, h4 code { font-size: inherit; }
h5 tt, h5 code { font-size: inherit; }
h6 tt, h6 code { font-size: inherit; }
h1 { padding-bottom: 0.3em; font-size: 2.25em; line-height: 1.2; border-bottom: 1px solid rgb(238, 238, 238); }
h2 { padding-bottom: 0.3em; font-size: 1.75em; line-height: 1.225; border-bottom: 1px solid rgb(238, 238, 238); }
h3 { font-size: 1.5em; line-height: 1.43; }
h4 { font-size: 1.25em; }
h5 { font-size: 1em; }
h6 { font-size: 1em; color: rgb(119, 119, 119); }
p, blockquote, ul, ol, dl, table { margin: 0.8em 0px; }
li > ol, li > ul { margin: 0px; }
hr { height: 2px; padding: 0px; margin: 16px 0px; background-color: rgb(231, 231, 231); border: 0px none; overflow: hidden; box-sizing: content-box; }
li p.first { display: inline-block; }
ul, ol { padding-left: 30px; }
ul:first-child, ol:first-child { margin-top: 0px; }
ul:last-child, ol:last-child { margin-bottom: 0px; }
blockquote { border-left: 4px solid rgb(223, 226, 229); padding: 0px 15px; color: rgb(119, 119, 119); }
blockquote blockquote { padding-right: 0px; }
table { padding: 0px; word-break: initial; }
table tr { border-top: 1px solid rgb(223, 226, 229); margin: 0px; padding: 0px; }
table tr:nth-child(2n), thead { background-color: rgb(248, 248, 248); }
table tr th { font-weight: bold; border-width: 1px 1px 0px; border-top-style: solid; border-right-style: solid; border-left-style: solid; border-top-color: rgb(223, 226, 229); border-right-color: rgb(223, 226, 229); border-left-color: rgb(223, 226, 229); border-image: initial; border-bottom-style: initial; border-bottom-color: initial; margin: 0px; padding: 6px 13px; }
table tr td { border: 1px solid rgb(223, 226, 229); margin: 0px; padding: 6px 13px; }
table tr th:first-child, table tr td:first-child { margin-top: 0px; }
table tr th:last-child, table tr td:last-child { margin-bottom: 0px; }
.CodeMirror-lines { padding-left: 4px; }
.code-tooltip { box-shadow: rgba(0, 28, 36, 0.3) 0px 1px 1px 0px; border-top: 1px solid rgb(238, 242, 242); }
.md-fences, code, tt { border: 1px solid rgb(231, 234, 237); background-color: rgb(248, 248, 248); border-radius: 3px; padding: 2px 4px 0px; font-size: 0.9em; }
code { background-color: rgb(243, 244, 244); padding: 0px 2px; }
.md-fences { margin-bottom: 15px; margin-top: 15px; padding-top: 8px; padding-bottom: 6px; }
.md-task-list-item > input { margin-left: -1.3em; }
@media print {
html { font-size: 13px; }
table, pre { break-inside: avoid; }
pre { overflow-wrap: break-word; }
}
.md-fences { background-color: rgb(248, 248, 248); }
#write pre.md-meta-block { padding: 1rem; font-size: 85%; line-height: 1.45; background-color: rgb(247, 247, 247); border: 0px; border-radius: 3px; color: rgb(119, 119, 119); margin-top: 0px !important; }
.mathjax-block > .code-tooltip { bottom: 0.375rem; }
.md-mathjax-midline { background: rgb(250, 250, 250); }
#write > h3.md-focus::before { left: -1.5625rem; top: 0.375rem; }
#write > h4.md-focus::before { left: -1.5625rem; top: 0.285714rem; }
#write > h5.md-focus::before { left: -1.5625rem; top: 0.285714rem; }
#write > h6.md-focus::before { left: -1.5625rem; top: 0.285714rem; }
.md-image > .md-meta { border-radius: 3px; padding: 2px 0px 0px 4px; font-size: 0.9em; color: inherit; }
.md-tag { color: rgb(167, 167, 167); opacity: 1; }
.md-toc { margin-top: 20px; padding-bottom: 20px; }
.sidebar-tabs { border-bottom: none; }
#typora-quick-open { border: 1px solid rgb(221, 221, 221); background-color: rgb(248, 248, 248); }
#typora-quick-open-item { background-color: rgb(250, 250, 250); border-color: rgb(254, 254, 254) rgb(229, 229, 229) rgb(229, 229, 229) rgb(238, 238, 238); border-style: solid; border-width: 1px; }
.on-focus-mode blockquote { border-left-color: rgba(85, 85, 85, 0.12); }
header, .context-menu, .megamenu-content, footer { font-family: "Segoe UI", Arial, sans-serif; }
.file-node-content:hover .file-node-icon, .file-node-content:hover .file-node-open-state { visibility: visible; }
.mac-seamless-mode #typora-sidebar { background-color: var(--side-bar-bg-color); }
.md-lang { color: rgb(180, 101, 77); }
.html-for-mac .context-menu { --item-hover-bg-color: #E6F0FE; }
#md-notification .btn { border: 0px; }
.dropdown-menu .divider { border-color: rgb(229, 229, 229); }
.ty-preferences .window-content { background-color: rgb(250, 250, 250); }
.ty-preferences .nav-group-item.active { color: white; background: rgb(153, 153, 153); }
-->

定时ping取返回值并绘图

  前些天一个朋友有要ping交易所前置以及绘制成折线图的需求,帮忙做了两天,感慨颇多,故写篇博客记录一下.

实际需求

  首先,我们的需求是,在window或者linux机器上定时执行ping + 网址 的语句,最终取到平均延迟,然后将这些延迟绘制成折线图.所以分析下来我们需要以下几个模块来实现这个功能.

需求分析

定时功能:

  datetime模块

用window机器远程控制linux机器,并发送指令:

  paramiko模块

绘制折线图:

  matplotlib模块

window机器上取本机的ping数据:

  subprocess模块

那么下面我们逐一分析这些模块,以及怎么样使用,完成最后的需求.

模块简介

datetime模块

相信我们都使用过这个模块,那么我们要实现每天定时来执行程序,就可以用以下方式来实现:

 
 
 
 
 
 
 
 
1
import datetime
2
import time
3
4
def main():
5
    while True:
6
        while True:
7
            now = datetime.datetime.now()# 这里可以取到系统的当前时间
8
            if now.hour == 6 and now.minute == 30:# 取当前时间的小时和分钟,这样每天到这个设定好的小时和分钟内的时候我们就会跳出这个内循环,进入到外循环,从而执行主函数
9
                # 当然设定时间我们也可以设定秒,但是其实设定到秒的情况下有可能无法进入函数,时间太短系统无法判定
10
                break
11
            if now.hour == 9 and now.minute == 30:
12
                break
13
            if now.hour == 12 and now.minute == 30:
14
                break
15
            if now.hour == 14 and now.minute == 30:
16
                break
17
            time.sleep(20)
18
        # 主函数
19
        time.sleep(60)# 这里加入睡眠60秒是为了让主函数不至于在这一分钟内一直执行,仅执行一次就好
20
 
 

subprocess模块

这个模块主要用于python调用系统的cmd窗口并返回结果,具体实现如下.

 
 
 
xxxxxxxxxx
1
26
 
 
 
 
1
# encoding=utf-8
2
import subprocess # 导入模块,没装的话自己去pip install subprocess
3
import sys
4
5
# 常用编码
6
GBK = 'gbk'
7
UTF8 = 'utf-8'
8
9
# 解码方式,一般 py 文件执行为utf-8 ,但是cmd 命令为 gbk
10
current_encoding = GBK
11
12
popen = subprocess.Popen(['ping', 'www.baidu.com'],
13
                         stdout=subprocess.PIPE,
14
                         stderr=subprocess.PIPE,
15
                         bufsize=1)
16
17
# 重定向标准输出
18
while popen.poll() is None:  # None表示正在执行中
19
    r = popen.stdout.readline().decode(current_encoding)
20
    sys.stdout.write(r)  # 可修改输出方式,比如控制台、文件等
21
22
# 重定向错误输出
23
if popen.poll() != 0:  # 不为0表示执行错误
24
    err = popen.stderr.read().decode(current_encoding)
25
    sys.stdout.write(err)  # 可修改输出方式,比如控制台、文件等
 
 

matplotlib折线图

 
 
 
x
 
 
 
 
1
'''
2
折线图绘制的时候主要碰到了下面几个问题:
3
1. 标签和折线的名称不能使用中文
4
解决:导入一个字体模块或者不用中文,用全拼或者英文
5
2. 绘图时候要控制图层的大小
6
解决: 在刚开始绘图的时候加入plt.figure(figsize=(10, 8)),可以调整图层的大小,后面的(10,8)实际大小是乘以100,也就是1000*800的图片大小
7
3. 最后保存图片的时候保存jpg格式出错
8
解决:需要额外装一个模块,语句 pip install pillow
9
'''
10
# 例程如下
11
from font_set import font_set# 这里我自己写了一个字体的模块,读者应该没有,可以忽略
12
import matplotlib.pyplot as plt
13
from pylab import mpl
14
15
mpl.rcParams['font.sans-serif'] = ['SimHei']  # SimHei是黑体的意思
16
17
x1 = ['06:00', '12:00', '18:00', '24:00']# 横轴
18
y1 = [4, 6, 8, 23]
19
z1 = [5, 5, 7, 15]
20
a1 = [2, 9, 10, 6]
21
22
# x = np.random.random_integers(1, 20, 10)
23
# # y = range(len(x))
24
25
26
fig = plt.figure(figsize=(10, 8))# 控制图层的大小
27
ax = fig.add_subplot(1, 1, 1)
28
ax.plot(x1, y1)
29
for x, y in zip(x1, y1):
30
    plt.text(x, y + 0.3, '%.0f' % y, ha='center', va='bottom', fontsize=10.5)
31
ax.plot(x1, z1)
32
for x, y in zip(x1, z1):
33
    plt.text(x, y + 0.3, '%.0f' % y, ha='center', va='bottom', fontsize=10.5)
34
ax.plot(x1, a1)
35
for x, y in zip(x1, a1):
36
    plt.text(x, y + 0.3, '%.0f' % y, ha='center', va='bottom', fontsize=10.5)
37
38
plt.xlabel(u'时间', FontProperties=font_set)
39
plt.ylabel(u'延迟', FontProperties=font_set)
40
plt.title(u"各交易所交易延时", FontProperties=font_set)
41
plt.legend([u"中金所", u"上期所", u"大商所"], prop=font_set)
42
plt.savefig("1.jpg")# 这里要注意,要先保存再show,如果先show了保存图片就会是空白
43
plt.show()
 
 

paramiko模块

 
 
 
x
81
 
 
 
 
1
'''
2
  paramiko模块主要作用是用python来远程连接服务器,发送请求以及取数据,由于使用的是python这样的能够跨平台运行的语言,所以所有python支持的平台,如Linux, Solaris, BSD, MacOS X, Windows等,paramiko都可以支持,因此,如果需要使用SSH从一个平台连接到另外一个平台,进行一系列的操作时,paramiko是最佳工具之一。
3
'''
4
5
class Ping_jifang:# 定义一个ping的类
6
7
    def __init__(self, host_ip, username, password, command, port=22):
8
        self.ssh = paramiko.SSHClient()
9
        self.host_ip = host_ip
10
        self.username = username
11
        self.password = password
12
        self.command = command
13
        self.port = port
14
15
    def ssh_jifang(self):
16
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
17
        try:
18
            self.ssh.connect(self.host_ip, self.port, self.username, self.password, timeout=8)
19
            return True
20
        except Exception as fail:
21
            return False
22
23
    def exec_ssh_command(self):
24
        stdin, stdout, stderr = self.ssh.exec_command(self.command)
25
        result_all = stdout if stdout else stderr
26
        # print(result_all.readlines())
27
        return result_all.readline()
28
        # return stdout
29
        # print(self.command)
30
        # result_all = os.popen(self.command)
31
        # return result_all
32
33
    def logout(self):
34
        self.ssh.close()
35
36
def main():
37
    print('进入主函数')
38
    ip_dit = {
39
        "yidong1": {
40
            "info": ["ip地址", "用户名", "密码"]
41
        },
42
        "yidong2": {
43
            "info": ["ip地址", "用户名", "密码"]
44
        },
45
        "shuxun": {
46
            "info": ["ip地址", "用户名", "密码"]
47
        },
48
        "languang": {
49
            "info": ["ip地址", "用户名", "密码"]
50
        }
51
    }
52
53
    # 这个语句就是我们用当前操作机来发送给linux机器的语句
54
    command_ping = "ping 114.114.114.114 -c 100 -i 0.001 -f | grep 'rtt' | awk -F '[ =/]+' '{print $7}'"
55
56
    for i in ip_dit:
57
58
        client_ping = Ping_jifang(ip_dit[i]["info"][0], ip_dit[i]["info"][1], ip_dit[i]["info"][2], command_ping)
59
        if client_ping.ssh_jifang():
60
            result = client_ping.exec_ssh_command()
61
            result = eval(result[:-2])# 因为绘图需要列表,列表内要是int或者float数据,所以这里我们切割掉\n,然后用eval去掉引号,从而使列表内是符合要求的可以绘图的数据
62
63
            # print(i)
64
            # print(type(a),yidong2.append(a),yidong2)
65
            if i == "yidong1":
66
                yidong1.append(result)
67
            elif i == "yidong2":
68
                yidong2.append(result)
69
            elif i == "shuxun":
70
                shuxun.append(result)
71
            elif i == "languang":
72
                languang.append(result)
73
            else:
74
                pass
75
            client_ping.logout()
76
77
    print(yidong1)
78
    print(yidong2)
79
    print(shuxun)
80
    print(languang)
 
 

模块的使用就如上介绍,下面放上在linux和window机器上分别可以使用的完整程序.

window版本程序

 
 
 
xxxxxxxxxx
1
112
 
 
1
'''
2
此程序是取本机(windows)对于其他网址的ping延迟
3
'''
4
import subprocess, sys, time, re, datetime
5
import numpy as np
6
import matplotlib.pyplot as plt
7
from matplotlib.font_manager import FontProperties
8
from pylab import mpl
9
from threading import Thread
10
11
mpl.rcParams['font.sans-serif'] = ['SimHei']  # SimHei是黑体的意思
12
plt.style.use('ggplot')
13
14
np.random.seed(1)
15
16
# 字体要导一下,还有别的导字体方法,这只是一种
17
font_set = FontProperties(fname=r"D:\\msyh.ttc", size=12)
18
19
count = 0
20
21
22
# %Y-%m-%d
23
def delay(host):
24
    popen = subprocess.Popen(['ping', host],
25
                             stdout=subprocess.PIPE,
26
                             stderr=subprocess.PIPE,
27
                             bufsize=1)
28
    while popen.poll() is None:
29
        r = popen.stdout.readline().decode('gbk')
30
        # sys.stdout.write(r)
31
32
        # 这里是取字段的功能,linux里面应该是按avg取,windows里面是按汉字'平均'取得
33
        res = re.findall(r'平均 = (.*?)ms', r)
34
        if res:
35
            return res[0]
36
    if popen.poll() != 0:
37
        err = popen.stderr.read()
38
        sys.stdout.write(err)
39
40
41
def run():
42
    print('进入程序主体')
43
    global time_x
44
    time_x.append(time_now)
45
    res1 = delay('www.qq.com')
46
    global lis1
47
    lis1.append(eval(res1))
48
    res2 = delay('www.baidu.com')
49
    global lis2
50
    lis2.append(eval(res2))
51
    res3 = delay('www.jianshu.com')
52
    global lis3
53
    lis3.append(eval(res3))
54
    res4 = delay('www.runoob.com')
55
    global lis4
56
    lis4.append(eval(res4))
57
58
    print(len(lis1))
59
    print(lis1)
60
    time.sleep(1)
61
    if len(lis1) == 4:  # 当取到四个延迟数据,也就是一天过去的时候,会生成折线图
62
        print('进入绘图函数')
63
        plt.figure(figsize=(10, 8))  # 调整图层大小
64
        plt.plot(time_x, lis1, marker='o', mec='b', mfc='w', label=u'QQ')
65
        for x, y in zip(time_x, lis1):
66
            plt.text(x, y + 0.3, '%.0f' % y, ha='center', va='bottom', fontsize=10.5)
67
68
        plt.plot(time_x, lis2, marker='v', mec='g', mfc='w', label=u'百度')
69
70
        plt.plot(time_x, lis3, marker='^', mec='r', mfc='w', label=u'简书')
71
        plt.plot(time_x, lis4, marker='s', mec='y', mfc='w', label=u'菜鸟编程')
72
        plt.plot([0, 15, 30, 45], "rd")
73
        plt.margins(0)
74
        plt.subplots_adjust(bottom=0.10)
75
        plt.xlabel(u'时间', FontProperties=font_set)  # X轴标签
76
        plt.ylabel(u'延迟ms', FontProperties=font_set)  # Y轴标签
 
 
77
        plt.title(u"各交易所交易延时", FontProperties=font_set)
78
79
        plt.grid(True)
80
        plt.legend(loc=0)
81
        global count
82
        count += 1
83
        plt.tight_layout()
84
        plt.savefig(f"{date}-{count}.jpg")  # 保存的文件名
85
        # plt.show()
86
        plt.close()  # 这里要注意,一定要关闭当前图层,不然之后画出来的图会和之前的图合并出现
87
        print('重置列表')
88
        time_x.clear()
89
        lis1.clear()
90
        lis2.clear()
91
        lis3.clear()
92
        lis4.clear()
93
94
95
if __name__ == '__main__':
96
    # 设定的开始时间,即第一次等于这个时间的时候开始进入程序,得到第一个延迟数据,之后可以一直不关,这个时间会一直保持增长
97
    sched_Timer = datetime.datetime(2019, 9, 27, 10, 38, 00)
98
99
    lis1 = list()
100
    lis2 = list()
101
    lis3 = list()
102
    lis4 = list()
103
    time_x = list()
104
    while True:
105
        date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
106
        time_now = time.strftime('%H:%M:%S', time.localtime(time.time()))
107
        now = datetime.datetime.now()  # 取到当前系统的时间
108
        # if sched_Timer < now < (sched_Timer + datetime.timedelta(seconds=1)):
109
        if 1 == 1:
110
            t1 = Thread(target=run)  # 子线程
111
            t1.start()
112
            t1.join()
113
            # 这里是延迟时间,即设定为hour=6就是六个小时ping一次数据,minutes=1就是一分钟ping一次,累计四次才会生成一个图片
114
            sched_Timer = sched_Timer + datetime.timedelta(minutes=1)
115
 
 

linux版本程序

 
 
 
x
4
147
 
 
 
 
1
'''
2
此程序是本机通过远程linux机器来取不同linux机器的ping的延迟
3
'''
4
import paramiko
5
import time
6
import datetime
7
import matplotlib.pyplot as plt
8
9
# font_set = FontProperties(fname=r"D:\\msyh.ttc", size=12)
10
# font_set = FontProperties(fname='utf-8', size=12)
11
12
13
class Ping_jifang:
14
15
    def __init__(self, host_ip, username, password, command, port=22):
16
        self.ssh = paramiko.SSHClient()
17
        self.host_ip = host_ip
18
        self.username = username
19
        self.password = password
20
        self.command = command
21
        self.port = port
22
23
    def ssh_jifang(self):
24
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
25
        try:
26
            self.ssh.connect(self.host_ip, self.port, self.username, self.password, timeout=8)
27
            return True
28
        except Exception as fail:
29
            return False
30
31
    def exec_ssh_command(self):
32
        stdin, stdout, stderr = self.ssh.exec_command(self.command)
33
        result_all = stdout if stdout else stderr
34
        # print(result_all.readlines())
35
        return result_all.readline()
36
        # return stdout
37
        # print(self.command)
38
        # result_all = os.popen(self.command)
39
        # return result_all
40
41
    def logout(self):
42
        self.ssh.close()
43
44
45
def main():
46
    print('进入主函数')
47
    ip_dit = {
48
        "yidong1": {
49
            "info": ["10.0.0.99", "root", "1"]
50
        },
51
        "yidong2": {
52
            "info": ["10.221.1.190", "root", "htqh@2019"]
53
        },
54
        "shuxun": {
55
            "info": ["10.225.1.94", "root", "123456"]
56
        },
57
        "languang": {
58
            "info": ["10.121.137.58", "root", "htqh@1234"]
59
        }
60
    }
61
62
    command_ping = "ping 114.114.114.114 -c 100 -i 0.001 -f | grep 'rtt' | awk -F '[ =/]+' '{print $7}'"
63
64
    for i in ip_dit:
65
66
        client_ping = Ping_jifang(ip_dit[i]["info"][0], ip_dit[i]["info"][1], ip_dit[i]["info"][2], command_ping)
67
        if client_ping.ssh_jifang():
68
            result = client_ping.exec_ssh_command()
69
            result = eval(result[:-2])
70
71
            # print(i)
72
            # print(type(a),yidong2.append(a),yidong2)
73
            if i == "yidong1":
74
                yidong1.append(result)
75
            elif i == "yidong2":
76
                yidong2.append(result)
77
            elif i == "shuxun":
78
                shuxun.append(result)
79
            elif i == "languang":
80
                languang.append(result)
81
            else:
82
                pass
83
            client_ping.logout()
84
85
    print(yidong1)
86
    print(yidong2)
87
    print(shuxun)
88
    print(languang)
89
90
    # 绘图函数
91
    if len(yidong2) == 4:  # 当取到四个延迟数据,也就是一天过去的时候,会生成折线图
92
        plt.figure(figsize=(10, 8))  # 调整图层大小
93
        time_x = ['06:00', '09:00', '12:00', '15:00']
94
        date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
95
        print('进入绘图函数')
96
        # plt.plot(time_x, yidong1, marker='o', mec='b', mfc='w', label=u'QQ')
97
        for x, y in zip(time_x, yidong2):
98
            plt.text(x, y + 0.3, '%.0f' % y, ha='center', va='bottom', fontsize=10.5)
99
        plt.plot(time_x, yidong2, marker='v', mec='g', mfc='w', label=u'shuxun')
100
        plt.plot(time_x, shuxun, marker='^', mec='r', mfc='w', label=u'zhongjinsuo')
101
        plt.plot(time_x, languang, marker='s', mec='y', mfc='w', label=u'yidong')
102
        plt.ylim(0, 20) # 纵坐标范围
103
        y = range(0, 20, 1)
104
        plt.yticks(y)   # 纵坐标刻度
105
        plt.margins(0)
106
        plt.subplots_adjust(bottom=0.10)
107
        plt.xlabel(u'time')  # X轴标签
108
        plt.ylabel(u'ms')  # Y轴标签
109
        plt.title(u"timedelate")
110
111
        plt.legend(loc=0)
112
        global count
113
        count += 1
114
        plt.tight_layout()
115
        plt.savefig(f"{date}-{count}.jpg")  # 保存的文件名
116
        # plt.show()
117
        plt.close()  # 这里要注意,一定要关闭当前图层,不然之后画出来的图会和之前的图合并出现
118
        print('重置列表')
119
        time_x.clear()
120
        yidong1.clear()
121
        yidong2.clear()
122
        shuxun.clear()
123
        languang.clear()
124
125
126
if __name__ == "__main__":
127
    yidong1 = []
128
    yidong2 = []
129
    shuxun = []
130
    languang = []
131
    count = 0
132
    while True:
133
        while True:
134
            now = datetime.datetime.now()
135
            print(f'\r当前时间:{now}', end='')
136
            if now.hour == 16 and now.minute == 1:
137
                break
138
            if now.hour == 16 and now.minute == 15:
139
                break
140
            if now.hour == 16 and now.minute == 16:
141
                break
142
            if now.hour == 16 and now.minute == 17:
143
                break
144
            time.sleep(1)
145
        time.sleep(61)
146
        main()
147
 
 

定时ping取返回值并绘图的更多相关文章

  1. ajax取返回值的方法

    var check_res; //ajax核对手机验证码 function smsverify(){ var ajaxurl = APP_ROOT+"/index.php?ctl=ajax& ...

  2. loadrunner-获取返回值和自定义参数(参数运算)

    实例:手机端操作,A新增了一条事件(返回结果:事件id,例如:1), A这时需要获取新增产生的事件id,并作为参数进行传递,才能将这条事件上报给B(返回结果:事件id不变,步骤id等于事件id加1), ...

  3. C#反射调用外部Dll,执行其中异步函数并取返回值

    using System.Reflection; 1.载入Dll Assembly asm=Assembly.LoadFile(FullPath);//FullPath 为Dll所在位置的全路径. 2 ...

  4. mybatis调用存储过程获得取返回值

    总体思路:map传值 controller: Map<String,Object> m=new HashMap<String,Object>(); m.put("na ...

  5. BeginInvoke与EndInvoke方法解决多线程接收委托返回值问题

    BeginInvoke与EndInvoke方法解决多线程接收委托返回值问题 原文:http://www.sufeinet.com/thread-3707-1-1.html      大家可以先看看我上 ...

  6. lua入门之二:c/c++ 调用lua及多个函数返回值的获取

    当 Lua 调用 C 函数的时候,使用和 C 调用 Lua 同样类型的栈来交互. C 函数从栈中获取她的參数.调用结束后将返回结果放到栈中.为了区分返回结果和栈中的其它的值,每一个 C 函数还会返回结 ...

  7. 【OC学习-8】存取器方法?getter和setter?事实上就是赋值和返回值的两种函数

    我们在声明类的时候,有实例变量+方法(函数),这些实例变量假设默认的话都是protected类型,一般无法直接訪问.更别提赋值和调用了,所以就产生了两种函数,getter函数就是可以返回实例变量的值, ...

  8. 关于readdir返回值中struct dirent.d_type的取值有关问题(转)

    关于readdir返回值中struct dirent.d_type的取值问题 原网页链接 http://www.gnu.org/software/libc/manual/html_node/Direc ...

  9. Jmeter的JDBC Request,sql参数化及返回值取值

    1.JDBC Request面板 Variable Name:数据库连接池的名字,需要与JDBC Connection Configuration的Variable Name Bound Pool名字 ...

随机推荐

  1. 归档和解档配合NSFile存储数据

    NSString *Name = @"yc"; //第一个常量NSDocumentDirectory表示正在查找沙盒Document目录的路径(如果参数为NSCachesDirec ...

  2. SQL SERVER 2008R2 执行大脚本文件时,提示“内存不足”的解决办法

    我把一个数据库的架构及数据都已脚本的方式拷贝下来,再去新建一个数据库想把脚本执行一下,但提示如下错误: 问题描述: 当客户服务器不允许直接备份时,往往通过导出数据库脚本的方式来部署-还原数据库, 但是 ...

  3. .Net 动态编译(c# 脚本)

    1 用.NET提供的类动态编译代码字符串,生成DLL存于内存中,加载到程序域 2 用反射的方式调用这个DLL 将要被编译和执行的代码读入并以字符串方式保存声明CSharpCodeProvider对象实 ...

  4. day10 nfs服务,nginx负载均衡,定时任务

    ==================nginx 负载均衡==================== 实现nginx负载均衡的效果,并运用nfs服务共享目录,使所有nginx服务拥有共同的http目录 n ...

  5. thinkphp DEFINE标签

    DEFINE标签用于中模板中定义常量,用法如下: 直线电机厂家 <define name="MY_DEFINE_NAME" value="3" /> ...

  6. java——万年历

    package oop; import java.util.Scanner; public class 万年历 { public static void main(String[] args) { / ...

  7. 软件-开发工具:Gradle

    ylbtech-软件-开发工具:Gradle Gradle是一个基于Apache Ant和Apache Maven概念的项目自动化构建开源工具.它使用一种基于Groovy的特定领域语言(DSL)来声明 ...

  8. 4_4.springboot之Web开发登录和拦截器

    1.登录处理 1).禁用模板引擎的缓存 # 禁用缓存 spring.thymeleaf.cache=false 2).页面修改完用ctrl+f9:重新编译: LoginController @Cont ...

  9. 执行sql查询,并查看语句执行花费时间

    declare @d datetimeset @d=getdate() select * from A PRINT '[语句执行花费时间(毫秒)]'+LTRIM(datediff(ms,@d,getd ...

  10. PHP网络请求优化

    目录 1. 设置超时时间 2. 将串行请求并行化 1. 设置超时时间 连接超时:200ms 读超时: 800ms 写超时: 500ms 2. 将串行请求并行化 使用curl_multi_*() 使用s ...