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

subprocess模块

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

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

matplotlib折线图

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

paramiko模块

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

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

window版本程序

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

linux版本程序

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

    当前有项目工程名为iOS,需要修改工程名为IFLY.在修改前注意备份项目 修改项目名 出现弹框,点击Rename 修改工程目录文件名 注意Tests与UITests不要删除 选中IFLY.xcodep ...

  2. 2018-10-29-微软-Tech-Summit-技术暨生态大会课程-·-基于-Roslyn-打造高性能预编译框架...

    title author date CreateTime categories 微软 Tech Summit 技术暨生态大会课程 · 基于 Roslyn 打造高性能预编译框架 lindexi 2018 ...

  3. 2019-3-20-win10-uwp-如何自定义-RichTextBlock-右键菜单

    title author date CreateTime categories win10 uwp 如何自定义 RichTextBlock 右键菜单 lindexi 2019-3-20 9:54:9 ...

  4. VS环境下,DEV插件的ComboBoxEdit控件最简单的数据源绑定和获取方法

    使用 ComboBoxEdit 控件绑定key/value值: 因为 ComboBoxEdit 没有 DataSource 属性,所以不能直接绑定数据源,只能一项一项的添加. 首先创建一个类ListI ...

  5. 数据库MySQL--基础查询

    1.查询字段 查询表某字段:select 字段名 from 表名: 查询表内所有字段:select * from 表名: (当字段和关键字重名是用( ` )着重号区分 ) 2.查询常量值 select ...

  6. [转]springmvc+mybatis需要的jar包与详解

    1.antlr-2.7.6.jar:  项目中没有添加,hibernate不会执行hql语句 2.Aopalliance.jar: 这个包是AOP联盟的API包,里面包含了针对面向切面的接口,通常Sp ...

  7. 最大流dicnic——hdu1532模板题

    #include<bits/stdc++.h> using namespace std; #define maxn 1005 #define ll long long const ll i ...

  8. SQLite3与C++的结合应用

    SQLite并没有一次性做到位,只有下载这些东西是不能放在vs2010中并马上使用的,下载下来的文件中有sqlite3.c/h/dll/def,还是不够用的.我们需要的sqlite3.lib文件并不在 ...

  9. 云时代IDC自动化运维的几大神器

    云时代IDC自动化运维的几大神器 2016年09月18日 10:27:41 天府云创 阅读数:1715   版权声明:本文为EnweiTech原创文章,未经博主允许不得转载. https://blog ...

  10. LightOJ-1007-Mathematically Hard-欧拉函数打表+前缀和+预处理

    Mathematically some problems look hard. But with the help of the computer, some problems can be easi ...