Jump to content
dunce

Add "copy file" in file action

Recommended Posts

Hello guys,

 

Im trying to figure out how to add a "copy file" option in file action list, anybody knows how?

 

The reason, I do have a lot of apps support directly paste in files, to send/share/upload/sync whatever different kinds of functions. I found it really handy to just copy files I need, then paste them in the app windows. both "copy to" and "copy file path" works in a different way, just need to copy the file it self. 

 

So, anyone help is really appreciated :D

 

edit: this just came into my mind: could there also be a "preview" in this option list? that would be really speed things up, at least for me:-)

Edited by dunce

Share this post


Link to post

You can copy a file to the clipboard with AppleScript. This script will work on the command line and copy the first filepath passed to it to the clipboard:

on run (argv)
    set the clipboard to POSIX file (POSIX path of ((POSIX file (first item of argv)) as alias))
end run

I don't think it's possible to copy more than one file to the clipboard without messing around with Cocoa.
 
Specifically, I believe you need to pass an NSArray of NSURLs to [NSPasteboard writeObjects:someArray].

Share this post


Link to post

I had a dig through some old, similar scripts and came up with this. It will work as a command-line script or pasted into the Script box of an Alfred Run Script action (set Language to Python).
 

#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2016 deanishe@deanishe.net
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2016-01-11
#

"""
Copy files to OS X clipboard.

Works as CLI script or Alfred File Action script.
"""

from __future__ import print_function, absolute_import

import os
import sys

from AppKit import NSPasteboard
from Foundation import NSURL


def paths2urls(paths):
    """Convert `paths` into a list of NSURLs.

    Args:
        paths (list): Absolute filepaths.

    Returns:
        list: List of NSURL objects corresponding to `paths`.
    """
    urls = []
    for p in paths:
        p = unicode(p, 'utf-8')
        url = NSURL.fileURLWithPath_(p)
        urls.append(url)
    return urls


def copy2pasteboard(items):
    """Place `items` on the general pasteboard.

    `items` *must* contain NSURLs.

    Args:
        items (list): List of NSURL objects.
    """
    pb = NSPasteboard.generalPasteboard()
    pb.clearContents()
    pb.writeObjects_(items)


def filepaths_from_argv():
    """Read filepaths from command-line arguments.

    Returns:
        list: Absolute paths read from ARGV.
    """
    return [os.path.abspath(p) for p in sys.argv[1:] if os.path.exists(p)]


def filepaths_from_alfred():
    """Return filepaths based on Alfred's { query } text macro.

    Parse Alfred's tab-separated list of paths.

    Returns:
        list: Absolute paths passed by Alfred.
    """
    filepaths = "{query}".split('\t')
    filepaths = [f for f in filepaths if f.strip() and os.path.exists(f)]
    return filepaths


def main():
    """Run script."""
    if os.getenv('alfred_version'):  # Running in Alfred
        filepaths = filepaths_from_alfred()
    else:  # Assume CLI
        filepaths = filepaths_from_argv()
    urls = paths2urls(filepaths)
    copy2pasteboard(urls)


if __name__ == '__main__':
    main()

Just attach this to a File Action (it works with multiple files).

Edited by deanishe

Share this post


Link to post

Thanks @deanishe and @raguay.customct 

Dean did get that right, it act like when you copy a file then paste it in evernote app, the file got attached in that note. just we already have that with evernote workflow, but the idea/need is same here, copy a file/some files (I think 1 file solve the problem since for me that's most my scenario) itself then paste in other apps, not copy it to somewhere else, not copy its path.

will try the python code later. just one quick noob question: how should it be applied? Pasted the code into text editor, saved as a .py file, then what?  always envy you guys who can code, seriously. :D

Share this post


Link to post

To use it in Alfred, you must paste it in the Script box of a Run Script Action (Language = /usr/bin/python, natch).

Edited by deanishe

Share this post


Link to post

To use it in Alfred, you must paste it in the Script box of a Run Script Action (Language = /usr/bin/python, natch).

 

just came back to say thank you, got it work followed by your guide, thx for the kind help :-)

Share this post


Link to post

Hi,

I would like to achieve the same goal. I tried script listed above but it doesn't work. In more detail it work when I select some file in Finder, then open Alfred's file actions via hotkey and use this action. However, it doesn't work when I search this file from Alfred and then use the file action. Do you have any ideas how to fix this?

I use Alfred 3 with most updated El Capitan.  

Share this post


Link to post

Below is a message from debugger 

Starting debug for 'copy file'

[2016-08-05 13:44:08][ERROR: action.script] Traceback (most recent call last):
  File "/Users/michaljurewicz/Library/Caches/com.runningwithcrayons.Alfred-3/Workflow Scripts/1407962B-1D86-40A0-8BA8-3B9FA8C784D1", line 22, in <module>
    from AppKit import NSPasteboard
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/AppKit/__init__.py", line 8, in <module>
    import objc
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/objc/__init__.py", line 39, in <module>
    from objc._properties import *
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/objc/_properties.py", line 7, in <module>
    from copy import copy as copy_func
  File "/Users/michaljurewicz/Dropbox (Osobiste)/Aplikacje/Alfred/Alfred.alfredpreferences/workflows/user.workflow.65F705C6-835B-4654-8FDA-2B714275B266/copy.py", line 22, in <module>
    from AppKit import NSPasteboard
ImportError: cannot import name NSPasteboard

However, when I tried use this with file selected in Finder it work but still generate similar error:

[2016-08-05 13:46:25][ERROR: action.script] Traceback (most recent call last):
  File "/Users/michaljurewicz/Library/Caches/com.runningwithcrayons.Alfred-3/Workflow Scripts/1407962B-1D86-40A0-8BA8-3B9FA8C784D1", line 22, in <module>
    from AppKit import NSPasteboard
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/AppKit/__init__.py", line 8, in <module>
    import objc
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/objc/__init__.py", line 39, in <module>
    from objc._properties import *
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC/objc/_properties.py", line 7, in <module>
    from copy import copy as copy_func
  File "/Users/michaljurewicz/Dropbox (Osobiste)/Aplikacje/Alfred/Alfred.alfredpreferences/workflows/user.workflow.65F705C6-835B-4654-8FDA-2B714275B266/copy.py", line 22, in <module>
    from AppKit import NSPasteboard
ImportError: cannot import name NSPasteboard
Edited by Malauch

Share this post


Link to post

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...