使用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')
相关推荐
天雪浪子7 分钟前
Python入门教程之逻辑运算符
开发语言·python
骄傲的心别枯萎17 分钟前
RV1126 NO.16:通过多线程同时获取H264和H265码流
linux·c++·音视频·rv1126
空灵之海19 分钟前
Ubuntu系统安全合规配置
linux·ubuntu·系统安全·1024程序员节
喜欢你,还有大家22 分钟前
FTP文件传输服务
linux·运维·服务器·前端
张子夜 iiii32 分钟前
实战项目-----在图片 hua.png 中,用红色画出花的外部轮廓,用绿色画出其简化轮廓(ε=周长×0.005),并在同一窗口显示
人工智能·pytorch·python·opencv·计算机视觉
gongzemin36 分钟前
Django入门2--设置数据库 admin
python·django
KimLiu1 小时前
LCODER之Python:使用Django搭建服务端
后端·python·django
czhc11400756631 小时前
LINUX99 centos8:网络 yum配置;shell:while [ $i -ne 5 ];do let i++ done
linux