简体   繁体   中英

Store files in clipboard in python (cross-platform)

I'm trying to store a file in the clipboard in windows mac and linux. For ex: running the script will put a file / files in the clipboard and now I can ctrl+v wherever i want to paste the files.

for windows i have written this code in c#:

using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace file2clip
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            StringCollection paths = new StringCollection();
            foreach (string s in args) paths.Add(s);
            Clipboard.SetFileDropList(paths);
        }
    }
}

then implement in python:

import subprocess

def files_to_win_clip(files: tuple):
    subprocess.call(f'file2clip.exe {files}')

For linux i found xclip which allows to copy and paste files but it doesnt go to the default clipboard so I can't paste (with ctrl+v) the file wherever I'm at.

I might need some help on how to make it work on linux and mac.

There are a lot of python modules to do this. One of them is https://pypi.org/project/pyperclip/

The c program in this way is not needed you can read the file in python as text or do all logic that you want and put it in the clipboard.

For full file copy you can use this snippet:

from PyQt4 import QtCore, QtGui

app = QtGui.QApplication([])

data = QtCore.QMimeData()
url = QtCore.QUrl.fromLocalFile('c:\\foo.file')
data.setUrls([url])

app.clipboard().setMimeData(data)

I can't comment but xclip can be used as follows:

$ xclip -selection clipboard [FILES]

This copies the files' text to the clipboard; I'm not sure if this is the behaviour you are looking for though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM