Windows批处理文件(.bat文件和.cmd文件)介绍以及简单使用_windows批处理文件是什么意思_Gary的面包屑小道的博客-CSDN博客

[toc]

通过bat实现博客自动上传

bat基础语法

echo:显示信息

1
echo hello   //在终端打印hello

@echo off

Windows下的bat文件的@echo off 作用?_五山口老法师的博客-CSDN博客

命令叫做“回显”

添加上这条语句后,就不会将文件内容打印到终端上.

@echo off表示执行了这条命令后关闭所有命令(包括本身这条命令)的回显。

@的作用就是关闭其后命令的回显。

而echo off命令则表示关闭其他所有命令(不包括本身这条命令)的回显。

1
2
3
4
5
6
7
8
9
@ECHO OFF
ECHO hello1
ECHO hello12
ECHO hello1234
ECHO hello12345
ECHO hello123456
ECHO Randolfluo

PAUSE

修改文件内容,去掉@符号

1
2
3
4
5
6
7
8
9
10
ECHO OFF
ECHO hello1
ECHO hello12
ECHO hello1234
ECHO hello12345
ECHO hello123456
ECHO Randolfluo


PAUSE
1
2
3
4
5
6
7
8
::ECHO OFF     //注释掉ECHO OFF 指令
ECHO hello1
ECHO hello12
ECHO hello1234
ECHO hello12345
ECHO hello123456
ECHO Randolfluo
PAUSE

博客便捷管理批处理文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@ECHO OFF
cd C:\Users\RandolfluoPC\Desktop\randolfluoblog
color 3
ECHO ##########----------~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Randolfluo ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~----------##########
ECHO.
ECHO.
:again
echo ---------------------------------------
echo number = s Local generation
echo number = gd Upload to github
echo number = others exit
echo ---------------------------------------
echo please enter your choice:

set /p num=
if "%num%"=="s" (
start http://localhost:4000/
hexo s
PAUSE
)
if "%num%"=="gd" (
hexo g && hexo d
PAUSE
)


通过python实现图床图库转本地图库

通过一段时间的摸索,发现将图片插入在本地目录即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import os
import re
from datetime import datetime

def normalize_date(date_str):
"""
标准化日期格式:
1. 移除单引号或双引号
2. 确保月份和日期是两位数
3. 确保使用连字符作为分隔符
"""
# 移除引号
date_str = date_str.strip("'\"")

try:
# 解析日期字符串(支持单个数字的月份和日期)
date_parts = re.split('[-/]', date_str)
year, month, day = map(int, date_parts)

# 格式化为标准格式 (YYYY-MM-DD)
return f"{year:04d}-{month:02d}-{day:02d}"
except (ValueError, IndexError):
return None

def update_markdown_file(file_path):
# 读取文件内容
with open(file_path, 'r', encoding='utf-8') as file:
content = file.readlines()

# 匹配 date: 行,支持引号和单个数字的月份/日期
date_pattern = re.compile(r'date:\s*[\'"]*(\d{4}[-/]\d{1,2}[-/]\d{1,2})[\'"]*')
updated_pattern = re.compile(r'updated:\s*')

# 首先找到 date 值
date_value = None
for line in content:
match = date_pattern.search(line.strip()) # 先去除行首尾的空格
if match:
raw_date = match.group(1)
date_value = normalize_date(raw_date)
if date_value: # 确保日期格式化成功
break

# 如果找到了有效的 date 值,则更新 updated 字段
if date_value:
for i, line in enumerate(content):
if updated_pattern.search(line.strip()): # 先去除行首尾的空格
# 保持原有的缩进
leading_spaces = re.match(r'^\s*', line).group(0)

# 打印修改信息
print(f"\n文件: {file_path}")
print(f"找到的date值: {date_value}")
print(f"修改前updated行: {line.strip()}")

# 使用 date 值更新 updated 字段,保持原有缩进
content[i] = f'{leading_spaces}updated: {date_value}\n'
print(f"修改后updated行: {content[i].strip()}")
break

# 写回文件
with open(file_path, 'w', encoding='utf-8') as file:
file.writelines(content)
else:
print(f"\n文件: {file_path} 中未找到有效的date字段")

def process_directory(directory):
"""
处理目录下的所有markdown文件
"""
for root, _, files in os.walk(directory):
for file in files:
if file.lower().endswith(('.md', '.markdown')):
file_path = os.path.join(root, file)
update_markdown_file(file_path)

if __name__ == '__main__':
current_dir = os.getcwd()
print(f"开始处理目录: {current_dir}")
process_directory(current_dir)
print("处理完成!")

gallery相关

脚本写入gallery的img目录然后写入index.md文件,并生成url链接

  • 需要先安装pillow库,

    1
    pip install pillow
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import os
from PIL import Image
import re

def process_images():
# 支持的图片格式
image_formats = ('.jpg', '.jpeg', '.png', '.webp', '.heic', '.svg', '.tiff', '.tif', '.bmp', '.dpx', '.exr')
gif_format = ('.gif',)
url = "https://randolfluo.top/album/wallpaper/img/"

# 检查img子目录是否存在
img_dir = os.path.join(os.path.dirname(__file__), 'img')
if not os.path.exists(img_dir) or not os.path.isdir(img_dir):
print(f"Error: Directory '{img_dir}' does not exist!")
return

# 初始化计数器
img_counter = 1
gif_counter = 1
gallery_content = ["{% gallery %}"] # 初始化画廊内容
url_links = [] #初始化url链接

# 处理img目录中的文件
for filename in sorted(os.listdir(img_dir)): # sorted for consistent ordering
filepath = os.path.join(img_dir, filename)
if not os.path.isfile(filepath):
continue

try:
name, ext = os.path.splitext(filename)
ext = ext.lower()

# 处理GIF文件(保留原格式)
if ext in gif_format:
# 确保文件名唯一
while True:
new_filename = f"gif_{gif_counter}.gif"
new_filepath = os.path.join(img_dir, new_filename)
if not os.path.exists(new_filepath):
break
gif_counter += 1

os.rename(filepath, new_filepath)
print(f'{filename} -> {new_filename}')
gallery_content.append(f"![](./img/{new_filename})")
url_links.append("- " + url + new_filename)
gif_counter += 1

# 处理其他图片文件(转为PNG)
elif ext in image_formats:
# 确保文件名唯一
while True:
new_filename = f"img_{img_counter}.png"
new_filepath = os.path.join(img_dir, new_filename)
if not os.path.exists(new_filepath):
break
img_counter += 1

with Image.open(filepath) as img:
# 处理透明通道
if img.mode in ('RGBA', 'P'):
img = img.convert('RGB')
img.save(new_filepath, 'PNG')

if filepath != new_filepath: # 避免删除新文件
os.remove(filepath)
print(f'{filename} -> {new_filename}')
gallery_content.append(f"![](./img/{new_filename})")
url_links.append("- " + url + new_filename)
img_counter += 1

except Exception as e:
print(f"Error processing {filename}: {str(e)}")
continue

# 结束画廊标记
gallery_content.append("{% endgallery %}")

# 读取并更新index.txt
index_file = os.path.join(os.path.dirname(__file__), 'index.md')
try:
# 读取现有内容
if os.path.exists(index_file):
with open(index_file, 'r', encoding='utf-8') as f:
content = f.read()
# 删除旧的画廊内容
pattern = re.compile(r'{%\s*gallery\s*%}.*?{%\s*endgallery\s*%}', re.DOTALL)
cleaned_content = re.sub(pattern, '', content)
else:
cleaned_content = ''

# 写入新内容
with open(index_file, 'w', encoding='utf-8') as f:
f.write(cleaned_content.strip() + '\n\n' + '\n'.join(gallery_content))

except Exception as e:
print(f"Error writing to {index_file}: {str(e)}")

url_path = os.path.join(os.path.dirname(__file__), 'url.txt')

try:
with open(url_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(url_links))
print("URL links have been saved to url.txt")
except Exception as e:
print(f"Error writing to url.txt: {str(e)}")


if __name__ == "__main__":
process_images()