#!/usr/bin/python
# coding: utf-8

#
# usage: python me.py [-h] -t tag1 -t tag2 file1 file2 ...
#

import sys, os, argparse
from subprocess import Popen, PIPE

applescript = r&#39;&#39;&#39;
use AppleScript version &#34;2.7&#34;
use scripting additions
use framework &#34;Foundation&#34;

property OSX : current application
property nil : missing value

on run (argv)
    set n to item 1 of argv

    set argv to items 2 thru end of argv
    set tags to my uniq(items 1 thru n of argv)
    set res to &#34;&#34;

    repeat with f in items (n + 1) thru end of argv
        set fpath to contents of f
        set res to res &amp; my set_tags(tags, fpath) &amp; linefeed
    end repeat
    
    return res
end run

on set_tags(tags, fpath)
    set furl to OSX&#39;s NSURL&#39;s fileURLWithPath:fpath
    set tkey to OSX&#39;s NSURLTagNamesKey
    set tags to OSX&#39;s NSArray&#39;s arrayWithArray:tags

    set {res, err} to furl&#39;s setResourceValue:tags forKey:tkey |error|:(reference)

    if (res) then
        return fpath
    else
        return fpath &amp; &#34;: &#34; &amp; err&#39;s localizedDescription as text
    end if
end set_tags

on uniq(tags)
    set new_tags to {}
    repeat with t in tags
        if contents of t is not in new_tags then
            set end of new_tags to contents of t
        end if
    end repeat
    return new_tags
end uniq
&#39;&#39;&#39;[1:-1]

def set_tags(tags, args):
    cmd = [&#39;osascript&#39;, &#39;-e&#39;, applescript, &#39;--&#39;, str(len(tags))] + tags + args
    proc = Popen(cmd, stdin = None, stdout = PIPE, stderr = PIPE)

    out, err = proc.communicate()

    if proc.returncode != 0:
        sys.exit(err.rstrip())

    return out.rstrip()

def parse_arguments():
    parser = argparse.ArgumentParser(
        description = &#39;set tags&#39;,
        usage = &#39;python %(prog)s [-h] -t tag1 -t tag2 -t tag3 file1 file2 ...&#39;
    )

    parser.add_argument(
        &#39;-t&#39;, &#39;--tag&#39;, required = True,
        action  = &#39;append&#39;,
        dest    = &#39;tags&#39;,
        metavar = &#39;tags&#39;,
        help    = &#39;specify tag name&#39;
    )

    parser.add_argument(
        &#39;files&#39;,
        nargs = &#39;+&#39;,
        help  = &#39;file1 file2 ...&#39;
    )

    args = parser.parse_args()

    return (args.tags, args.files)

def main():
    if len(sys.argv) &lt; 2:
        sys.exit(&#39;usage: python {0} file1 file2 ...&#39;.format(__file__))

    tags, args = parse_arguments()

    tags = [x for x in tags if x]
    args = [x for x in args if os.path.exists(x)]

    res = set_tags(tags, args)
    print(res)

main()
