定时ping取返回值并绘图
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模块
相信我们都使用过这个模块,那么我们要实现每天定时来执行程序,就可以用以下方式来实现:
- import datetime
- import time
-
- def main():
- while True:
- while True:
- now = datetime.datetime.now()# 这里可以取到系统的当前时间
- if now.hour == 6 and now.minute == 30:# 取当前时间的小时和分钟,这样每天到这个设定好的小时和分钟内的时候我们就会跳出这个内循环,进入到外循环,从而执行主函数
- # 当然设定时间我们也可以设定秒,但是其实设定到秒的情况下有可能无法进入函数,时间太短系统无法判定
- break
- if now.hour == 9 and now.minute == 30:
- break
- if now.hour == 12 and now.minute == 30:
- break
- if now.hour == 14 and now.minute == 30:
- break
- time.sleep(20)
- # 主函数
- time.sleep(60)# 这里加入睡眠60秒是为了让主函数不至于在这一分钟内一直执行,仅执行一次就好
-
subprocess模块
这个模块主要用于python调用系统的cmd窗口并返回结果,具体实现如下.
- xxxxxxxxxx
- # encoding=utf-8
- import subprocess # 导入模块,没装的话自己去pip install subprocess
- import sys
-
- # 常用编码
- GBK = 'gbk'
- UTF8 = 'utf-8'
-
- # 解码方式,一般 py 文件执行为utf-8 ,但是cmd 命令为 gbk
- current_encoding = GBK
-
- popen = subprocess.Popen(['ping', 'www.baidu.com'],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- bufsize=1)
-
- # 重定向标准输出
- while popen.poll() is None: # None表示正在执行中
- r = popen.stdout.readline().decode(current_encoding)
- sys.stdout.write(r) # 可修改输出方式,比如控制台、文件等
-
- # 重定向错误输出
- if popen.poll() != 0: # 不为0表示执行错误
- err = popen.stderr.read().decode(current_encoding)
- sys.stdout.write(err) # 可修改输出方式,比如控制台、文件等
matplotlib折线图
- x
- '''
- 折线图绘制的时候主要碰到了下面几个问题:
- 1. 标签和折线的名称不能使用中文
- 解决:导入一个字体模块或者不用中文,用全拼或者英文
- 2. 绘图时候要控制图层的大小
- 解决: 在刚开始绘图的时候加入plt.figure(figsize=(10, 8)),可以调整图层的大小,后面的(10,8)实际大小是乘以100,也就是1000*800的图片大小
- 3. 最后保存图片的时候保存jpg格式出错
- 解决:需要额外装一个模块,语句 pip install pillow
- '''
- # 例程如下
- from font_set import font_set# 这里我自己写了一个字体的模块,读者应该没有,可以忽略
- import matplotlib.pyplot as plt
- from pylab import mpl
-
- mpl.rcParams['font.sans-serif'] = ['SimHei'] # SimHei是黑体的意思
-
- x1 = ['06:00', '12:00', '18:00', '24:00']# 横轴
- y1 = [4, 6, 8, 23]
- z1 = [5, 5, 7, 15]
- a1 = [2, 9, 10, 6]
-
- # x = np.random.random_integers(1, 20, 10)
- # # y = range(len(x))
-
-
- fig = plt.figure(figsize=(10, 8))# 控制图层的大小
- ax = fig.add_subplot(1, 1, 1)
- ax.plot(x1, y1)
- for x, y in zip(x1, y1):
- plt.text(x, y + 0.3, '%.0f' % y, ha='center', va='bottom', fontsize=10.5)
- ax.plot(x1, z1)
- for x, y in zip(x1, z1):
- plt.text(x, y + 0.3, '%.0f' % y, ha='center', va='bottom', fontsize=10.5)
- ax.plot(x1, a1)
- for x, y in zip(x1, a1):
- plt.text(x, y + 0.3, '%.0f' % y, ha='center', va='bottom', fontsize=10.5)
-
- plt.xlabel(u'时间', FontProperties=font_set)
- plt.ylabel(u'延迟', FontProperties=font_set)
- plt.title(u"各交易所交易延时", FontProperties=font_set)
- plt.legend([u"中金所", u"上期所", u"大商所"], prop=font_set)
- plt.savefig("1.jpg")# 这里要注意,要先保存再show,如果先show了保存图片就会是空白
- plt.show()
paramiko模块
- x
- '''
- paramiko模块主要作用是用python来远程连接服务器,发送请求以及取数据,由于使用的是python这样的能够跨平台运行的语言,所以所有python支持的平台,如Linux, Solaris, BSD, MacOS X, Windows等,paramiko都可以支持,因此,如果需要使用SSH从一个平台连接到另外一个平台,进行一系列的操作时,paramiko是最佳工具之一。
- '''
-
- class Ping_jifang:# 定义一个ping的类
-
- def __init__(self, host_ip, username, password, command, port=22):
- self.ssh = paramiko.SSHClient()
- self.host_ip = host_ip
- self.username = username
- self.password = password
- self.command = command
- self.port = port
-
- def ssh_jifang(self):
- self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- try:
- self.ssh.connect(self.host_ip, self.port, self.username, self.password, timeout=8)
- return True
- except Exception as fail:
- return False
-
- def exec_ssh_command(self):
- stdin, stdout, stderr = self.ssh.exec_command(self.command)
- result_all = stdout if stdout else stderr
- # print(result_all.readlines())
- return result_all.readline()
- # return stdout
- # print(self.command)
- # result_all = os.popen(self.command)
- # return result_all
-
- def logout(self):
- self.ssh.close()
-
- def main():
- print('进入主函数')
- ip_dit = {
- "yidong1": {
- "info": ["ip地址", "用户名", "密码"]
- },
- "yidong2": {
- "info": ["ip地址", "用户名", "密码"]
- },
- "shuxun": {
- "info": ["ip地址", "用户名", "密码"]
- },
- "languang": {
- "info": ["ip地址", "用户名", "密码"]
- }
- }
-
- # 这个语句就是我们用当前操作机来发送给linux机器的语句
- command_ping = "ping 114.114.114.114 -c 100 -i 0.001 -f | grep 'rtt' | awk -F '[ =/]+' '{print $7}'"
-
- for i in ip_dit:
-
- client_ping = Ping_jifang(ip_dit[i]["info"][0], ip_dit[i]["info"][1], ip_dit[i]["info"][2], command_ping)
- if client_ping.ssh_jifang():
- result = client_ping.exec_ssh_command()
- result = eval(result[:-2])# 因为绘图需要列表,列表内要是int或者float数据,所以这里我们切割掉\n,然后用eval去掉引号,从而使列表内是符合要求的可以绘图的数据
-
- # print(i)
- # print(type(a),yidong2.append(a),yidong2)
- if i == "yidong1":
- yidong1.append(result)
- elif i == "yidong2":
- yidong2.append(result)
- elif i == "shuxun":
- shuxun.append(result)
- elif i == "languang":
- languang.append(result)
- else:
- pass
- client_ping.logout()
-
- print(yidong1)
- print(yidong2)
- print(shuxun)
- print(languang)
模块的使用就如上介绍,下面放上在linux和window机器上分别可以使用的完整程序.
window版本程序
- xxxxxxxxxx
- '''
- 此程序是取本机(windows)对于其他网址的ping延迟
- '''
- import subprocess, sys, time, re, datetime
- import numpy as np
- import matplotlib.pyplot as plt
- from matplotlib.font_manager import FontProperties
- from pylab import mpl
- from threading import Thread
-
- mpl.rcParams['font.sans-serif'] = ['SimHei'] # SimHei是黑体的意思
- plt.style.use('ggplot')
-
- np.random.seed(1)
-
- # 字体要导一下,还有别的导字体方法,这只是一种
- font_set = FontProperties(fname=r"D:\\msyh.ttc", size=12)
-
- count = 0
-
-
- # %Y-%m-%d
- def delay(host):
- popen = subprocess.Popen(['ping', host],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- bufsize=1)
- while popen.poll() is None:
- r = popen.stdout.readline().decode('gbk')
- # sys.stdout.write(r)
-
- # 这里是取字段的功能,linux里面应该是按avg取,windows里面是按汉字'平均'取得
- res = re.findall(r'平均 = (.*?)ms', r)
- if res:
- return res[0]
- if popen.poll() != 0:
- err = popen.stderr.read()
- sys.stdout.write(err)
-
-
- def run():
- print('进入程序主体')
- global time_x
- time_x.append(time_now)
- res1 = delay('www.qq.com')
- global lis1
- lis1.append(eval(res1))
- res2 = delay('www.baidu.com')
- global lis2
- lis2.append(eval(res2))
- res3 = delay('www.jianshu.com')
- global lis3
- lis3.append(eval(res3))
- res4 = delay('www.runoob.com')
- global lis4
- lis4.append(eval(res4))
-
- print(len(lis1))
- print(lis1)
- time.sleep(1)
- if len(lis1) == 4: # 当取到四个延迟数据,也就是一天过去的时候,会生成折线图
- print('进入绘图函数')
- plt.figure(figsize=(10, 8)) # 调整图层大小
- plt.plot(time_x, lis1, marker='o', mec='b', mfc='w', label=u'QQ')
- for x, y in zip(time_x, lis1):
- plt.text(x, y + 0.3, '%.0f' % y, ha='center', va='bottom', fontsize=10.5)
-
- plt.plot(time_x, lis2, marker='v', mec='g', mfc='w', label=u'百度')
-
- plt.plot(time_x, lis3, marker='^', mec='r', mfc='w', label=u'简书')
- plt.plot(time_x, lis4, marker='s', mec='y', mfc='w', label=u'菜鸟编程')
- plt.plot([0, 15, 30, 45], "rd")
- plt.margins(0)
- plt.subplots_adjust(bottom=0.10)
- plt.xlabel(u'时间', FontProperties=font_set) # X轴标签
- plt.ylabel(u'延迟ms', FontProperties=font_set) # Y轴标签
- plt.title(u"各交易所交易延时", FontProperties=font_set)
-
- plt.grid(True)
- plt.legend(loc=0)
- global count
- count += 1
- plt.tight_layout()
- plt.savefig(f"{date}-{count}.jpg") # 保存的文件名
- # plt.show()
- plt.close() # 这里要注意,一定要关闭当前图层,不然之后画出来的图会和之前的图合并出现
- print('重置列表')
- time_x.clear()
- lis1.clear()
- lis2.clear()
- lis3.clear()
- lis4.clear()
-
-
- if __name__ == '__main__':
- # 设定的开始时间,即第一次等于这个时间的时候开始进入程序,得到第一个延迟数据,之后可以一直不关,这个时间会一直保持增长
- sched_Timer = datetime.datetime(2019, 9, 27, 10, 38, 00)
-
- lis1 = list()
- lis2 = list()
- lis3 = list()
- lis4 = list()
- time_x = list()
- while True:
- date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
- time_now = time.strftime('%H:%M:%S', time.localtime(time.time()))
- now = datetime.datetime.now() # 取到当前系统的时间
- # if sched_Timer < now < (sched_Timer + datetime.timedelta(seconds=1)):
- if 1 == 1:
- t1 = Thread(target=run) # 子线程
- t1.start()
- t1.join()
- # 这里是延迟时间,即设定为hour=6就是六个小时ping一次数据,minutes=1就是一分钟ping一次,累计四次才会生成一个图片
- sched_Timer = sched_Timer + datetime.timedelta(minutes=1)
-
linux版本程序
- x
- '''
- 此程序是本机通过远程linux机器来取不同linux机器的ping的延迟
- '''
- import paramiko
- import time
- import datetime
- import matplotlib.pyplot as plt
-
- # font_set = FontProperties(fname=r"D:\\msyh.ttc", size=12)
- # font_set = FontProperties(fname='utf-8', size=12)
-
-
- class Ping_jifang:
-
- def __init__(self, host_ip, username, password, command, port=22):
- self.ssh = paramiko.SSHClient()
- self.host_ip = host_ip
- self.username = username
- self.password = password
- self.command = command
- self.port = port
-
- def ssh_jifang(self):
- self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- try:
- self.ssh.connect(self.host_ip, self.port, self.username, self.password, timeout=8)
- return True
- except Exception as fail:
- return False
-
- def exec_ssh_command(self):
- stdin, stdout, stderr = self.ssh.exec_command(self.command)
- result_all = stdout if stdout else stderr
- # print(result_all.readlines())
- return result_all.readline()
- # return stdout
- # print(self.command)
- # result_all = os.popen(self.command)
- # return result_all
-
- def logout(self):
- self.ssh.close()
-
-
- def main():
- print('进入主函数')
- ip_dit = {
- "yidong1": {
- "info": ["10.0.0.99", "root", "1"]
- },
- "yidong2": {
- "info": ["10.221.1.190", "root", "htqh@2019"]
- },
- "shuxun": {
- "info": ["10.225.1.94", "root", "123456"]
- },
- "languang": {
- "info": ["10.121.137.58", "root", "htqh@1234"]
- }
- }
-
- command_ping = "ping 114.114.114.114 -c 100 -i 0.001 -f | grep 'rtt' | awk -F '[ =/]+' '{print $7}'"
-
- for i in ip_dit:
-
- client_ping = Ping_jifang(ip_dit[i]["info"][0], ip_dit[i]["info"][1], ip_dit[i]["info"][2], command_ping)
- if client_ping.ssh_jifang():
- result = client_ping.exec_ssh_command()
- result = eval(result[:-2])
-
- # print(i)
- # print(type(a),yidong2.append(a),yidong2)
- if i == "yidong1":
- yidong1.append(result)
- elif i == "yidong2":
- yidong2.append(result)
- elif i == "shuxun":
- shuxun.append(result)
- elif i == "languang":
- languang.append(result)
- else:
- pass
- client_ping.logout()
-
- print(yidong1)
- print(yidong2)
- print(shuxun)
- print(languang)
-
- # 绘图函数
- if len(yidong2) == 4: # 当取到四个延迟数据,也就是一天过去的时候,会生成折线图
- plt.figure(figsize=(10, 8)) # 调整图层大小
- time_x = ['06:00', '09:00', '12:00', '15:00']
- date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
- print('进入绘图函数')
- # plt.plot(time_x, yidong1, marker='o', mec='b', mfc='w', label=u'QQ')
- for x, y in zip(time_x, yidong2):
- plt.text(x, y + 0.3, '%.0f' % y, ha='center', va='bottom', fontsize=10.5)
- plt.plot(time_x, yidong2, marker='v', mec='g', mfc='w', label=u'shuxun')
- plt.plot(time_x, shuxun, marker='^', mec='r', mfc='w', label=u'zhongjinsuo')
- plt.plot(time_x, languang, marker='s', mec='y', mfc='w', label=u'yidong')
- plt.ylim(0, 20) # 纵坐标范围
- y = range(0, 20, 1)
- plt.yticks(y) # 纵坐标刻度
- plt.margins(0)
- plt.subplots_adjust(bottom=0.10)
- plt.xlabel(u'time') # X轴标签
- plt.ylabel(u'ms') # Y轴标签
- plt.title(u"timedelate")
-
- plt.legend(loc=0)
- global count
- count += 1
- plt.tight_layout()
- plt.savefig(f"{date}-{count}.jpg") # 保存的文件名
- # plt.show()
- plt.close() # 这里要注意,一定要关闭当前图层,不然之后画出来的图会和之前的图合并出现
- print('重置列表')
- time_x.clear()
- yidong1.clear()
- yidong2.clear()
- shuxun.clear()
- languang.clear()
-
-
- if __name__ == "__main__":
- yidong1 = []
- yidong2 = []
- shuxun = []
- languang = []
- count = 0
- while True:
- while True:
- now = datetime.datetime.now()
- print(f'\r当前时间:{now}', end='')
- if now.hour == 16 and now.minute == 1:
- break
- if now.hour == 16 and now.minute == 15:
- break
- if now.hour == 16 and now.minute == 16:
- break
- if now.hour == 16 and now.minute == 17:
- break
- time.sleep(1)
- time.sleep(61)
- main()
-
定时ping取返回值并绘图的更多相关文章
- ajax取返回值的方法
var check_res; //ajax核对手机验证码 function smsverify(){ var ajaxurl = APP_ROOT+"/index.php?ctl=ajax& ...
- loadrunner-获取返回值和自定义参数(参数运算)
实例:手机端操作,A新增了一条事件(返回结果:事件id,例如:1), A这时需要获取新增产生的事件id,并作为参数进行传递,才能将这条事件上报给B(返回结果:事件id不变,步骤id等于事件id加1), ...
- C#反射调用外部Dll,执行其中异步函数并取返回值
using System.Reflection; 1.载入Dll Assembly asm=Assembly.LoadFile(FullPath);//FullPath 为Dll所在位置的全路径. 2 ...
- mybatis调用存储过程获得取返回值
总体思路:map传值 controller: Map<String,Object> m=new HashMap<String,Object>(); m.put("na ...
- BeginInvoke与EndInvoke方法解决多线程接收委托返回值问题
BeginInvoke与EndInvoke方法解决多线程接收委托返回值问题 原文:http://www.sufeinet.com/thread-3707-1-1.html 大家可以先看看我上 ...
- lua入门之二:c/c++ 调用lua及多个函数返回值的获取
当 Lua 调用 C 函数的时候,使用和 C 调用 Lua 同样类型的栈来交互. C 函数从栈中获取她的參数.调用结束后将返回结果放到栈中.为了区分返回结果和栈中的其它的值,每一个 C 函数还会返回结 ...
- 【OC学习-8】存取器方法?getter和setter?事实上就是赋值和返回值的两种函数
我们在声明类的时候,有实例变量+方法(函数),这些实例变量假设默认的话都是protected类型,一般无法直接訪问.更别提赋值和调用了,所以就产生了两种函数,getter函数就是可以返回实例变量的值, ...
- 关于readdir返回值中struct dirent.d_type的取值有关问题(转)
关于readdir返回值中struct dirent.d_type的取值问题 原网页链接 http://www.gnu.org/software/libc/manual/html_node/Direc ...
- Jmeter的JDBC Request,sql参数化及返回值取值
1.JDBC Request面板 Variable Name:数据库连接池的名字,需要与JDBC Connection Configuration的Variable Name Bound Pool名字 ...
随机推荐
- iOS开发系列-修改项目工程名
当前有项目工程名为iOS,需要修改工程名为IFLY.在修改前注意备份项目 修改项目名 出现弹框,点击Rename 修改工程目录文件名 注意Tests与UITests不要删除 选中IFLY.xcodep ...
- 2018-10-29-微软-Tech-Summit-技术暨生态大会课程-·-基于-Roslyn-打造高性能预编译框架...
title author date CreateTime categories 微软 Tech Summit 技术暨生态大会课程 · 基于 Roslyn 打造高性能预编译框架 lindexi 2018 ...
- 2019-3-20-win10-uwp-如何自定义-RichTextBlock-右键菜单
title author date CreateTime categories win10 uwp 如何自定义 RichTextBlock 右键菜单 lindexi 2019-3-20 9:54:9 ...
- VS环境下,DEV插件的ComboBoxEdit控件最简单的数据源绑定和获取方法
使用 ComboBoxEdit 控件绑定key/value值: 因为 ComboBoxEdit 没有 DataSource 属性,所以不能直接绑定数据源,只能一项一项的添加. 首先创建一个类ListI ...
- 数据库MySQL--基础查询
1.查询字段 查询表某字段:select 字段名 from 表名: 查询表内所有字段:select * from 表名: (当字段和关键字重名是用( ` )着重号区分 ) 2.查询常量值 select ...
- [转]springmvc+mybatis需要的jar包与详解
1.antlr-2.7.6.jar: 项目中没有添加,hibernate不会执行hql语句 2.Aopalliance.jar: 这个包是AOP联盟的API包,里面包含了针对面向切面的接口,通常Sp ...
- 最大流dicnic——hdu1532模板题
#include<bits/stdc++.h> using namespace std; #define maxn 1005 #define ll long long const ll i ...
- SQLite3与C++的结合应用
SQLite并没有一次性做到位,只有下载这些东西是不能放在vs2010中并马上使用的,下载下来的文件中有sqlite3.c/h/dll/def,还是不够用的.我们需要的sqlite3.lib文件并不在 ...
- 云时代IDC自动化运维的几大神器
云时代IDC自动化运维的几大神器 2016年09月18日 10:27:41 天府云创 阅读数:1715 版权声明:本文为EnweiTech原创文章,未经博主允许不得转载. https://blog ...
- LightOJ-1007-Mathematically Hard-欧拉函数打表+前缀和+预处理
Mathematically some problems look hard. But with the help of the computer, some problems can be easi ...