使用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')
相关推荐
Jiangnan_Cai1 分钟前
Linux 系统 docker 部署 Dify
linux·docker·大模型·dify
李昊哲小课17 分钟前
销售数据可视化分析项目
python·信息可视化·数据分析·matplotlib·数据可视化·seaborn
烛阴27 分钟前
带参数的Python装饰器原来这么简单,5分钟彻底掌握!
前端·python
Two_brushes.1 小时前
【linux网络】深入理解 TCP/UDP:从基础端口号到可靠传输机制全解析
linux·运维·服务器
全干engineer1 小时前
Flask 入门教程:用 Python 快速搭建你的第一个 Web 应用
后端·python·flask·web
FJW0208141 小时前
【Linux】系统引导修复
linux·运维·服务器
nightunderblackcat1 小时前
新手向:Python网络编程,搭建简易HTTP服务器
网络·python·http
李昊哲小课1 小时前
pandas销售数据分析
人工智能·python·数据挖掘·数据分析·pandas
慌糖1 小时前
CentOS 安装 Redis 简明指南
linux·redis·centos
C嘎嘎嵌入式开发1 小时前
python之set详谈
开发语言·python