使用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')
相关推荐
JiMoKuangXiangQu3 分钟前
Linux 时间子系统 (1):基础框架概述
linux·timer·时间子系统·timekeeping
傻啦嘿哟4 分钟前
Python实现PDF文档高效转换为HTML文件:从基础到进阶的完整指南
python·pdf·html
天选之女wow4 分钟前
【Hard——Day8】65.有效数字、68.文本左右对齐、76.最小覆盖子串
linux·运维·redis·算法·leetcode
精英的英25 分钟前
【嵌入式Linux开发】如何在Windows上开发Linux ARM版本QT程序
linux·arm开发·windows
咯哦哦哦哦26 分钟前
linux patchelf工具 用法
linux·vscode·编辑器·gcc
努力的小帅26 分钟前
Linux_进程控制(Linux入门到精通)
linux·网络·shell·进程创建·linux入门
睡觉然后上课27 分钟前
如何让虚拟机运行速度翻倍
linux·arm开发·windows
喜欢你,还有大家30 分钟前
DaemonSet && service && ingress的
linux·架构·kubernetes
天下无敌笨笨熊1 小时前
ES作为向量库研究
大数据·python·elasticsearch
数据知道1 小时前
FastAPI项目:从零到一搭建一个网站导航系统
python·mysql·fastapi·python web·python项目