鱼C论坛

 找回密码
 立即注册
查看: 2609|回复: 8

[Python] 我想实现局域网自动更新文件功能

[复制链接]
发表于 2023-10-26 21:05:17 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
新手,写了个程序,编译后的Main程序在我本机里
想加个自动更新的功能,点登录后就会自动下载保持程序一致性
但我从来没接触过目前毫无头绪
请问是用requests库吗?具体应该怎么实现?
有人做过相关功能可以指点指点吗

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-10-26 21:05:29 | 显示全部楼层
是的,你可以使用Python的requests库来实现局域网自动更新文件的功能。具体步骤如下:

1. 首先,你需要确定文件的下载地址。可以是一个HTTP或FTP链接,或者是一个局域网内部的共享文件夹路径。

2. 使用requests库发送HTTP请求,下载文件。你可以使用 requests.get() 方法来发送GET请求,并将文件保存到本地。

下面是一个简单的示例代码:

  1. import requests

  2. def download_file(url, save_path):
  3.     response = requests.get(url)
  4.     with open(save_path, 'wb') as file:
  5.         file.write(response.content)

  6. # 调用示例
  7. url = 'http://example.com/file.txt'  # 文件的下载地址
  8. save_path = 'path/to/save/file.txt'  # 文件保存的路径
  9. download_file(url, save_path)
复制代码


在这个示例中, download_file() 函数接受文件的下载地址和保存路径作为参数,使用 requests.get() 方法下载文件,并使用 open() 函数将文件保存到本地。

你可以根据自己的需求,将上述代码集成到你的程序中。当用户登录后,调用 download_file() 函数来下载文件,以保持程序的一致性。

请注意,这只是一个简单的示例,你可能还需要处理一些异常情况,例如网络连接错误或文件不存在等。你可以根据具体需求进行相应的错误处理。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-10-26 21:09:57 | 显示全部楼层
isdkz 发表于 2023-10-26 21:05
是的,你可以使用Python的requests库来实现局域网自动更新文件的功能。具体步骤如下:

1. 首先,你需要 ...

这是AI的,下午我已经尝试过AI,解释的不是非常通透。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-10-26 21:23:51 | 显示全部楼层
可以把项目开源到 GitHub,然后每次更新都调用 git pull
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-10-26 21:43:23 | 显示全部楼层
歌者文明清理员 发表于 2023-10-26 21:23
可以把项目开源到 GitHub,然后每次更新都调用 git pull

我们是纯内网,这个方法可能行不通吧
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-10-27 17:03:05 | 显示全部楼层
hejialiangya 发表于 2023-10-26 21:43
我们是纯内网,这个方法可能行不通吧

确实有点麻烦了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-10-31 21:08:42 | 显示全部楼层

