使用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')
相关推荐
D4c-lovetrain20 小时前
Linux个人心得25 (mysql⑤)
linux·运维·mysql
菜_小_白20 小时前
RTP协议收发组件开发
linux·网络·c++
yanghuashuiyue20 小时前
langchain AI应用框架研究【前端-篇二】
人工智能·python·langchain
Deitymoon20 小时前
linux——UDP编程
linux·网络·udp
简单点了20 小时前
mac安装wireshark
测试工具·macos·wireshark
Amelio_Ming20 小时前
linux内存管理-页面回收之内核线程 kswapd (二)
linux·服务器
维基框架21 小时前
WIKI 知识库系统 — 项目框架全解析
python
Lenyiin21 小时前
Python数据类型与运算符:深入理解Python世界的基石
java·开发语言·python
小江的记录本21 小时前
【大语言模型】大语言模型——核心概念(预训练、SFT监督微调、RLHF/RLAIF对齐、Token、Embedding、上下文窗口)
java·人工智能·后端·python·算法·语言模型·自然语言处理
坐吃山猪21 小时前
Python04_序列和字符串
python