def get_party_set(self, requested_party_set_slug): try: return PartySet.objects.get(slug=requested_party_set_slug) except PartySet.DoesNotExist: self.stdout.write("Couldn't find the party set '{0}'".format( requested_party_set_slug )) all_party_sets = PartySet.objects.values_list('slug', flat=True) if PartySet.objects.exists(): self.stdout.write("You might have meant one of these:") for other_party_set_slug in all_party_sets: self.stdout.write(" " + other_party_set_slug) self.stdout.write( "Create the party set '{0}'? (y/n) ".format( requested_party_set_slug ), ending='' ) response = input() if response.strip().lower() != 'y': self.stderr.write("Exiting.") return self.stdout.write('What is the full name of the party set? ') response = input() return PartySet.objects.create( slug=requested_party_set_slug, name=response )
def main(argv): try: command = argv[1].lower() if command not in ('build', 'dump'): raise ValueError options = [] argc = 2 for arg in argv[argc:]: if arg[0] == '-': argc += 1 if arg[1] == '-': break options.append(arg) else: break rom = argv[argc] directory = argv[argc + 1] argc += 2 if len(argv) != argc: raise ValueError except: print("""Usage: %s COMMAND [options] ROM DIRECTORY COMMAND build Creates a ROM from the specified directory dump Dumps ROM to specified directory OPTIONS -y --assume-yes Overwrite target directory automatically when extracting. Overwrite ROM automatically when building -- No further arguments. This is required when ROM starts with a - character. """ % argv[0]) exit() if command == 'build': if os.path.exists(rom) and '-y' not in options and \ '--assume-yes' not in options: if input('Do you want to overwrite %s? [y/n] ' % rom).\ lower() != 'y': print('Aborted building new ROM') exit() build(rom, directory) elif command == 'dump': if os.path.exists(directory) and '-y' not in options and \ '--assume-yes' not in options: if input('Do you want to overwrite %s? [y/n] ' % directory).\ lower() != 'y': print('Aborted dumping ROM') exit() try: os.mkdir(directory) except OSError: pass dump(rom, directory)
def decision_from_user(self, ppc_data, popit_result): # Ask whether the PPC is the same as this person from the # PopIt search results: print("--------------------------------------------------------") print("Is this PPC ...") print(" Name:", ppc_data["name"].encode("utf-8")) if "email" in ppc_data: print(" Email:", ppc_data["email"]) print(" Party:", ppc_data["party_slug"]) print(" Constituency:", ppc_data["constituency"]) if "full_url" in ppc_data: print(" PPC URL:", ppc_data["full_url"]) print("... the same as this person from PopIt:") print(" PopIt URL:", popit_result["html_url"]) print(" Name:", popit_result["name"].encode("utf-8")) if "email" in popit_result: print(" Email:", popit_result["email"]) for year in popit_result["party_memberships"]: print(" Party in {}: {}".format( year, popit_result["party_memberships"][year]["name"])) for year in popit_result["standing_in"]: print(" Constituency in {}: {}".format( year, popit_result["standing_in"][year]["name"])) response = "" while response.lower() not in ("y", "n"): response = input("Are they the same? (y/Y/n/N) ") response = response.lower().strip() if response == "y": return True elif response == "n": return False
def apply_transactions(transactions, auto=False): ''' Apply renaming transactions. apply_transactions(transactions) transactions = [(old_path, new_path),(old_path),(new_path),...] Manual review of transactions is required. ''' if auto: logger.warning('Auto is On. No confirmation required.') print('='*30) if not transactions: logger.debug('NO TRANSACTIONS') sys.exit('No Transactions to apply.') return for t in transactions: print('[{}] > [{}]'.format(t[0].name, t[1].name)) print('{} Transactions to apply. Renaming...'.format(len(transactions))) count = 0 if auto or input('EXECUTE ? [y]\n>') == 'y': for src, dst in transactions: try: src.rename(dst) except: logger.error(sys.exc_info()[0].__name__) logger.error('Could not rename: [{}]>[{}]'.format(src, dst)) else: logger.debug('[{}] renamed to [{}]'.format(src, dst)) count += 1 print('{} folders renamed.'.format(count))
def decision_from_user(self, ppc_data, popit_result): # Ask whether the PPC is the same as this person from the # PopIt search results: print("--------------------------------------------------------") print("Is this PPC ...") print(" Name:", ppc_data['name'].encode('utf-8')) if 'email' in ppc_data: print(" Email:", ppc_data['email']) print(" Party:", ppc_data['party_slug']) print(" Constituency:", ppc_data['constituency']) if 'full_url' in ppc_data: print(" PPC URL:", ppc_data['full_url']) print("... the same as this person from PopIt:") print(" PopIt URL:", popit_result['html_url']) print(" Name:", popit_result['name'].encode('utf-8')) if 'email' in popit_result: print(" Email:", popit_result['email']) for year in popit_result['party_memberships']: print(" Party in {0}: {1}".format( year, popit_result['party_memberships'][year]['name'])) for year in popit_result['standing_in']: print(" Constituency in {0}: {1}".format( year, popit_result['standing_in'][year]['name'])) response = '' while response.lower() not in ('y', 'n'): response = input('Are they the same? (y/Y/n/N) ') response = response.lower().strip() if response == 'y': return True elif response == 'n': return False
def apply_transactions(transactions, auto=False): ''' Apply renaming transactions. apply_transactions(transactions) transactions = [(old_path, new_path),(old_path),(new_path),...] Manual review of transactions is required. ''' if auto: logger.warning('Auto is On. No confirmation required.') print('=' * 30) if not transactions: logger.debug('NO TRANSACTIONS') sys.exit('No Transactions to apply.') return for t in transactions: print('[{}] > [{}]'.format(t[0].name, t[1].name)) print('{} Transactions to apply. Renaming...'.format(len(transactions))) count = 0 if auto or input('EXECUTE ? [y]\n>') == 'y': for src, dst in transactions: try: src.rename(dst) except: logger.error(sys.exc_info()[0].__name__) logger.error('Could not rename: [{}]>[{}]'.format(src, dst)) else: logger.debug('[{}] renamed to [{}]'.format(src, dst)) count += 1 print('{} folders renamed.'.format(count))
def decision_from_user(self, ppc_data, popit_result): # Ask whether the PPC is the same as this person from the # PopIt search results: print("--------------------------------------------------------") print("Is this PPC ...") print(" Name:", ppc_data['name'].encode('utf-8')) if 'email' in ppc_data: print(" Email:", ppc_data['email']) print(" Party:", ppc_data['party_slug']) print(" Constituency:", ppc_data['constituency']) if 'full_url' in ppc_data: print(" PPC URL:", ppc_data['full_url']) print("... the same as this person from PopIt:") print(" PopIt URL:", popit_result['html_url']) print(" Name:", popit_result['name'].encode('utf-8')) if 'email' in popit_result: print(" Email:", popit_result['email']) for year in popit_result['party_memberships']: print(" Party in {0}: {1}".format( year, popit_result['party_memberships'][year]['name'] )) for year in popit_result['standing_in']: print(" Constituency in {0}: {1}".format( year, popit_result['standing_in'][year]['name'] )) response = '' while response.lower() not in ('y', 'n'): response = input('Are they the same? (y/Y/n/N) ') response = response.lower().strip() if response == 'y': return True elif response == 'n': return False
def main(): usage = 'python foldify.py source_file [destination_file] [--label] [--help]' description = ''' ====================================================== Foldify - CLI tools for managing directory Trees. Version: {version} Author: {author} Operations: ## Print a directory tree ## $ foldify directory1 ## Label empty Folder in tree ## $ foldify directory1 --label [update, remove] ## Copy a directory Tree ## $ foldify directory1 directory2 ## Create Json from a directory ## $ foldify directory1 directory1.json ## Create Directory from json ## $ foldify directory1.json directory1 ====================================================== '''.format(version=__version__, author=__author__) parser = argparse.ArgumentParser(prog='Foldify', description=description, usage=usage, formatter_class=help_formatter, ) parser.add_argument('source_file', type=str, help='Source filepath.') parser.add_argument('-l', '--label', choices=['update', 'remove'], help='Adds Label _EMPTY to empty folders.') parser.add_argument('--custom-label', help='Customizes empty label.') parser.add_argument('dest_file', type=str, nargs='?', help='Destination filepath.') parser.add_argument('-v', '--verbose', action='store_true') args_dict = vars(parser.parse_args()) globals().update(args_dict) # print(args_dict) if verbose: enable_debug() # ensure source_file exists, if not exit. exists = os.path.exists if not exists(source_file): print('=' * 40) parser.print_help() print('=' * 40) print('ERROR: source_file does not exist.') sys.exit() # If no dest_file, print source_tree if not dest_file: if label: t = generate_transactions(path=source_file, label=custom_label, remove_all=bool(label == 'remove')) apply_transactions(t) else: tree = Tree(source_file, json=is_json(source_file)) print('=' * 40) tree.print_tree() print('=' * 40) sys.exit('Done.') # if dest_file exists, prompt for overwite before continuing. if exists(dest_file): if label: sys.exit('Must use only source_file with --label option.') if input('WARNING: dest_file already exists. Overwrite? (y/n)') != 'y': print('Exiting.') print('=' * 40) sys.exit() # Copy folder, json from dir, or dir from json, depending on formats. tree = Tree(source_file, json=is_json(source_file)) write_dest = tree.write_json if is_json(dest_file) else tree.write_tree write_dest(dest_file)