使用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')
相关推荐
南棱笑笑生9 分钟前
20251217给飞凌OK3588-C开发板适配Rockchip原厂的Buildroot【linux-5.10】后调通ov5645【只能预览】
linux·c语言·开发语言·rockchip
HyperAI超神经22 分钟前
【vLLM 学习】Prithvi Geospatial Mae
人工智能·python·深度学习·学习·大语言模型·gpu·vllm
逻极24 分钟前
Python MySQL防SQL注入实战:从字符串拼接的坑到参数化查询的救赎
python·mysql·安全·sql注入
赫凯30 分钟前
【强化学习】第一章 强化学习初探
人工智能·python·强化学习
Amewin33 分钟前
window 11 安装pyenv-win管理不同的版本的python
开发语言·python
小鸡吃米…1 小时前
Python编程语言面试问题二
开发语言·python·面试
Sleepy MargulisItG2 小时前
【Linux网络编程】应用层协议:HTTP协议
linux·服务器·网络·http
eve杭2 小时前
AI、大数据与智能时代:从理论基石到实战路径
人工智能·python·5g·网络安全·ai
G31135422732 小时前
Linux 内核设计中的核心思想与架构原则
linux·架构·php
zhuzewennamoamtf2 小时前
Linux内核platform抽象、数据结构、内核匹配机制
linux·运维·数据结构