我不明白为什么当我像这样执行 Python 脚本时它能在控制台中完美运行(运行 1-2 秒):
但是如果我在任务计划程序中运行它(手动或在计划的时间),它会永远运行并最终在 2 小时的时间限制后超时:
这是需要时的脚本,我甚至exit(0)
在最后添加了它以防它挂在那里(通过 FTP 下载所有 zip 文件,根据其修改日期重命名它们,然后在服务器上删除它们):
import ftplib
import os
from pathlib import Path
from datetime import datetime, timezone
# FTP server details
FTP_SERVER = "domain.com"
FTP_USERNAME = "username"
FTP_PASSWORD = "password"
# Directory for downloaded files
LOCAL_DIR = Path(r"G:\Neverland Backups")
# Connect to the FTP server
ftp = ftplib.FTP(FTP_SERVER, FTP_USERNAME, FTP_PASSWORD)
# List all files in the current directory on the server
files = ftp.nlst()
for file in files:
# Check if the file is a .zip file
if file.endswith('.zip'):
# Download the file
local_file = LOCAL_DIR / file
with open(local_file, 'wb') as fp:
ftp.retrbinary('RETR ' + file, fp.write)
# Get the file modification time
modification_time = ftp.sendcmd('MDTM ' + file)
modification_time = datetime.strptime(modification_time[4:], "%Y%m%d%H%M%S")
# Rename the file
renamed_filepath = LOCAL_DIR / f"Neverland_{modification_time.strftime('%Y-%m-%d_%H.%M.%S')}.zip"
(LOCAL_DIR / file).rename(renamed_filepath)
# Convert the modification time to local timezone
modification_time = modification_time.replace(tzinfo=timezone.utc).astimezone(tz=None)
# Set the file's modification time
timestamp = modification_time.timestamp()
os.utime(renamed_filepath, (timestamp, timestamp))
# Delete the original file on the server
ftp.delete(file)
# Close the connection
ftp.quit()
exit(0)
顺便说一句,我还尝试了 Windows 的“运行”命令C:\Users\Administrator\AppData\Local\Programs\Python\Python312\python.exe "C:\scripts\download-neverland-backups.py"
,脚本窗口打开、执行然后关闭。