吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 552|回复: 7
收起左侧

[求助] 小白。麻烦大佬帮忙看看python那里没对,运行程序就直接重启。。谢谢!!

[复制链接]
明天星期六 发表于 2023-5-26 12:18
家里有电脑PT,小白写一个小程序,主要是检测家里网络。。如果检测出断网了就重启,重启5分钟后在ping网络如果还是不通就关闭电脑。代码如下,我编译好后。一运行程序就重启电脑。。但这时候网络是有的。。先谢谢了。。


import os
import time

restart = True  
shutdown = False

def check_network():
    os.system("ping -n 10 www.baidu.com")
    if os.system("ipconfig | findstr \"字符串\"") == 0:
        return True
    else:
        return False

while True:
    if not check_network():  
        if restart:
            os.system("shutdown /r /t 0")  
            print("检测到网络断开,正在自动重启...")
            restart = False  
            shutdown = True  
        elif shutdown:
            time.sleep(60*5)  
            os.system("shutdown /s /t 0")  
            print("网络5分钟内仍未恢复,正在自动关闭...")
            shutdown = False  
            
    time.sleep(10)

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

lmyx2008 发表于 2023-5-26 15:38
代码有问题,shutdown应放在check_network函数中,并定义restart和shutdown变量,while循环调用check_network函数进行检测,若发现网络断开,则重启电脑。重启五分钟后,如果网络仍然不可用,则关闭电脑。另外,应添加time.sleep函数,循环检测网络状况,以免电脑运行太快而出现错误。修改后的代码如下:

import os
import time

restart = False
shutdown = False

def check_network():
    os.system("ping -n 10 www.baidu.com")
    if os.system("ipconfig | findstr \"字符串\"") == 0:
        return True
    else:
        if restart:
            os.system("shutdown /r /t 0")  
            print("检测到网络断开,正在自动重启...")
            restart = False  
            shutdown = True  
        elif shutdown:
            time.sleep(60*5)  
            os.system("shutdown /s /t 0")  
            print("网络5分钟内仍未恢复,正在自动关闭...")
            shutdown = False
          return False

while True:
    if not check_network():  
    else:
        time.sleep(10)

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
明天星期六 + 1 + 1 谢谢@Thanks!

查看全部评分

wkdxz 发表于 2023-5-26 16:23
每10秒检测一次网络,网络不通就重启。

【重启5分钟后在ping网络如果还是不通就关闭电脑。】 这个是不会执行的吧,10秒钟不通就重启一次,怎么会有5分钟以后再关电脑的操作呢。

[Python] 纯文本查看 复制代码
import os
import time


def check_network():
    '''检测网络是否畅通'''
    network_check = os.popen("ping -n 2 baidu.com").read()
    if "TTL=" in network_check:
        return True
    else:
        return False


def restart_pc():
    '''重启'''
    os.system("shutdown /r /t 0")
    print("检测到网络断开,正在自动重启...")


while True:
    # 网络不通就重启
    if not check_network():
        restart_pc()

    time.sleep(10)

免费评分

参与人数 1吾爱币 +2 热心值 +1 收起 理由
明天星期六 + 2 + 1 热心回复!

查看全部评分

 楼主| 明天星期六 发表于 2023-5-26 17:23
wkdxz 发表于 2023-5-26 16:23
每10秒检测一次网络,网络不通就重启。

【重启5分钟后在ping网络如果还是不通就关闭电脑。】 这个是不会 ...

感谢,其主要是电脑的无线网络有时会断网,只要重启下电脑。。就能联上网络。。。随便重启后如果网络不通就考虑是停电了。。这时就关机。。。我在试试改改。。
wkdxz 发表于 2023-5-27 09:10
本帖最后由 wkdxz 于 2023-5-27 09:17 编辑
明天星期六 发表于 2023-5-26 17:23
感谢,其主要是电脑的无线网络有时会断网,只要重启下电脑。。就能联上网络。。。随便重启后如果网络不通 ...

给你一个思路,将最后一次断网的时间写入一个文本(比如:c:\net.txt)

下次运行时,如果网络不通,则将当前时间减去 c:\net.txt 里面的时间,若时间超过6分钟,则直接关机

大概就是这样:

[Python] 纯文本查看 复制代码
import os
import time

net_txt = 'D:/net.txt'
restart_cmd = 'shutdown /r /t 0'
shutdown_cmd = 'shutdown /s /t 0'
max_offline_time = 6 * 60  # 最大离线时间为6分钟


def check_network():
    '''检测网络是否畅通'''
    network_check = os.popen("ping -n 2 baidu.com").read()
    if "TTL=" in network_check:
        return True
    else:
        return False


def restart_pc():
    '''重启'''
    print("检测到网络断开,正在自动重启...")
    os.system(restart_cmd)


def shutdown_pc():
    '''关机'''
    print("网络断开超过6分钟,正在自动关机...")
    os.system(shutdown_cmd)


def get_last_offline_time():
    '''获取上次离线时间'''
    if os.path.exists(net_txt):
        with open(net_txt, 'r') as f:
            last_offline_time = float(f.read())
            return last_offline_time
    else:
        return None


def write_last_offline_time():
    '''写入本次离线时间'''
    with open(net_txt, 'w') as f:
        f.write(str(time.time()))


last_offline_time = get_last_offline_time()
while True:
    # 网络不通
    if not check_network():
        # 判断是否超过6分钟
        if last_offline_time is not None and (time.time() - last_offline_time) > max_offline_time:
            shutdown_pc()
            break
        else:
            restart_pc()
            last_offline_time = time.time()
            write_last_offline_time()
    else:
        # 网络畅通
        if last_offline_time is not None:
            os.remove(net_txt)
        time.sleep(10)
胶州小哥哥 发表于 2023-5-27 18:25
你的代码有一些问题,os.system() 函数在执行完命令后会返回一个状态码,如果命令执行成功,则返回0,否则返回其他非零值。因此,你需要先将命令执行结果保存下来,再判断网络是否正常。例如,可以将检测网络连通性的命令改为:

Copy Code
result = os.system("ping -n 10 www.baidu.com > nul")
if result == 0:
    return True
else:
    return False
另外,你在重启或关闭电脑之前应该先让程序等待一段时间以确保操作系统能够正常地完成相关操作。例如:

Copy Code
os.system("shutdown /r /t 60") # 等待60秒后重启电脑
time.sleep(60) # 等待60秒
os.system("shutdown /s /t 0") # 关闭电脑
最后,你需要注意代码中的字符串匹配部分(即 ipconfig | findstr \"字符串\")。你需要将字串 "字符串" 改为实际需要查找的字符串。另外,由于中文字符可能会出现编码问题,你可以考虑使用英文字符或者使用解码函数进行处理。

完整代码如下所示:

Copy Code
import os
import time

restart = True  
shutdown = False

def check_network():
    result = os.system("ping -n 10 www.baidu.com > nul")
    if result == 0:
        return True
    else:
        return False

while True:
    if not check_network():  
        if restart:
            os.system("shutdown /r /t 60") # 等待60秒后重启电脑
            print("检测到网络断开,正在自动重启...")
            restart = False  
            shutdown = True  
        elif shutdown:
            time.sleep(60*5) # 等待5分钟
            os.system("shutdown /s /t 0") # 关闭电脑
            print("网络5分钟内仍未恢复,正在自动关闭...")
            shutdown = False  
            
    time.sleep(10)

免费评分

参与人数 1吾爱币 +2 热心值 +1 收起 理由
明天星期六 + 2 + 1 热心回复!

查看全部评分

 楼主| 明天星期六 发表于 2023-5-29 11:21
胶州小哥哥 发表于 2023-5-27 18:25
你的代码有一些问题,os.system() 函数在执行完命令后会返回一个状态码,如果命令执行成功,则返回0,否则 ...

感谢~~~我编译好后,把程序弄成开机自动运行。。然后。。把无线网络一断。。电脑就一直重启。。好像不会判断超5分钟不通网就自动关机。。
 楼主| 明天星期六 发表于 2023-6-2 09:03
import time
import subprocess
import logging

logging.basicConfig(filename='网络监控.log', level=logging.INFO)

restart_timeout = 3*60  # 3分钟
shutdown_timeout = 10*60 # 10分钟
restart_time = 0
shutdown_time = 0

def check_network():
    try:
        subprocess.check_call(["ping", "-n", "10", "www.baidu.com"], stdout=subprocess.DEVNULL)
        logging.info('网络连接正常')
        return True
    except subprocess.CalledProcessError:
        logging.info('网络已断开')  
        return False

def restart_pc():
    subprocess.check_call(["shutdown", "/r", "/t", "0"])
    logging.info('网络断开超过%d分钟,正在自动重启...' % restart_timeout/60)
   
def shutdown_pc():
    subprocess.check_call(["shutdown", "/s", "/t", "0"])
    logging.info('网络断开超过%d分钟,正在自动关闭...' % shutdown_timeout/60)

if __name__ == '__main__':            
    while True:
        if check_network():
            restart_time = 0
            shutdown_time = 0
        else:
            restart_time += 10  #每10秒检测一次
            shutdown_time += 10
            if restart_time >= restart_timeout:
                restart_pc()
                restart_time = 0
            elif shutdown_time >= shutdown_timeout:
                shutdown_pc()
                shutdown_time = 0  

        time.sleep(10)

修改成这样。。。设成开机自动运行编译好的程序。。但好像并没有达到效果。。。高手些帮忙在看看~~
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止回复与主题无关非技术内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-4-27 01:39

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表