使用Python在Windows、Linux、MacOS系统创建快捷方式

一、使用Python在Windows系统创建快捷方式

Windows系统需要安装 winshell

bash 复制代码
pip3 install winshell

使用winshell.CreateShortcut函数来创建快捷方式,有两个参数:path和target,

path:快捷方式文件的路径,

target:快捷方式指向的目标文件路径

python 复制代码
import os
import sys
import platform

def create_shortcut(target, shortcut_location):

    system = platform.system()

    if system == 'Windows':

        # 在Windows下创建快捷方式
        import winshell

        winshell.CreateShortcut(Path=shortcut_location, Target=target, Icon=(target,0))
   
create_shortcut('/root/pictures/airship.png', '/root/pictures/abc.desktop')

二、使用Python在Linux系统创建快捷方式

Linux:需要创建一个桌面入口文件(.desktop文件)来实现快捷方式

python 复制代码
import os
import sys
import platform

def create_shortcut(target, shortcut_location):

    system = platform.system()

    if system == 'linux':
     
        # 在Linux下创建快捷方式/root/pictures
        from pathlib import Path

        # 将target处理完绝对路径
        target = Path(target).resolve()

        with open(shortcut_location, 'w') as f:
            f.write(f'[Desktop Entry]\nType=Link\nURL={target}\nName={target.name}\n')

create_shortcut('/root/pictures/airship.png', '/root/pictures/abc.desktop')

三、使用Python在MacOS系统创建快捷方式

MacOS:需要创建一个bash脚本实现快捷方式功能,需要使用chmod函数让该脚本可执行

python 复制代码
import os
import sys
import platform

def create_shortcut(target, shortcut_location):

    system = platform.system()

    if system == 'Darwin':

        # 在macOS下创建快捷方式
        from pathlib import Path

        # 将target处理完绝对路径
        target = Path(target).resolve()

        with open(shortcut_location, 'w') as f:
            f.write(f'#!/bin/sh\nopen "{target}"\n')

        os.chmod(shortcut_location, 0x755)

create_shortcut('/root/pictures/airship.png', '/root/pictures/abc.desktop')
相关推荐
吴佳浩 Alben2 分钟前
一文讲透推理引擎性能指标:TTFT、TPOT、KV命中率、并发,到底对应 vLLM / SGLang 的哪个参数?
人工智能·python·语言模型·架构·ai编程·vllm·sglang
用户298698530143 分钟前
Python 实现 Word 转 XPS、PostScript 与 OFD 格式
后端·python·api
wuminyu15 分钟前
ZGC染色指针在虚拟线程stackChunkOop上的并发屏障全景分析
java·linux·c语言·jvm·c++
Khalil三省25 分钟前
Mac怎么显示桌面歌词?Apple Music和Spotify也能开
macos·开源·效率工具·音乐
Patrick在香港27 分钟前
你写的「比较 token」函数,正在用 36 纳秒泄露密码:时序攻击实测
python·安全·标准库·时序攻击·常量时间
蜗牛互联网27 分钟前
Python Agent 工具调用:审批令牌、参数白名单和累计预算
java·开发语言·人工智能·windows·后端·python
硅基手札1 小时前
【I2C 技术系列 11】I2C Linux 驱动框架
linux·驱动开发·stm32·单片机·嵌入式硬件·mcu·计算机外设
imDwAaY1 小时前
程序里的地址是真实内存地址吗?从虚拟内存到地址转换
java·linux·服务器
INGNIGHT1 小时前
486. 预测赢家(博弈dp/区间dp)
linux·c++
维克兜率天1 小时前
【维克】统计套利:寻找市场的“定价误差“
人工智能·python·算法