MacOS 使用命令解压 rar 文件

360 阅读1分钟

RAR 是一种专利文件格式,RAR 的解码器是开源的,但是编码器是有版权费的。所以你能看到 Mac 上几乎所有解压缩 App 都能解压 RAR 文件,但是不能把文件压缩成 RAR

需求:在Mac OS上解压rar文件
参考:superuser.com/questions/5…

安装 rar 命令

# 安装 unrar
brew install unrar 

# 安装后可以查看位置
whereis unrar
unrar: /opt/homebrew/bin/unrar

# 列出文件内容
unrar l ./video_concentrate.rar 

# 解压缩到当前目录
unrar x video_concentrate.rar ./

批量解压 rar

暂未找到批量解压 rar 的原生命令,写个 python 吧:

import os

if __name__ == '__main__':
    input_ok = False
    print('注:此程序适用于批量解压,如果解压单个文件,请使用 unrar x [file_name]')
    hint_str = '请输入批量解压目录位置: '
    while not input_ok:
        dir_path = input(hint_str)
        # Python是可以解析带空格的路径的,但是:
        # 在 MacOS下,如果路径有空格,并且是直接把目录拖入命令行,os系统会把空格转成 [空格]
        # 比如 'Application Support' 会被转成 'Application\ Support'
        # https://stackoverflow.com/questions/36555950/spaces-in-directory-path-python
        dir_path = dir_path.replace('\ ', ' ')

        # 严谨一些把最左和最右空格去掉, 从命令行拖动一个目录进入最后会多带一个空格
        dir_path = os.path.join(dir_path).strip()
        if not os.path.isdir(dir_path):
            hint_str = '输入不合法,请重新输入批量解压目录位置: '
        else:
            input_ok = True

    # os.chdir(dir_path)
    for file_name in os.listdir(dir_path):
        # command = f'os.chdir({dir_path})'
        # chdir = os.system(command)
        # command = f'open {dir_path}'
        # os.system(command)
        dest_dir = os.path.join(dir_path, '__unrar_dir')
        if not os.path.exists(dest_dir):
            os.makedirs(dest_dir) # 创建一个目录,所所有
        if file_name.endswith('.rar'):
            file_path = os.path.join(dir_path, file_name)
            command = f"unrar x -o+ '{file_path}' '{dest_dir}'"
            result = os.system(command)
            if result == 0:
                print(f'解压:{file_name} 成功')
            else:
                print(f'解压:{file_name} 失败')

导出可执行文件

image.png

然后双击运行,拖入目录即可(目录中放入一批.rar文件)