简体   繁体   English

我需要帮助完成我的代码。 注意我是 Python 的初学者

[英]I need help completing my code. Note I am a beginner in Python

I am trying to develop a script which sends an email about checking ping regularly at one hour interval of time.我正在尝试开发一个脚本,它会每隔一小时发送一封关于定期检查 ping 的电子邮件。 I am using Python to program this script and I cannot create a log file to keep the ping logs which I need to mail.我正在使用 Python 编写此脚本,但无法创建日志文件来保存需要邮寄的 ping 日志。 I'm new to using subprocess module and its functions.我是使用 subprocess 模块及其功能的新手。

import threading
import os

def check_ping():
    threading.Timer(5.0, check_ping).start()
    hostname = "www.google.com"
    response = os.system("ping -c 4 " + hostname)

'''
def trace_route():
    threading.Timer(5.0, trace_route).start()
    hostname = "www.google.com"
    response = os.system("traceroute" + hostname)
'''
check_ping()
#trace_route()

output = check_ping()
file = open("sample.txt","a")
file.write(output)
file.close()




import os, platform
import threading

def check_ping():
    threading.Timer(10.0,check_ping).start()
    hostname = "www.google.com"
    response = os.system("ping " + ("-n 1 " if  platform.system().lower()=="windows" else "-c 1 ") + hostname)
    # and then check the response...
    if response == 0:
        pingstatus = "Network Active"
    else:
        pingstatus = "Network Error"

    return pingstatus

pingstatus = check_ping()

This is what I came up with:这就是我想出的:

  • using subprocess instead of os.system使用 subprocess 而不是 os.system
  • added timeout of 8 seconds添加了 8 秒的超时
  • writing to csv file instead of txt file写入 csv 文件而不是 txt 文件
  • added timestamps to csv file, without which I don't really see the point of logging in the first place向 csv 文件添加了时间戳,没有它,我一开始就看不到登录的意义
import os
import threading
import time
from subprocess import Popen, PIPE

def check_ping():
    threading.Timer(10.0,check_ping).start()

    # Get current time
    timestamp = int(time.time())

    # Build the command
    hostname = "www.google.com"
    if os.name == 'nt':
        command = ['ping', '-n', '1', hostname]
    else:
        command = ['ping', '-c', '1', hostname]

    # Create process
    pingProcess = Popen(command, stdout=PIPE, stderr=PIPE)
    try:
        # Timeout 8 seconds, to avoid overlap with the next ping command
        outs, errs = pingProcess.communicate(timeout=8)
    except TimeoutExpired:
        # If timed out, kill
        pingProcess.kill()
        outs, errs = pingProcess.communicate()

    # Get the return code of the process
    response = pingProcess.returncode

    # and then check the response...
    # These four lines can be removed, they are just to see if the system
    # works.
    if response == 0:
        print("Network Active")
    else:
        print("Network Error")

    # You most likely want a CSV file, as most programs accept this file type,
    # including Microsoft Excel and LibreOffice Calc
    # Further, I'm sure you want timestamps with the results.
    file = open("ping.csv","a")
    file.write(str(timestamp) + "," + str(response) + "\n")
    file.close()

check_ping()

Here is another version without using the system's ping command, but instead using a python library for pinging.这是另一个版本,没有使用系统的ping命令,而是使用 python 库进行 ping。 This ensures that the code works on all operating systems:这确保代码适用于所有操作系统:

import threading
import time

from ping3 import ping

def check_ping():
    threading.Timer(10.0,check_ping).start()

    # Get current time
    timestamp = int(time.time())

    # Build the command
    hostname = "www.google.com"

    # Run ping
    ping_result = ping(hostname, timeout=8)
    ping_success = False if ping_result is None else True

    # and then check the response...
    # These four lines can be removed, they are just to see if the system
    # works.
    if ping_success:
        print("Network Active (" + str(ping_result) + ")")
    else:
        print("Network Error")

    # You most likely want a CSV file, as most programs accept this file type,
    # including Microsoft Excel and LibreOffice Calc
    # Further, I'm sure you want timestamps with the results.
    file = open("ping.csv", "a")
    ping_value_str = str(ping_result) if ping_success else "NaN"
    file.write(str(timestamp) + "," + ("0" if ping_success else "1") + "," + ping_value_str + "\n")
    file.close()

check_ping()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在研究 Python Class 和方法。 但我不知道我的代码有什么问题。 需要帮忙。 P3、P4 的结果不起作用 - I am studying Python Class and method. But I don't know whats wrong with my code. Need help. Result for P3, P4 do not work 需要帮助来理解 python 代码 - 我是 Python 的初学者 - Need assistance to understand python code - I am very beginner in Python 我的代码能解决问题吗? 我是python的初学者 - Does my code solve the question? I am a beginner in python 运行此 python 代码时出现错误。 错误是“ElementNotInteractableException”。 任何人都可以帮助我吗? - I am getting error while running this python code. The error is “ElementNotInteractableException”. Can any on help me out? 我得到此python代码的NonType错误。 我该如何更改代码? - I am getting NonType error for this python code. How should I change my code? 我是 python 的初学者,不明白我的代码有什么问题。 我正在使用 pynput - I'm a beginner to python and don't understand what's wrong with my code. I'm using pynput 我的 python 代码中出现此错误。 “OSError:[WinError 10038] 尝试对不是套接字的东西进行操作” - I am getting this error in my python code. "OSError: [WinError 10038] An operation was attempted on something that is not a socket" 我是python OOP的初学者,并且在我的代码中获得了“没有足够的值来解压缩” - I am a beginner in OOP in python and am getting “not enough values to unpack” in my code Python 错误:需要帮助解决 2 个错误(我是初学者) - Python Error: Need help resolving 2 errors (I'm a beginner) 初学者在测试Python代码时,需要帮助! - Beginner at testing Python code, need help!
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM