Post

Codes to solve small problem

##

###

递归地打印目录树:

1
2
3
4
5
6
7
8
9
10
def dfs_showdir(path, depth):
    if depth == 0:
        print("root:[" + path + "]")

    for item in os.listdir(path):
        newitem = path + '/' + item
        if not os.path.isfile(newitem):
            print("| " * depth + "+--" + item)
            
            dfs_showdir(newitem, depth +1) ## if os.path.isdir(newitem):

命令行(Linux)创建名为filename的Python文件:

1
touch filename.py

装饰器 @dataclass用于定义一个数据类,无需定义初始化函数__init__即可完成成员属性的赋值;装饰器 @classmethod 的作用:可以在class内实例化class,用来为class创建一些预处理的实例;参考链接

re.sub(pattern, replace, content)表示利用正则表达式来替换原string的部分内容,pattern表示匹配模式,replace表示替换后的内容,content表示要被替换的原文本内容。 举个正则表达式的使用例子:中括号 [] 表示一个字符集, ^在字符集中放在首位意味着取反, 星号*是表示任意次数地匹配之前的字符或组字符集的量词,反斜杠\是转义字符,因此[^\n]*表示匹配任意次数地不是换行符的字符

re.escape() 是一个方便的工具,可以确保路径被视为普通文本,而不是正则表达式的特殊符号。这在路径包含特殊字符时特别有用(例如正则表达式中的 .、*、\ 等)

在 Python 中多线程执行 .bat 文件可以通过 threading 模块实现。每个线程执行一个独立的批处理文件,可以并行运行多个文件。下面是一个使用模块 threadingsubprocess来多线程批处理文件的伪代码示范:

1
2
3
4
5
6
7
8
9
10
11
12
13
import threading
import subprocess

threads = []
for batch_file in batch_files:
    thread = threading.Thread(target = run_batch_file, args = (batch_file, ))
    threads.append(thread)
    thread.start()

for thread in threads:
    thread.join()

print("All batch files have completed execution.")

在上述例子中,target表示要执行的函数,args以元组的形式向target传入参数;threading.Thread表示创建一个独立的线程,start()表示方法启动线程,join() 方法表示等待线程完成,保证主线程在继续执行之前等待所有子线程执行完毕,下面看用于执行给定的命令或脚本的方法subprocess.run的一些参数:

  • shell=True: 这个参数允许你在 Windows 上执行批处理文件。
  • check=True: 设置该参数会在批处理文件返回非零退出代码时抛出 CalledProcessError。
  • stdout=subprocess.DEVNULL: 将标准输出重定向到 DEVNULL,丢弃所有正常输出。
  • stderr=subprocess.DEVNULL: 将标准错误输出重定向到 DEVNULL,丢弃所有错误输出。

加载json文件以及修改例子如下,读取json文件的特定字典然后修改特定键名的内容:

1
2
3
4
5
6
7
8
9
10
11
with open(json_path, 'r', encoding='utf-8') as json_file:
    data = json.load(json_file)
    
height = data['sensor']['height']
width = data['sensor']['width']
x = int((height - crop_height) // 2)
y = int((width - crop_width) // 2)
data['sensor']['image_crop_info'] = [x, y, crop_height, crop_width]

with open(json_path, 'w', encoding='utf-8') as json_file:
    json.dump(data, json_file, ensure_ascii=False, indent=4)
This post is licensed under CC BY 4.0 by the author.

Trending Tags