学了2天学了点皮毛,打算用通过ftp协议来实现。
瞎整了一段代码,但是运行起来有点问题,请大佬帮我看看


  1. from ftplib import FTP
  2. import os
  3. import sys
  4. import time
  5. import socket

  6. class MyFTP():
  7.     # 初始化FTP客户端
  8.     def __init__(self, host, port=21):
  9.         self.host = host
  10.         self.port = port
  11.         self.ftp = FTP()
  12.         # 重新设置下编码方式
  13.         self.ftp.encoding = 'gbk'
  14.         self.log_file = open("log.txt", "a")
  15.         self.file_list = []

  16.     # FTP客户端登录
  17.     def login(self, username, password):
  18.         try:
  19.             timeout = 60
  20.             socket.setdefaulttimeout(timeout)
  21.             # 0主动模式 1 #被动模式
  22.             self.ftp.set_pasv(True)
  23.             # 打开调试级别2,显示详细信息
  24.             # self.ftp.set_debuglevel(2)

  25.             self.debug_print('开始尝试连接到 %s' % self.host)
  26.             self.ftp.connect(self.host, self.port)
  27.             self.debug_print('成功连接到 %s' % self.host)

  28.             self.debug_print('开始尝试登录到 %s' % self.host)
  29.             self.ftp.login(username, password)
  30.             self.debug_print('成功登录到 %s' % self.host)

  31.             self.debug_print(self.ftp.welcome)
  32.         except Exception as error:
  33.             self.deal_error("FTP 连接或登录失败 ,错误描述为:%s" % error)
  34.             pass

  35.     #用于下载前判断远程文件和本地文件大小是否一致
  36.     def is_same_size(self, local_file, remote_file):
  37.         try:
  38.             remote_file_size = self.ftp.size(remote_file)
  39.         except Exception as error:
  40.             # self.debug_print("is_same_size() 错误描述为:%s" % error)
  41.             remote_file_size = -1

  42.         try:
  43.             local_file_size = os.path.getsize(local_file)
  44.         except Exception as error:
  45.             # self.debug_print("is_same_size() 错误描述为:%s" % error)
  46.             local_file_size = -1

  47.         self.debug_print('local_file_size:%d  , remote_file_size:%d' % (local_file_size, remote_file_size))
  48.         if remote_file_size == local_file_size:
  49.             return 1
  50.         else:
  51.             return 0

  52.     #从ftp下载单个文件
  53.     def download_file(self, local_file, remote_file):
  54.         self.debug_print("download_file()---> local_path = %s ,remote_path = %s" % (local_file, remote_file))

  55.         if self.is_same_size(local_file, remote_file):
  56.             self.debug_print('%s 文件大小相同,无需下载' % local_file)
  57.             return
  58.         else:
  59.             try:
  60.                 self.debug_print('>>>>>>>>>>>>下载文件 %s ... ...' % local_file)
  61.                 buf_size = 1024
  62.                 file_handler = open(local_file, 'wb')
  63.                 self.ftp.retrbinary('RETR %s' % remote_file, file_handler.write, buf_size)
  64.                 file_handler.close()
  65.             except Exception as error:
  66.                 self.debug_print('下载文件出错,出现异常:%s ' % error)
  67.                 return

  68.     #从远程目录下载多个文件到本地目录
  69.     def download_file_tree(self, local_path, remote_path):
  70.         print("download_file_tree()--->  local_path = %s ,remote_path = %s" % (local_path, remote_path))
  71.         try:
  72.             self.ftp.cwd(remote_path)
  73.         except Exception as error:
  74.             self.debug_print('远程目录%s不存在,继续...' % remote_path + " ,具体错误描述为:%s" % error)
  75.             return

  76.         if not os.path.isdir(local_path):
  77.             self.debug_print('本地目录%s不存在,先创建本地目录' % local_path)
  78.             os.makedirs(local_path)

  79.         self.debug_print('切换至目录: %s' % self.ftp.pwd())

  80.         self.file_list = []
  81.         # 方法回调
  82.         self.ftp.dir(self.get_file_list)

  83.         remote_names = self.file_list
  84.         self.debug_print('远程目录 列表: %s' % remote_names)
  85.         for item in remote_names:
  86.             file_type = item[0]
  87.             file_name = item[1]
  88.             local = os.path.join(local_path, file_name)
  89.             if file_type == 'd':
  90.                 print("download_file_tree()---> 下载目录: %s" % file_name)
  91.                 self.download_file_tree(local, file_name)
  92.             elif file_type == '-':
  93.                 print("download_file()---> 下载文件: %s" % file_name)
  94.                 self.download_file(local, file_name)
  95.             self.ftp.cwd("..")
  96.             self.debug_print('返回上层目录 %s' % self.ftp.pwd())
  97.         return True

  98.     # 从本地上传文件到ftp
  99.     def upload_file(self, local_file, remote_file):
  100.         if not os.path.isfile(local_file):
  101.             self.debug_print('%s 不存在' % local_file)
  102.             return

  103.         if self.is_same_size(local_file, remote_file):
  104.             self.debug_print('跳过相等的文件: %s' % local_file)
  105.             return

  106.         buf_size = 1024
  107.         file_handler = open(local_file, 'rb')
  108.         self.ftp.storbinary('STOR %s' % remote_file, file_handler, buf_size)
  109.         file_handler.close()
  110.         self.debug_print('上传: %s' % local_file + "成功!")

  111.     # 从本地上传目录下多个文件到ftp
  112.     def upload_file_tree(self, local_path, remote_path):
  113.         if not os.path.isdir(local_path):
  114.             self.debug_print('本地目录 %s 不存在' % local_path)
  115.             return

  116.         self.ftp.cwd(remote_path)
  117.         self.debug_print('切换至远程目录: %s' % self.ftp.pwd())

  118.         local_name_list = os.listdir(local_path)
  119.         for local_name in local_name_list:
  120.             src = os.path.join(local_path, local_name)
  121.             if os.path.isdir(src):
  122.                 try:
  123.                     self.ftp.mkd(local_name)
  124.                 except Exception as error:
  125.                     self.debug_print("目录已存在 %s ,具体错误描述为:%s" % (local_name, error))
  126.                 self.debug_print("upload_file_tree()---> 上传目录: %s" % local_name)
  127.                 self.upload_file_tree(src, local_name)
  128.             else:
  129.                 self.debug_print("upload_file_tree()---> 上传文件: %s" % local_name)
  130.                 self.upload_file(src, local_name)
  131.         self.ftp.cwd("..")

  132.     def close(self):
  133.         self.debug_print("close()---> FTP退出")
  134.         self.ftp.quit()
  135.         self.log_file.close()

  136.     # 打印日志
  137.     def debug_print(self, s):
  138.         self.write_log(s)

  139.     # 处理错误异常
  140.     def deal_error(self, error):
  141.         log_str = '发生错误: %s' % error
  142.         self.write_log(log_str)
  143.         sys.exit()

  144.     # 记录日志
  145.     def write_log(self, log_str):
  146.         time_now = time.localtime()
  147.         date_now = time.strftime('%Y-%m-%d', time_now)
  148.         format_log_str = "%s ---> %s \n " % (date_now, log_str)
  149.         print(format_log_str)
  150.         self.log_file.write(format_log_str)

  151.     # 获取文件列表
  152.     def get_file_list(self, line):
  153.         file_arr = self.get_file_name(line)
  154.         # 去除  . 和  ..
  155.         if file_arr[1] not in ['.', '..']:
  156.             self.file_list.append(file_arr)

  157.     # 获取文件名
  158.     def get_file_name(self, line):
  159.         pos = line.rfind(':')
  160.         while (line[pos] != ' '):
  161.             pos += 1
  162.         while (line[pos] == ' '):
  163.             pos += 1
  164.         file_arr = [line[0], line[pos:]]
  165.         return file_arr


  166. if __name__ == "__main__":
  167.     my_ftp = MyFTP("130.1.11.70")
  168.     my_ftp.login("xxk", "xxk@2021")
  169.     # 下载单个文件
  170.     # my_ftp.download_file("D:/download", "./update/")
  171.     # 下载目录
  172.     my_ftp.download_file_tree(r"D:\download", "/update/")
  173.     # 上传单个文件
  174.     # my_ftp.upload_file("G:/f/", "/App/")
  175.     # 上传目录
  176.     # my_ftp.upload_file_tree("G:/f/", "/App/")
  177.     my_ftp.close()
复制代码



ftp服务器上有4个文件

                               
登录/注册后可看大图

下载到本地只有1个文件

                               
登录/注册后可看大图

下载文件夹的时候会报错

                               
登录/注册后可看大图

以下是报错日志:

                               
登录/注册后可看大图

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-10-31 21:56:17 | 显示全部楼层
hejialiangya 发表于 2023-10-31 21:08
学了2天学了点皮毛,打算用通过ftp协议来实现。
瞎整了一段代码,但是运行起来有点问题,请大佬帮我看看 ...


好家伙,给我整不会了

参考:
https://www.cnblogs.com/kaituorensheng/p/4480512.html
https://www.jianshu.com/p/8e645e6de8bf
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-10-31 22:03:51 | 显示全部楼层
可以每次连接时服务端发送版本号,一致则进入,不一致则传输最新版本文件,我之前写的聊天室里面有点,就在论坛里面,你觉得麻烦看看这个思路也行
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-27 14:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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