Skip to content

Instantly share code, notes, and snippets.

@ProbonoBonobo
Last active August 8, 2017 01:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ProbonoBonobo/59071ea680995df6f788fd1dada9eb2d to your computer and use it in GitHub Desktop.
Save ProbonoBonobo/59071ea680995df6f788fd1dada9eb2d to your computer and use it in GitHub Desktop.
Python utility methods for opening files (Mac only)
#!/usr/bin/env python3
""" Some Mac-specific utility methods I have found useful for opening files. Uses mdfind, a built-in command-line
interface to spotlight's desktop cache, so results are usually instantaneous.
Demo:
In [390]: %timeit pprint(conjure('LCD Soundsystem'))
['/Users/kz/Desktop/artists/metacritic/lcd-soundsystem.json',
'/Users/kz/Desktop/artists/metacritic/http:⚡︎⚡︎metacritic.com⚡︎music⚡︎lcd-soundsystem⚡︎lcd-soundsystem⚡︎user-reviews',
'/Users/kz/Desktop/artists/metacritic/http:⚡︎⚡︎www.trouserpress.com⚡︎entry.php?a=lcd_soundsystem',
'/Users/kz/Desktop/artists/metacritic/lcd-soundsystem.pkl',
'/Users/kz/Desktop/directory/artists/LCD Soundsystem.txt',
'/Users/kz/Desktop/artists/test/LCD Soundsystem',
'/Users/kz/dev/github/review/view/content/lcd-soundsystem-dance-yrself-clean',
'/Users/kz/dev/github/review/view/content/lcd-soundsystem-home',
'/Users/kz/dev/github/artists/2598-lcd-soundsystem',
'/Users/kz/dev/github/news/lcd-soundsystem-warn-dont-buy-any-tickets-online']
['/Users/kz/Desktop/artists/metacritic/lcd-soundsystem.json',
(...)
],
(...)
10 loops, best of 3: 59.4 ms per loop
In [391]: resurrect("extracted.out", feeling_lucky=False)
['/Users/kz/dev/pybrary/iter5/extracted.out', '/Users/kz/Desktop/artists/extracted.out', '/Users/kz/dev/pybrary/iter4/extracted.out']
resurrect INFO ['/Users/kz/dev/pybrary/iter5/extracted.out', '/Users/kz/Desktop/artists/extracted.out', '/Users/kz/dev/pybrary/iter4/extracted.out']
Found 3 matches for files named 'extracted.out'
[0] => /Users/kz/dev/pybrary/iter5/extracted.out
[1] => /Users/kz/Desktop/artists/extracted.out
[2] => /Users/kz/dev/pybrary/iter4/extracted.out
Index of the file you'd like to open:
>> 0
resurrect INFO /
resurrect INFO fp is /Users/kz/dev/pybrary/iter4/extracted.out
resurrect DEBUG FileSearchResponse(exists=True, preview='["jackie-o-motherfucker", "earth-sound-system", true, "CMJ", "Earth Sound System is structured with actual musical tracks interspersed between organized chaotic electronica. The attempts at the two different approaches to this type of music come off as undecided and incoherent, yet there is merit in the tracks that actually offer stable grounds for musical exploration.", 70, "http://www.cmj.com/reviews/2011/07/jackie-o-motherfucker-%E2%80%93-earth-sound-system/", ""] \n["jackie-o-motherfucker", "earth-sound-system", true, "AllMusic", "This shifting back and forth between tradition and avant-garde tradition, as it were, defines much of the rest of the album -- call it maturing or call it other interests, but it\'s a comfortable enough listen, as appropriate for the schizophrenic beast that still gets labeled indie rock as anything else.", 70, "http://www.allmusic.com/album/earth-sound-system-r2182141", ""] \n["jackie-o-motherfucker", "earth-sound-system", true, "Blurt Magazine", "The final', is_bytes=False, is_obj=False, is_text=True, is_none=False, text='["jackie-o-motherfucker", "earth-sound-system", true, "CMJ", "Earth Sound System is structured with actual musical tracks interspersed between organized chaotic electronica. The attempts at the two different approaches to this type of music come off as undecided and incoherent, yet there is merit in the tracks that actually offer stable grounds for musical exploration.", 70, "http://www.cmj.com/reviews/2011/07/jackie-o-motherfucker-%E2%80%93-earth-sound-system/", ""] \n["jackie-o-motherfucker", "earth-sound-system", true, "AllMusic", "This shifting back and forth between tradition and avant-garde tradition, as it were, defines much of the rest of the album -- call it maturing or call it other interests, but it\'s a comfortable enough listen, as appropriate for the schizophrenic beast that still gets labeled indie rock as anything else.", 70, "http://www.allmusic.com/album/earth-sound-system-r2182141", ""] \n["jackie-o-motherfucker", "earth-sound-system", true, "Blurt Magazine", "The final product can both unnerve and captivate, though not at the same time. As far as consistency, well that\'s another story.", 60, "http://blurt-online.com/reviews/view/3162/", ""] \n
"""
import subprocess
import pickle
import logging
from pprint import pprint as pp, pformat
logging.basicConfig(level=logging.DEBUG)
logg = logging.getLogger("FileFinderUtils")
def filter_empty(lst):
return [x for x in lst if x]
def conjure(filename):
out = subprocess.check_output("mdfind -name {}".format(filename).split())
lines = filter_empty([result.strip() for result in out.decode("utf-8").split("\\n")])
return lines
def resurrect(filename, callback=None,feeling_lucky=True, log_level=logging.DEBUG ):
is_text, is_bytes, is_obj, is_err, exists, contents, is_none = False, False, False, False, False, None, True
fp = [path for path in conjure(filename) if filename in os.path.basename(path)]
print(fp)
if fp:
logg.info(fp)
exists = True
if feeling_lucky:
choice = 0
fp = fp[choice]
else:
choice = -1
while choice not in range(0, len(fp)):
print("Found {} matches for files named \\'{}\\'".format(len(fp), filename))
for i, fp in enumerate(fp):
print(" {0: >5} => {1}".format(''.join(["[",str(i),"]"]), fp))
print("Index of the file you'd like to open: ")
index = input(">> ")
try:
choice = int(index.strip())
logg.info("{}".format(fp[choice]))
except Exception as e:
print("Invalid choice: {}, e".format(index, e))
assert(os.path.isfile(fp)), "Error selecting the file: {} is not a valid file!".format(fp)
logg.info("fp is {}".format(fp))
try:
with open(fp, 'r') as f:
try:
contents = pickle.loads(f)
is_obj = True
except Exception as e:
print(e)
contents = f.read()
is_text = True
except Exception as e:
print(e)
with open(fp, 'rb') as f:
try:
contents = pickle.load(f)
is_obj = True
except Exception as e:
print(e)
contents = f.read()
is_bytes = True
if contents:
is_none = False
try:
preview = contents.__str__()
preview = preview[0:min(1000, len(preview))]
except:
preview = ""
response_template = namedtuple("FileSearchResponse", ['exists', 'preview', 'is_bytes', 'is_obj', 'is_text', 'is_none', 'text', 'responseObj', 'filepath'])
response = response_template(exists, preview, is_bytes, is_obj, is_text, is_none, contents if is_text else contents.__str__(), contents if is_obj else {}, fp)
if not callback:
callback = lambda response: response
logg.debug(pformat(response))
return callback(response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment