使用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')
相关推荐
workflower1 小时前
时序数据获取事件
开发语言·人工智能·python·深度学习·机器学习·结对编程
鸠摩智首席音效师2 小时前
linux 系统中 Shutting Down, Restarting, Halting 有什么区别 ?
linux·运维·服务器
CIb0la2 小时前
Linux 将继续不支持 HDMI 2.1 实现
linux·运维·服务器
C++业余爱好者2 小时前
Java 提供了8种基本数据类型及封装类型介绍
java·开发语言·python
德生coding3 小时前
wifi驱动编译出来的驱动文件怎么做strip
linux
鹿鸣天涯3 小时前
Kali Linux 2025.4 发布:桌面环境增强,新增 3 款安全工具
linux·运维·安全
AI Echoes3 小时前
构建一个LangChain RAG应用
数据库·python·langchain·prompt·agent
学习&笔记3 小时前
MTK(系统篇)user版本无法使用setenforce 0命令关闭selinux权限
linux·运维·服务器
派大鑫wink4 小时前
从零到精通:Python 系统学习指南(附实战与资源)
开发语言·python
c骑着乌龟追兔子4 小时前
Day 38 官方文档的阅读
python