Last active
November 5, 2018 12:40
-
-
Save KhasMek/f17e78c155e16e9b1c95421c8e65139b to your computer and use it in GitHub Desktop.
Open a random File. Default command to use is xdg open random file in current directory (and subdirectories). Modify defaults with the -c/--command and -d/--directory flags.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
""" | |
Open a random file | |
""" | |
# TODO: | |
# - add config file | |
# - history suppoort | |
import argparse | |
import os | |
import os.path | |
import random | |
import re | |
import subprocess | |
def build_file_dict(rootdir='.'): | |
file_dict = {} | |
for root, subdirs, files in os.walk(rootdir): | |
for file in files: | |
full_path = os.path.abspath(os.path.join(root, file)) | |
pretty_name = re.sub(r'[-_]', " ", file.rsplit('.', 1)[0]) | |
file_dict[pretty_name] = full_path | |
return file_dict | |
def pick_random(file_dict): | |
random_pick = random.choice(list(file_dict.keys())) | |
return random_pick | |
def run_cmd(cmd, path): | |
subprocess.run([cmd, path]) | |
def repeat_to_length(string_to_expand, length): | |
return (string_to_expand * (int(length/len(string_to_expand))))[:length] | |
def get_console_dimensions(): | |
rows, columns = os.popen('stty size', 'r').read().split() | |
return rows, columns | |
def main(cmd, rootdir): | |
file_dict = build_file_dict(rootdir) | |
rows, columns = get_console_dimensions() | |
print(" [ ] {} [ ] ".format(repeat_to_length('*', int(columns) - 10))) | |
print(" [*] Number of options: {} {} [ ] ".format(len(file_dict), | |
repeat_to_length(' ', int(columns) - 33))) | |
choice = pick_random(file_dict) | |
print(" [*] Choice: {} {} [ ] ".format(choice, | |
repeat_to_length(' ', int(columns) - len(choice) - 19))) | |
print(" [*] File Location: {} {} [ ] ".format(file_dict[choice], | |
repeat_to_length(' ', int(columns) - len(file_dict[choice]) - 26))) | |
print(" [ ] {} [ ] ".format(repeat_to_length('*', int(columns) - 10))) | |
run_cmd(cmd, file_dict[choice]) | |
if __name__ == '__main__': | |
argparser = argparse.ArgumentParser() | |
argparser.add_argument('-c', '--command', default='xdg-open', | |
help='command to run on randomly picked file. \ | |
(default: %(default)s)') | |
argparser.add_argument('-d', '--directory', default='.', help='directory \ | |
root to search through. (default: %(default)s)') | |
args = argparser.parse_args() | |
main(args.command, args.directory) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment