Пример #1
0
def main():
    parser = argparse.ArgumentParser(formatter_class=CustomFormatter,
                                     description='Sekigae Program')
    parser.add_argument('-t', '--tag', default='FRONT', help='set tag name\n')
    parser.add_argument('-o', '--out', help='Write Tables to CSV File\n')
    parser.add_argument('-f',
                        '--format',
                        action='store_true',
                        help='Output Tables as CSV Style\n')
    _format = lambda s: [
        tuple(map(int, order.split(':'))) for order in s.split(',')
    ]
    parser.add_argument(
        '-s',
        '--special',
        type=_format,
        help='select number to especially place. \nFormat: row:col:number,...\n'
    )
    if stdin.isatty():
        # UNIXパイプラインinput無し
        parser.add_argument('n_people', type=int, help='Number of people')
        parser.add_argument('ncol', type=int, help='Number of columns')
        parser.add_argument(
            '--csv', help='Read CSV File (ignore n-people and nrow options)\n')
        args = parser.parse_args()

        seki = Sekigae(args.n_people, args.ncol, args.tag)

        # Read CSV
        if args.csv:
            seki.read_csv(args.csv, args.tag)
    else:
        # UNIXパイプラインinputあり
        args = parser.parse_args()

        seki = Sekigae(2, 1, args.tag)

        # apply stdin CSV
        if not stdin.isatty():
            seki.read_csv_iter(stdin, args.tag)

    # apply special order
    if args.special:
        for order in args.special:
            seki.set(*order)

    # show tables
    if args.format:
        seki.show_csv()
    else:
        seki.show()

    # Write CSV
    if args.out:
        seki.to_csv(args.out)
        if not args.format:
            print('csv wrote')
Пример #2
0
    def take_action(self, parsed_args):
        self.LOG.debug('deleting group')
        self.app.secrets.requires_environment()
        self.app.secrets.read_secrets_descriptions()
        groups = self.app.secrets.get_groups()
        choice = None

        if parsed_args.group is not None:
            choice = parsed_args.group
        elif not (stdin.isatty() and 'Bullet' in dir()):
            # Can't involve user in getting a choice.
            raise RuntimeError('[-] no group specified to delete')
        else:
            # Give user a chance to choose.
            choices = ['<CANCEL>'] + sorted(groups)
            cli = Bullet(prompt="\nSelect group to delete:",
                         choices=choices,
                         indent=0,
                         align=2,
                         margin=1,
                         shift=0,
                         bullet="→",
                         pad_right=5)
            choice = cli.launch()
            if choice == "<CANCEL>":
                self.LOG.info('cancelled deleting group')
                return

        # Group chosen. Now do we need to confirm?
        if not parsed_args.force:
            if not stdin.isatty():
                raise RuntimeError(
                    '[-] must use "--force" flag to delete a group.')
            else:
                prompt = 'Type the name "{}" to confirm: '.format(choice)
                cli = Input(prompt,
                            default="",
                            word_color=colors.foreground["yellow"])
                confirm = cli.launch()
                if confirm != choice:
                    self.LOG.info('cancelled deleting group')
                    return

        descriptions_path = self.app.secrets.descriptions_path()
        group_file = os.path.join(descriptions_path, '{0}.yml'.format(choice))
        if not os.path.exists(group_file):
            raise RuntimeError(('Group file "{}" does not '
                                'exist').format(group_file))
        # Delete secrets from group.
        secrets = self.app.secrets.get_items_from_group(choice)
        for secret in secrets:
            self.app.secrets.delete_secret(secret)
        # Delete group descriptions.
        os.unlink(group_file)
        self.LOG.info('[+] deleted secrets group "{0}"'.format(choice))
Пример #3
0
    def take_action(self, parsed_args):
        se = self.app.secrets
        se.requires_environment()
        se.read_secrets_descriptions()
        group = parsed_args.group
        groups = se.get_groups()
        choice = None

        if parsed_args.group is not None:
            choice = parsed_args.group
        elif not (stdin.isatty() and 'Bullet' in globals()):
            # Can't involve user in getting a choice.
            raise RuntimeError('[-] no group specified to delete')
        else:
            # Give user a chance to choose.
            choices = ['<CANCEL>'] + sorted(groups)
            cli = Bullet(prompt="\nSelect group to delete:",
                         choices=choices,
                         indent=0,
                         align=2,
                         margin=1,
                         shift=0,
                         bullet="→",
                         pad_right=5)
            choice = cli.launch()
            if choice == "<CANCEL>":
                self.logger.info('[-] cancelled deleting group')
                return

        # Group chosen. Now do we need to confirm?
        if not parsed_args.force:
            if not stdin.isatty():
                raise RuntimeError(
                    '[-] must use "--force" flag to delete a group.')
            else:
                prompt = f"Type the name '{choice}' to confirm: "
                cli = Input(prompt,
                            default="",
                            word_color=colors.foreground["yellow"])
                confirm = cli.launch()
                if confirm != choice:
                    self.logger.info('[-] cancelled deleting group')
                    return

        group_file = se.get_descriptions_path(group=group)
        if not os.path.exists(group_file):
            raise RuntimeError(f"[-] group file '{group_file}' does not exist")
        # Delete secrets from group.
        secrets = se.get_items_from_group(choice)
        for secret in secrets:
            se.delete_secret(secret)
        # Delete group descriptions.
        safe_delete_file(group_file)
        self.logger.info("[+] deleted secrets group '%s' (%s)", choice,
                         group_file)
Пример #4
0
    def take_action(self, parsed_args):
        self.LOG.debug('[*] deleting environment')
        choice = None
        if parsed_args.environment is not None:
            choice = parsed_args.environment
        elif not (stdin.isatty() and 'Bullet' in globals()):
            # Can't involve user in getting a choice.
            raise RuntimeError('[-] no environment specified to delete')
        else:
            # Give user a chance to choose.
            environments = os.listdir(self.app.secrets.secrets_basedir())
            choices = ['<CANCEL>'] + sorted(environments)
            cli = Bullet(prompt="\nSelect environment to delete:",
                         choices=choices,
                         indent=0,
                         align=2,
                         margin=1,
                         shift=0,
                         bullet="→",
                         pad_right=5)
            choice = cli.launch()
            if choice == "<CANCEL>":
                self.LOG.info('[-] cancelled deleting environment')
                return

        # Environment chosen. Now do we need to confirm?
        e = psec.secrets.SecretsEnvironment(choice)
        env_path = e.environment_path()
        if not parsed_args.force:
            if not stdin.isatty():
                output = psec.utils.atree(env_path,
                                          outfile=None,
                                          print_files=True)
                raise RuntimeError(
                    "[-] must use '--force' flag to delete an environment.\n"
                    "[-] the following will be deleted: \n"
                    f"{''.join([line for line in output])}"
                )
            else:
                prompt = f"Type the name '{choice}' to confirm: "
                cli = Input(prompt,
                            default="",
                            word_color=colors.foreground["yellow"])
                confirm = cli.launch()
                if confirm != choice:
                    self.LOG.info('[-] cancelled deleting environment')
                    return

        # We have confirmation or --force. Now safe to delete.
        # TODO(dittrich): Use safe_delete_file over file list
        shutil.rmtree(env_path)
        self.LOG.info(f"[+] deleted directory path '{env_path}")
Пример #5
0
def main():
	arg_parser = ArgumentParser(usage="%(prog)s [OPTIONS] -y <EXPRESSION> [CSV ...]")
	arg_parser.add_argument("csvs",  metavar="CSV", nargs="*", help="CSV data")
	arg_parser.set_defaults(constraints=[], xs=[], ys=[], groups=[], header=True, verbose=False)
	arg_parser.add_argument("-x",  dest="xs",           action="append",       help="independent column")
	arg_parser.add_argument("-y",  dest="ys",           action="append",       help="dependent column")
	arg_parser.add_argument("-g",  dest="groups",       action="append",       help="comparison column")
	arg_parser.add_argument("-c",  dest="constraints",  action="append",       help="constraints")
	arg_parser.add_argument("-p",  dest="plot_data",    action="store",        help="generate gnuplot file")
	arg_parser.add_argument("-t",  dest="header",       action="store_false",  help="no headers")
	arg_parser.add_argument("-v",  dest="verbose",      action="store_true",   help="show SQL statements")
	args = arg_parser.parse_args()

	sql_file = mkstemp(".sqlite")[1]

	if args.csvs or not stdin.isatty():
		if not stdin.isatty():
			tmp_in = mkstemp(".csv")[1]
			with open(tmp_in, 'w') as tmp_out:
				tmp_out.write(stdin.read())
			args.csvs = [tmp_in,]

	exit_code = 0

	try:
		if args.csvs:
			sql = csv2sql(args.csvs, sql_file)
			if args.verbose:
				stderr.write("{}\n".format(sql))
		sql, column_names, xs, ys, gs = generateSQL(args, sql_file)
		if args.verbose:
			stderr.write("{}\n".format(sql))
	except BaseException as err:
		if isinstance(err, KeyboardInterrupt):
			stderr.write("interrupted;")
		elif isinstance(err, AssertionError):
			stderr.write("{};\n".format(err))
		else:
			stderr.write("Unforeseen error: {};\n".format(err))
		exit_code = 1
	finally:
		if args.plot_data:
			assert len(args.ys) == 1, "cannot plot more than one dependent variable"
			output_script(args.plot_data, column_names, sql, sql_file, args, xs, ys, gs)
		else:
			output_print(column_names, sql, sql_file, args)
		rm(sql_file)
		if not stdin.isatty():
			rm(tmp_in)
		exit(exit_code)
Пример #6
0
    def run(args):
        """Install a shared-secret to this cluster.

        When invoked interactively, you'll be prompted to enter the secret.
        Otherwise the secret will be read from the first line of stdin.

        In both cases, the secret must be hex/base16 encoded.
        """
        # Obtain the secret from the invoker.
        if stdin.isatty():
            try:
                secret_hex = input("Secret (hex/base16 encoded): ")
            except EOFError:
                print()  # So that the shell prompt appears on the next line.
                raise SystemExit(1)
            except KeyboardInterrupt:
                print()  # So that the shell prompt appears on the next line.
                raise
        else:
            secret_hex = stdin.readline()
        # Decode and install the secret.
        try:
            secret = to_bin(secret_hex.strip())
        except binascii.Error as error:
            print("Secret could not be decoded:", str(error), file=stderr)
            raise SystemExit(1)
        else:
            set_shared_secret_on_filesystem(secret)
            shared_secret_path = get_shared_secret_filesystem_path()
            print("Secret installed to %s." % shared_secret_path)
            raise SystemExit(0)
Пример #7
0
def main():
    """ppx command line script entry point."""
    # Logging to the console.
    setup_logger_console()

    # Command line.
    args = parse_cl()

    # Initialise XML parser and remove blank text for 'pretty_print' formatting.
    #   https://lxml.de/FAQ.html#parsing-and-serialisation
    parser = XMLParser(remove_blank_text=True)

    # Pretty print XML sources.
    for xml_s in args.xml_sources:
        pp_xml(xml_s,
               parser=parser,
               syntax=args.syntax,
               xml_declaration=args.declaration)

    if not args.xml_sources:
        # Read from a pipe when no XML source is specified.
        if not stdin.isatty():
            pp_xml(stdin,
                   parser=parser,
                   syntax=args.syntax,
                   xml_declaration=args.declaration)
        else:
            stderr.write("Error: no XML source specified\n")
Пример #8
0
    def discover(cls, manager):
        """
        Args:
            manager (Manager): Manager instance.

        Raises:
            SystemExit: If invalid options are provided.
        """

        import_secrets = manager.args.get("import_secrets")
        export_secrets = manager.args.get("export_secrets")

        # fail fast if no options is provided...
        if import_secrets is not True and not isinstance(export_secrets, list):
            Log.fatal("Unexpected migrate request...")

        # create tmp dir if not eixsts...
        if not path.exists(cls.migrate_tmpdir):
            makedirs(cls.migrate_tmpdir)

        # run migration
        mig = cls(manager)
        if import_secrets is True:
            if stdin.isatty():
                Log.fatal("Migration failed: stdin is empty")
            mig.import_secrets()
        elif isinstance(export_secrets, list) and len(export_secrets) >= 0:
            if stdout.isatty():
                Log.fatal("Migration failed: stdout is empty")
            mig.export_secrets(records=export_secrets)

        # cleanup
        rmtree(cls.migrate_tmpdir)
Пример #9
0
    def __init__(self):
        super().__init__()
        self.settings = Settings()

        # If there is piped input
        if not stdin.isatty():
            try:
                cli_settings = stdin.read().rstrip().split(' ')

                self.settings.CELL_SIZE = int(cli_settings[0])
                self.settings.NUM_OBSTACLES = int(cli_settings[1])
                self.settings.GRID_WIDTH = int(cli_settings[2])
                self.settings.GRID_HEIGHT = int(cli_settings[3])
                self.settings.HEURISTIC = str(cli_settings[4])

                self.settings.WINDOW_WIDTH = str(self.settings.CELL_SIZE *
                                                 self.settings.GRID_WIDTH)
                self.settings.WINDOW_HEIGHT = str(self.settings.CELL_SIZE *
                                                  self.settings.GRID_HEIGHT)

                Config.set('graphics', 'width', self.settings.WINDOW_WIDTH)
                Config.set('graphics', 'height', self.settings.WINDOW_HEIGHT)

            except:
                raise IOError
Пример #10
0
def getpassword(prompt='Password: '):
    """ Returns secure password, read from stdin w/o echoing """

    if stdin.isatty():
        return getpass.getpass(prompt)
    else:
        return stdin.readline().rstrip()
Пример #11
0
def main():
    import argparse
    from sys import exit, stdin
    parser = argparse.ArgumentParser()
    parser.add_argument('-v', '--version', action='version', version="%%(prog)s %s (%s)" % (__version__, __author__))
    parser.add_argument('username', help="Your HE DNS username")
    parser.add_argument('password', help="Your HE DNS password")
    parser.add_argument('command', nargs=argparse.REMAINDER,
                        help="An optional command, if blank we drop into interactive mode")
    options = parser.parse_args()

    shell = HurricaneDNSShell(options.username, options.password)
    try:
        if not options.command:
            if stdin.isatty():
                shell.cmdloop()
            else:
                for line in stdin.readlines():
                    shell.onecmd(line)
        else:
            from pipes import quote
            shell.onecmd(" ".join(map(lambda x: quote(x), options.command)))
    except HurricaneDNS.HurricaneAuthenticationError as e:
        print '%s: HE sent an error (%s)' % (parser.prog, e)
        exit(1)
    except HurricaneDNS.HurricaneError as e:
        print '%s: %s' % (parser.prog, e)
Пример #12
0
def init():
  if Settings.get('helper_tasks', True):
    import helper_tasks
    helper_tasks.main()


  def worker(line):
    try:
      result = execCommand(split(line), True)
      print '' if result is None else '%s\n' % str(result)

    except HandledException as e:
      err('%s\n' % e)

  if stdin.isatty(): # Enter interactive shell

    prompt = Settings.get('prompt', '>')

    while True:
      try:
        line = raw_input(prompt)

        if line:
          worker(line)

      except EOFError: # ^z (null character) was passed.
        exit()

  else:

    for line in stdin.readlines():
      worker(line.strip('\r\n ')) # #Pending: As of now, stdin should provide whole commands. Commands and argoments couldn't be separated into multiple lines (like with the interactive mode). Fix this,
Пример #13
0
def choose_superlinter_setup(setups: List[Setup]) -> Optional[Setup]:
    if not setups:
        return None

    count = len(setups)
    if count == 1:
        return setups[0]

    from sys import stdin, stdout

    is_interactive = stdin.isatty() and stdout.isatty()

    print("Pick which Super-Linter setup to use:" if is_interactive else
          "The following Super-Linter setups were found:")
    for number, setup in enumerate(setups, 1):
        print()
        print(f"  #{number:<3}  {setup.path}")
        print(f'        step {setup.step} of "{setup.job}" job on {setup.img}')
        for key, value in setup.env.items():
            print(f"        {key}={value}")
    print()

    if not is_interactive:
        print("Defaulting to the first setup found.")
        return setups[0]

    number = 0
    while not 1 <= number <= count:
        try:
            number = int(input("? "))
        except ValueError:
            pass

    return setups[number - 1]
Пример #14
0
def main():
    if not stdin.isatty():
        authors = stdin.read()
    else:
        authors = argv[1]
    authors = author_fix(authors)
    print(authors)
Пример #15
0
 def take_action(self, parsed_args):
     se = self.app.secrets
     se.requires_environment()
     se.read_secrets_and_descriptions()
     group = parsed_args.group
     groups = se.get_groups()
     # Default to using a group with the same name as the environment,
     # for projects that require a group of "global" variables.
     if group is None:
         group = str(self.app.secrets)
     if group not in groups:
         raise RuntimeError((f"[!] group '{group}' does not exist in "
                             f"environment '{str(se)}'"
                             ) if parsed_args.group is not None else
                            "[!] please specify a group with '--group'")
     descriptions = se.read_descriptions(group=group)
     variables = [item['Variable'] for item in descriptions]
     args = parsed_args.arg
     for arg in args:
         if arg not in variables:
             raise RuntimeError(
                 f"[!] variable '{arg}' does not exist in group '{group}'")
         if not parsed_args.force:
             if not stdin.isatty():
                 raise RuntimeError(
                     "[-] must use '--force' flag to delete a secret")
             else:
                 prompt = f"Type the name '{arg}' to confirm: "
                 cli = Input(prompt,
                             default="",
                             word_color=colors.foreground["yellow"])
                 confirm = cli.launch()
                 if confirm != arg:
                     self.logger.info('[-] cancelled deleting secret')
                     return
         descriptions = [
             item for item in descriptions if item['Variable'] != arg
         ]
         se.delete_secret(arg)
     if len(descriptions) == 0:
         paths = [se.get_descriptions_path(group=group)]
         if parsed_args.mirror_locally:
             paths.append(
                 se.get_descriptions_path(
                     root=os.getcwd(),
                     group=group,
                 ))
         for path in paths:
             safe_delete_file(path)
             self.logger.info("[+] deleted empty group '%s' (%s)", group,
                              path)
     else:
         se.write_descriptions(
             data=descriptions,
             group=group,
             mirror_to=os.getcwd() if parsed_args.mirror_locally else None)
         se.write_secrets()
Пример #16
0
 def take_action(self, parsed_args):
     if parsed_args.unset:
         if parsed_args.environment is not None:
             raise RuntimeError("[-] '--unset' does not take an argument")
         if clear_saved_default_environment():
             self.logger.info('[+] explicit default environment unset')
         else:
             self.logger.info('[+] no default environment was set')
     elif parsed_args.set:
         # If it is not possible to interactively ask for environment,
         # just raise an exception.
         if (parsed_args.environment is None
                 and not (stdin.isatty() and 'Bullet' in globals())):
             raise RuntimeError('[-] no environment specified')
         # Otherwise, let's prompt for an environment for better UX!
         if parsed_args.environment is not None:
             choice = parsed_args.environment
         else:
             basedir = self.app.secrets.get_secrets_basedir()
             environments = [
                 env_path.name
                 for env_path in get_environment_paths(basedir=basedir)
             ]
             choices = ['<CANCEL>'] + sorted(environments)
             cli = Bullet(prompt="\nChose a new default environment:",
                          choices=choices,
                          indent=0,
                          align=2,
                          margin=1,
                          shift=0,
                          bullet="→",
                          pad_right=5)
             choice = cli.launch()
             # Having second thoughts, eh?
             if choice == "<CANCEL>":
                 self.logger.info('[-] cancelled setting default')
         if save_default_environment(choice):
             self.logger.info(
                 "[+] default environment explicitly set to '%s'", choice)
     elif parsed_args.environment is not None:
         print(parsed_args.environment)
     else:
         # No environment specified; show current setting.
         env_string = get_saved_default_environment()
         if env_string is not None:
             if self.app_args.verbose_level > 1:
                 self.logger.info(
                     "[+] default environment explicitly set to '%s'",
                     env_string)
         else:
             # No explicit saved default.
             env_string = get_default_environment()
             if self.app_args.verbose_level > 1:
                 self.logger.info(
                     "[+] default environment is implicitly '%s'",
                     env_string)
         print(env_string)
Пример #17
0
def ezstdin():
    if stdin.isatty():
        o: bool = False
        return o
    else:
        o: List[str] = []
        for line in stdin.readlines():
            o.append(line)
        return o
Пример #18
0
 def cmd_map_diff(self, path):
     if path is None:
         if stdin.isatty():
             usage_error("please pipe a diff into \"codemapper map-diff\","
                         " or provide a path to a .diff/.patch file")
         diff_fp = stdin
     else:
         diff_fp = open(path)
     patternish_paths = self._get_patternish_paths_from_diff(diff_fp)
     self._map_paths(patternish_paths)
Пример #19
0
def read_input():
    try:
        inf = ''
        if not stdin.isatty():
            inf = stdin.read().rstrip('\n')
        else:
            print('input is empty')
    except:
        print('failed to parse input')
    return inf
Пример #20
0
def read_all_inputs(files):
	if files:
		result = []
		for file in files:
			with open(file, "r") as fd:
				result.append(fd.read())
		return "".join(result)
	elif not stdin.isatty():
		return stdin.read()
	else:
		return ""
Пример #21
0
	def __init__(self):
		"""
		Entrance point for the dragbox application

		+ Read commandline
		+ Try dbus connection
		+ Add items
		+ Run
		"""
		# Read commandline switches
		(files, texts, cli_flags) = self.read_opts(argv[1:])

		# Read from stdin
		from sys import stdin
		if not stdin.isatty():
			pipe_text = stdin.read()
			if pipe_text:
				texts += [pipe_text]

		self.cli_flags = cli_flags

		get = self.cli_flags.get("get")
		list_names = self.cli_flags.get("list-names")
		nofork = self.cli_flags.get("no-fork")
		self.identifier = self.cli_flags.get("identifier")

		success = True
		quit_done = False
		if nofork:
			self.dbus_connection = None
		elif list_names:
			self.get_dbus_names()
			quit_done = True
		else:
			self.dbus_connection = self.get_dbus_connection()
			if get:
				success = self.try_get_data()
				quit_done = True
			elif not nofork and self.dbus_connection:
				self.dbus_send(files, texts)
				quit_done = True
			else:
				self.dbus_service = self.start_dbus_service()
				# Fork to disconnect from terminal
				pid = fork()
				if pid:
					quit_done = True
		if quit_done:
			raise SystemExit(not success)

		(self.data_controller, self.writer) = self.init_data()
		self.add_files(None, files)
		self.add_texts(None, texts)
		self.run_window()
Пример #22
0
def getSTDIN():
    from sys import stdin

    if stdin.isatty():
        return

    b = b''

    for chunk in iter(lambda: stdin.read(4096), b''):
        b += chunk

    return b or None
Пример #23
0
 def take_action(self, parsed_args):
     self.LOG.debug('managing localized environment default')
     if parsed_args.unset:
         if parsed_args.environment is not None:
             raise RuntimeError('--unset does not take an argument')
         if clear_saved_default_environment():
             self.LOG.info('explicit default environment unset')
         else:
             self.LOG.info('no default environment was set')
     elif parsed_args.set:
         # If it is not possible to interactively ask for environment,
         # just raise an exception.
         if (parsed_args.environment is None
                 and not (stdin.isatty() and 'Bullet' in dir())):
             raise RuntimeError('[-] no environment specified')
         # Otherwise, let's prompt for an environment for better UX!
         if parsed_args.environment is not None:
             choice = parsed_args.environment
         else:
             environments = os.listdir(self.app.secrets.secrets_basedir())
             choices = ['<CANCEL>'] + sorted(environments)
             cli = Bullet(prompt="\nChose a new default environment:",
                          choices=choices,
                          indent=0,
                          align=2,
                          margin=1,
                          shift=0,
                          bullet="→",
                          pad_right=5)
             choice = cli.launch()
             # Having second thoughts, eh?
             if choice == "<CANCEL>":
                 self.LOG.info('cancelled setting default')
         if save_default_environment(choice):
             self.LOG.info(('default environment set explicitly to '
                            f'"{choice}"'))
     elif parsed_args.environment is not None:
         print(parsed_args.environment)
     else:
         # No environment specified; show current setting.
         env_string = get_saved_default_environment()
         if env_string is not None:
             if self.app_args.verbose_level > 1:
                 self.LOG.info(('default environment set explicitly to '
                                f'"{env_string}"'))
         else:
             # No explicit saved default.
             env_string = default_environment()
             if self.app_args.verbose_level > 1:
                 self.LOG.info(('default environment is implicitly '
                                f'"{env_string}"'))
         print(env_string)
Пример #24
0
    def read(cls):
        """Check if authority is piped.

        Returns:
            bool: True if data is piped, otherwise False.
        """

        if len(argv) > 1:
            return False
        if not stdin.isatty():
            cls.buf_in = unicode(stdin.read()).strip()
            return len(cls.buf_in) > 0
        return False
Пример #25
0
 def _loop(self):
     while True:
         if stdin.isatty():
             print('? ', end='', file=stderr)
         try:
             req = raw_input()
         except EOFError:
             break
         print('->', req, '\n', file=stderr)
         req = json.loads(req)
         (name, args), = req.iteritems()
         resp = getattr(self, name)(**args)
         self._send(resp)
Пример #26
0
def main(sentence=None,
         tag=None,
         append=False,
         replace=False,
         delete=False,
         list_tags=False,
         limit=None,
         db_path=None,
         unique=False,
         print_tag=False):
    """Manage/search a DB of example sentences.

    sentence: Sentence search regex or input sentence for append/replace operations.
    tag: Tag search regex or tag for append/replace operations.
    append: Add sentences to a tag. Either use --sentence to specify a single sentence or pipe lines into stdin.
    replace: Like --append, but clears the tag before inserting.
    delete: Delete tag.
    list_tags: List all tags.
    limit: Limit number of search results shown.
    db_path: Alternate path (directory) for tags storage.
    unique: Ignore duplicate lines in input.
    print_tag: Print the tag name in front of every result.'
    """

    db = SentenceDB(db_path)
    if list_tags:
        for tag in db.tags():
            print(tag)
        return

    if append or replace:
        if not tag:
            print('Error: You need to specify a tag.', file=stderr)
            return 1
        sent_in = [sentence] if stdin.isatty() else stdin
        db.add(tag, sent_in, replace=replace, unique=unique)
        return

    if delete:
        if not tag:
            print('Error: You need to specify a tag.', file=stderr)
            return 1
        return

    limit = int(limit) if type(limit) is str else -1
    for res in db.search(tag, sentence):
        print(res['tag'] + ': ' +
              res['sentence'] if print_tag else res['sentence'])
        limit -= 1
        if not limit:
            return
def main():
    # check if an input file is piped into terminal command and exit if not
    if stdin.isatty():
        print("NO MATCH")
        exit(1)

    patterns, paths = process_input()

    matching_patterns = get_matching_patterns(patterns, paths)

    for m in matching_patterns:
        print(m)

    exit()
Пример #28
0
def start():
    global quit, sleep

    print()
    print("Starting sync daemon...")

    quit = False
    sleep = Event()

    daemon = Thread(name="daemon-sync", target=forever, daemon=True)
    daemon.start()

    print("Daemon running")

    if stdin.isatty() and stdout.isatty():
        print()

        while not quit:
            print(
                ">>> Hit [I] for info, [Q] to quit after current block, or [^C] to exit immediately <<<"
            )

            c = read_char()

            if 'q' == c or 'Q' == c:
                quit = True
                sleep.set()
                daemon.join()

            elif 'i' == c or 'I' == c:
                print()
                sync = Process(url=get_rpc_url())
                sync.get_info()
                print()

            elif '\x03' == c:
                print()
                print("Interrupted")
                raise KeyboardInterrupt()

            #else:
            #    print(repr(c))

        print()
        print("User quit")

    else:
        daemon.join()
Пример #29
0
    def get_key():
        nonlocal key

        if not key:
            if stdin.isatty():
                print()
                key = getpass("Enter private BCH key (hex): ")

            else:
                key = stdin.readline().rstrip()

        if not key:
            print()
            raise ValueError("Key may not be empty")

        return key
Пример #30
0
def deserialize():
    if stdin.isatty():
        return [[]]

    frames = json.loads(stdin.read())

    #txt = open("christmas/anim.json").read()
    #frames = json.loads(txt)

    for frame in frames:
        for led in frame:
            left, top, width, height = led['rect']
            led['rect'] = pygame.Rect(left, top, width, height)
            r, g, b = led['color']
            led['color'] = pygame.Color(r, g, b)
    return frames
Пример #31
0
def read_chain(args):
    chain = ([], {})
    # read stdin for chained data and unpickle into chain array
    # check if stdin is not a terminal
    if not stdin.isatty() and args.file != stdin:
        chain = pickle.loads(getattr(stdin, 'buffer', stdin).read())

    # check our data is what we expect it to be
    # TODO: error handling
    assert(isinstance(chain, tuple))
    assert(len(chain) == 2)
    assert(isinstance(chain[0], list))
    assert(isinstance(chain[1], dict))
    for link in chain[0]:
        assert(isinstance(link, Graph))

    return chain
Пример #32
0
def search_input(argv):
    lines = []
    # check if there is some data at stdin:
    if not stdin.isatty():
        for line in stdin.readlines():
            lines.append(line)
    # check if files are given
    elif len(argv) > 2:
        try:
            for file in argv[2:]:
                with open(file, "r") as f:
                    for line in f.readlines():
                        lines.append(line)
        except FileNotFoundError:
            print(f"File '{file}' not found.")
            exit(1)
    return lines
Пример #33
0
def read_chain(args):
    chain = ([], {})
    # read stdin for chained data and unpickle into chain array
    # check if stdin is not a terminal
    if not stdin.isatty() and args.file != stdin:
        chain = pickle.loads(stdin.buffer.read())

    # check our data is what we expect it to be
    # TODO: error handling
    assert (type(chain) is tuple)
    assert (len(chain) == 2)
    assert (type(chain[0]) is list)
    assert (type(chain[1]) is dict)
    for link in chain[0]:
        assert (type(link) is Graph)

    return chain
Пример #34
0
def run(args):
    """Register the rack controller with a region controller."""
    # If stdin supplied to program URL must be passed as argument.
    if not stdin.isatty() and args.url is None:
        print(
            "MAAS region controller URL must be given when supplying the "
            "shared secret via stdin with a non-interactive shell."
        )
        raise SystemExit(1)
    try:
        call_and_check(["systemctl", "stop", "maas-rackd"])
    except ExternalProcessError as e:
        print("Unable to stop maas-rackd service.", file=stderr)
        print("Failed with error: %s." % e.output_as_unicode, file=stderr)
        raise SystemExit(1)
    # maas_id could be stale so remove it
    set_maas_id(None)
    if args.url is not None:
        with ClusterConfiguration.open_for_update() as config:
            config.maas_url = args.url
    else:
        try:
            url = input("MAAS region controller URL: ")
        except EOFError:
            print()  # So that the shell prompt appears on the next line.
            raise SystemExit(1)
        except KeyboardInterrupt:
            print()  # So that the shell prompt appears on the next line.
            raise
        with ClusterConfiguration.open_for_update() as config:
            config.maas_url = url
        print("MAAS region controller URL saved as %s." % url)
    if args.secret is not None:
        set_shared_secret_on_filesystem(to_bin(args.secret))
    else:
        InstallSharedSecretScript.run(args)
    try:
        call_and_check(["systemctl", "enable", "maas-rackd"])
        call_and_check(["systemctl", "start", "maas-rackd"])
    except ExternalProcessError as e:
        print(
            "Unable to enable and start the maas-rackd service.", file=stderr
        )
        print("Failed with error: %s." % e.output_as_unicode, file=stderr)
        raise SystemExit(1)
Пример #35
0
    def run(self):
        """Execute the search, filter, format, print results."""
        # Either load results from pipe or grep new ones
        if stdin.isatty():
            if self.config.search_term is None:
                exit()
            else:
                reader = self.reader_cls.from_grep(self.config)
        else:
            reader = self.reader_cls.from_pipe(self.config)

            # Set operations
            if self.config.union:
                reader.union()
            elif self.config.diff:
                reader.diff()
            elif self.config.fast_exclude:
                reader.fast_exclude()
            elif self.config.exclude:
                reader.exclude()
            elif self.config.inter:
                reader.inter()
            else:
                reader.fast_inter()

        if self.config.debug:
            print "=== Results dict ==="
            print dumps(reader.tree.data, indent=4) + '\n'

        # We can't publish with colour to a pipe because it's ugly
        format_ = self.config.outp_format
        if self.config.force_publish:
            if format_ == 'colour':
                format_ = 'clean'

        # Push to stdout or dump tree to pipe
        if stdout.isatty() or self.config.force_publish:
            publisher = self.VALID_FORMATS[format_]
            pub = publisher(self.config)
            pub.publish(reader.tree)
        else:
            reader.tree.dump(stdout)
Пример #36
0
def contentsOfFileSpecifiedIn(argv):
    """
    Find the first file specified in the arguments,
	and return its contents, as a list of its lines.
	
    """
    for argument in argv:
        try:
            with open(argument) as testFile:
                return testFile.readlines()
        except EnvironmentError:
            pass  # Expect many to not be files.
        
    # No file specified, try stdin
    try:
        if not stdin.isatty():
            return stdin.readlines()  # Read, but only from non-interactive stdin
    except EnvironmentError:
       pass  # Give up.
    return None
Пример #37
0
def main():
    # Skip handshake when testing manually
    if stdin.isatty():
        print('stdin is tty, skipping handshake')
    else:
        if stdin.readline() == 'HELO\t1\n':
            output('OK', 'pdns-ldap-py is ready')
        else:
            output('FAIL')
            stdin.readline()
            exit(1)

    # XXX Global variable
    global connection
    connection = ReconnectLDAPObject(config.uri, retry_max=4, retry_delay=5)
    # XXX A little ugly here
    connection.deref = ldap.DEREF_FINDING

    if config.start_tls:
        ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
        connection.start_tls_s()

    connection.bind_s(config.binddn, config.bindpw)

    while True:
        line = stdin.readline()
        if len(line) == 0:
            continue
        fields = line.rstrip('\n').split('\t')
        try:
            if respond(fields):
                output('END')
            else:
                output('FAIL')
        except Exception:
            output('FAIL')
            output('LOG', 'Shutting down on unexpected error. Traceback:')
            tb_lines = traceback.format_exc().split('\n')
            for line in tb_lines:
                output('LOG', line)
            break
Пример #38
0
    def __init__(self):
        super().__init__()
        self.settings = Settings()

        # If there is piped input
        if not stdin.isatty():
            try:
                cli_settings = stdin.read().rstrip().split(' ')

                self.settings.CELL_SIZE = int(cli_settings[0])
                self.settings.NUM_OBSTACLES = int(cli_settings[1])
                self.settings.GRID_WIDTH = int(cli_settings[2])
                self.settings.GRID_HEIGHT = int(cli_settings[3])
                self.settings.HEURISTIC = str(cli_settings[4])

                self.settings.WINDOW_WIDTH  = str(self.settings.CELL_SIZE * self.settings.GRID_WIDTH)
                self.settings.WINDOW_HEIGHT = str(self.settings.CELL_SIZE * self.settings.GRID_HEIGHT)

                Config.set('graphics', 'width', self.settings.WINDOW_WIDTH)
                Config.set('graphics', 'height', self.settings.WINDOW_HEIGHT)

            except:
                raise IOError
Пример #39
0
    USERNAME = None
    PASSWORD = ''
    EML_CREATE = False
    AUTH = True

    # Message view
    SUBJECT = ''
    BODY = ''
    FILES = []
    CHARSET = 'utf-8'

    # Use special send with personal or only receivers addresses
    SEND_WITH_CC = True

    # Other conf
    TTY = stdin.isatty()

    """Check for whom parameter use: from here or key from terminal"""
    if not (FROM and TO and SMTP_SERVER and TTY):
        arguments = get_args_parser(TTY)
        set_email_arguments(arguments)

    email = DispatchEmail(sender=FROM, receivers=TO, cc=CC,
                          smtp=SMTP_SERVER, port=PORT, tls=TLS)

    if TTY:
        """If stdin was used for send email via API, else without it"""
        eml = MessageWithAttachment(subject=SUBJECT, body=BODY, files=FILES,
                                    charset=CHARSET)

        if EML_CREATE:
Пример #40
0
def main():
    log_format = "%(asctime)s %(levelname)s: %(message)s"
    log_datefmt = "%m/%d/%Y %I:%M:%S %p"

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--version", "-v", action="version", version=runipy.__version__, help="print version information"
    )
    parser.add_argument("input_file", nargs="?", help=".ipynb file to run (or stdin)")
    parser.add_argument("output_file", nargs="?", help=".ipynb file to save cell output to")
    parser.add_argument("--quiet", "-q", action="store_true", help="don't print anything unless things go wrong")
    parser.add_argument(
        "--overwrite", "-o", action="store_true", help="write notebook output back to original notebook"
    )
    format_grp = parser.add_mutually_exclusive_group()
    format_grp.add_argument("--html", nargs="?", default=False, help="output an HTML snapshot of the notebook")
    format_grp.add_argument("--pdf", nargs="?", default=False, help="output a PDF snapshot of the notebook")
    parser.add_argument("--template", nargs="?", default=False, help="template to use for HTML output")
    parser.add_argument("--pylab", action="store_true", help="start notebook with pylab enabled")
    parser.add_argument("--matplotlib", action="store_true", help="start notebook with matplotlib inlined")
    parser.add_argument(
        "--skip-exceptions",
        "-s",
        action="store_true",
        help="if an exception occurs in a cell," + " continue running the subsequent cells",
    )
    parser.add_argument("--stdout", action="store_true", help="print notebook to stdout (or use - as output_file")
    parser.add_argument("--stdin", action="store_true", help="read notebook from stdin (or use - as input_file)")
    parser.add_argument(
        "--no-chdir", action="store_true", help="do not change directory to notebook's at kernel startup"
    )
    parser.add_argument("--profile-dir", help="set the profile location directly")
    args = parser.parse_args()

    if args.overwrite:
        if args.output_file is not None:
            print("Error: output_filename must not be provided if " "--overwrite (-o) given", file=stderr)
            exit(1)
        else:
            args.output_file = args.input_file

    if not args.quiet:
        logging.basicConfig(level=logging.INFO, format=log_format, datefmt=log_datefmt)

    working_dir = None

    payload_source = ""
    payload = ""
    if args.input_file == "-" or args.stdin:  # force stdin
        payload_source = stdin.name
        payload = stdin.read()
    elif not args.input_file and stdin.isatty():  # no force, empty stdin
        parser.print_help()
        exit()
    elif not args.input_file:  # no file -> default stdin
        payload_source = stdin.name
        payload = stdin.read()
    else:  # must have specified normal input_file
        with open(args.input_file) as input_file:
            payload_source = input_file.name
            payload = input_file.read()
        working_dir = os.path.dirname(args.input_file)

    if args.no_chdir:
        working_dir = None

    if args.profile_dir:
        profile_dir = os.path.expanduser(args.profile_dir)
    else:
        profile_dir = None

    logging.info("Reading notebook %s", payload_source)
    try:
        # Ipython 3
        nb = reads(payload, 3)
    except (TypeError, NBFormatError):
        # Ipython 2
        nb = reads(payload, "json")
    nb_runner = NotebookRunner(nb, args.pylab, args.matplotlib, profile_dir, working_dir)

    exit_status = 0
    try:
        nb_runner.run_notebook(skip_exceptions=args.skip_exceptions)
    except NotebookError:
        exit_status = 1

    if args.output_file and args.output_file != "-":
        logging.info("Saving to %s", args.output_file)
        with open(args.output_file, "w") as output_filehandle:
            try:
                # Ipython 3
                write(nb_runner.nb, output_filehandle, 3)
            except (TypeError, NBFormatError):
                # Ipython 2
                write(nb_runner.nb, output_filehandle, "json")

    if args.stdout or args.output_file == "-":
        try:
            # Ipython 3
            write(nb_runner.nb, stdout, 3)
        except (TypeError, NBFormatError):
            # Ipython 2
            write(nb_runner.nb, stdout, "json")
        print()

    if args.html is not False:
        if args.html is None:
            # if --html is given but no filename is provided,
            # come up with a sane output name based on the
            # input filename
            if args.input_file.endswith(".ipynb"):
                args.html = args.input_file[:-6] + ".html"
            else:
                args.html = args.input_file + ".html"

        if args.template is False:
            exporter = HTMLExporter()
        else:
            exporter = HTMLExporter(
                config=Config({"HTMLExporter": {"template_file": args.template, "template_path": [".", "/"]}})
            )

        logging.info("Saving HTML snapshot to %s" % args.html)
        output, resources = exporter.from_notebook_node(convert(nb_runner.nb, current_nbformat))
        codecs.open(args.html, "w", encoding="utf-8").write(output)

    elif args.pdf is not False:
        if args.pdf is None:
            # if --html is given but no filename is provided,
            # come up with a sane output name based on the
            # input filename
            if args.input_file.endswith(".ipynb"):
                args.pdf = args.input_file[:-6] + ".pdf"
            else:
                args.pdf = args.input_file + ".pdf"

        if args.template is False:
            exporter = PDFExporter()
        else:
            exporter = PDFExporter(
                config=Config({"PDFExporter": {"template_file": args.template, "template_path": [".", "/"]}})
            )

        logging.info("Saving PDF snapshot to %s" % args.pdf)
        output, resources = exporter.from_notebook_node(convert(nb_runner.nb, current_nbformat))
        writer = FilesWriter()
        writer.build_directory = os.path.dirname(args.pdf)
        writer.write(output, resources, os.path.splitext(os.path.basename(args.pdf))[0])

    nb_runner.shutdown_kernel()

    if exit_status != 0:
        logging.warning("Exiting with nonzero exit status")
    exit(exit_status)
Пример #41
0
    exit(1)

    
help_text = """
Type "?" to see his message.
Type "help()" for help on available methods.
Type "Ctrl-D" to exit.
Restart with "cornetto-client.py -h" to see command line options.
"""

startup_msg = ( "cornetto-client.py (version %s)\n" % __version__ + 
                "Copyright (c) Erwin Marsi\n" + help_text )

    

if stdin.isatty():
    prompt = "$ "
    if opts.pretty_print is None:
        opts.pretty_print = True
    print startup_msg
else:
    prompt = ""
    if opts.pretty_print is None:
        opts.pretty_print = False
    
# use of eval might allow arbitrary code execution - probably not entirely safe    
if opts.ask:
    process = lambda c: eval('server.ask("%s")' % c.strip())
else:
    process = lambda c: eval("server." + c.strip())
Пример #42
0
    controllers = discover()

    # for now only care about one controller
    controller = next(controllers, None)
    if controller is None:
        print("no tellstick devices found")
        exit(0)

    if argv[-1] == "raw":
        stream = map(prepend_timestamp, controller.packets())
    else:
        stream = controller.values()

    for packet in stream:
        print(packet)
        try:
            stdout.flush()
        except IOError:
            # broken pipe
            pass


if __name__ == "__main__":
    if argv[-1] == "mock":
        from tellsticknet.discovery import mock
        mock()
    elif not stdin.isatty():
        parse_stdin()
    else:
        print_event_stream()
Пример #43
0
#!/usr/bin/env python

from sys import stdin, stdout, stderr

print "Piped input:",  not stdin.isatty()
print "Piped output:", not stdout.isatty()
print "Piped error:",  not stderr.isatty()
Пример #44
0
def main():
    if stdin.isatty():
        run_interactively()
    else:
        run_from_stdin()
Пример #45
0
fh.setFormatter(formatter)
logger.addHandler(fh)

fh = logging.StreamHandler()
fh.setLevel(logging.ERROR) if options.DEBUG else fh.setLevel(logging.CRITICAL)
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.disabled = False  # maybe make this a cmdline switch? -D ?

logging.info("\n")
logging.info("=" * 50)
logging.info("STARTING NEW LOG ENTRY...")
logging.info("=" * 50)
logging.info("\n\n")

logging.debug("input, output isatty: %s\t%s" % (stdin.isatty(), stdout.isatty()))
if options.COLOR == 'AUTO':
    options.COLOR = 'ON' if (os.environ.get("QTOP_COLOR", stdout.isatty()) in ("ON", True)) else 'OFF'
logging.debug("options.COLOR is now set to: %s" % options.COLOR)

sections_off = {
    1: options.sect_1_off,
    2: options.sect_2_off,
    3: options.sect_3_off
}

sys.excepthook = handle_exception


def get_jobs_info(fn, write_method=options.write_method):
    """
Пример #46
0
async def main(args):

    loop = asyncio.get_event_loop()

    def poller(then=None):
        interval = 5
        now = loop.time()
        if then:
            _LOGGER.debug("Poller %f Took %f", interval, now - then)
        loop.call_later(interval, poller, now)

    if loop.get_debug():
        poller()

    if args["parse"] and not stdin.isatty():
        parse_stdin()
        exit()
    elif args["mock"]:
        from tellsticknet.discovery import mock

        await mock()
        exit()
    elif args["devices"]:
        for e in (e for e in read_config() if "sensorId" not in e):
            print("-", e["name"])
        exit()
    elif args["sensors"]:
        for e in (e for e in read_config() if "sensorId" in e):
            print("-", e["name"])
        exit()

    ip = args["--ip"]

    if args["discover"]:
        async for c in await discover(ip=ip, discover_all=True):
            print(c)
        exit()

    config = read_config()

    from functools import partial

    if args["mqtt"]:
        from tellsticknet.mqtt import run

        await run(partial(discover, ip=ip), config)
        exit()

    controller = await discover(ip=ip)
    if not controller:
        exit("No tellstick device found")

    _LOGGER.info("Found controller: %s", controller)

    if args["listen"]:
        await print_event_stream(controller, raw=args["--raw"])
    elif args["send"]:
        cmd = args["<cmd>"]
        METHODS = dict(
            on=const.TURNON,
            turnon=const.TURNON,
            off=const.TURNOFF,
            turnoff=const.TURNOFF,
            up=const.UP,
            down=const.DOWN,
            stop=const.STOP,
            dim=const.DIM,
        )
        method = METHODS.get(cmd.lower()) or exit("method not found")

        param = args["<param>"]

        if method == const.DIM and not param:
            exit("dim level missing")

        name = args["<name>"]
        protocol = args["<protocol>"]
        model = args["<model>"]
        house = args["<house>"]
        unit = args["<unit>"]

        if name:
            devices = [
                e for e in config if e["name"].lower().startswith(name.lower())
            ]
            if not devices:
                exit(f"Device with name {name} not found")
        elif protocol and model and house and unit:
            exit("Not implemented")

        if not devices:
            exit("No devices found")

        _LOGGER.info("Executing for %d devices", len(devices))

        _LOGGER.debug("Waiting for tasks to finish")
        await asyncio.gather(
            *[
                controller.execute(device, method, param=param)
                for device in devices
            ]
        )
Пример #47
0
def has_colors():
    return is_interactive() or (not stdin.closed and stdin.isatty())
Пример #48
0
def run_notebook(parser, args):
    """Run notebook. Input parameters are in args. To run this inside script,
    put args to some object, i.e.

    >>> class Args(object): pass
    >>> args = Args()
    >>> args.output_file = ...
    >>> exit_status = run_notebook(args)

    """
    if args.overwrite:
        if args.output_file is not None:
            print('Error: output_filename must not be provided if '
                    '--overwrite (-o) given', file=stderr)
            exit(1)
        else:
            args.output_file = args.input_file

    if not args.quiet:
        logging.basicConfig(level=logging.INFO, format=log_format, datefmt=log_datefmt)
    if args.debug:
        logging.basicConfig(level=logging.DEBUG, format=log_format, datefmt=log_datefmt)

    working_dir = None

    if args.profile_dir:
        profile_dir = os.path.expanduser(args.profile_dir)
    else:
        profile_dir = None

    if args.input_file == '-' or args.stdin:  # force stdin
        payload = stdin
    elif not args.input_file and stdin.isatty():  # no force, empty stdin
        parser.print_help()
        exit()
    elif not args.input_file:  # no file -> default stdin
        payload = stdin
    else:  # must have specified normal input_file
        payload = open(args.input_file)
        working_dir = os.path.dirname(args.input_file)

    if args.no_chdir:
        working_dir = None

    logging.info('Reading notebook %s', payload.name)
    nb = read(payload, 'json')
    nb_runner = NotebookRunner(nb, args.pylab, args.matplotlib, profile_dir, working_dir, kernel=args.kernel, port=args.port)

    exit_status = 0
    try:
        nb_runner.run_notebook(skip_exceptions=args.skip_exceptions)
    except NotebookError:
        exit_status = 1

    if args.output_file and args.output_file != '-':
        logging.info('Saving to %s', args.output_file)
        write(nb_runner.nb, open(args.output_file, 'w'), 'json')

    if args.stdout or args.output_file == '-':
        write(nb_runner.nb, stdout, 'json')
        print()

    if args.html is not False:
        export_to_html(nb_runner, args)

    if args.rst is not False:
        export_to_rst(nb_runner, args)

    nb_runner.shutdown_kernel()
    return exit_status
Пример #49
0
def main():
    log_format = '%(asctime)s %(levelname)s: %(message)s'
    log_datefmt = '%m/%d/%Y %I:%M:%S %p'

    parser = argparse.ArgumentParser()
    parser.add_argument('--version', '-v', action='version', version=runipy.__version__,
            help='print version information')
    parser.add_argument('input_file', nargs='?',
            help='.ipynb file to run (or stdin)')
    parser.add_argument('output_file', nargs='?',
            help='.ipynb file to save cell output to')
    parser.add_argument('--quiet', '-q', action='store_true',
            help='don\'t print anything unless things go wrong')
    parser.add_argument('--overwrite', '-o', action='store_true',
            help='write notebook output back to original notebook')
    parser.add_argument('--html', nargs='?', default=False,
            help='output an HTML snapshot of the notebook')
    parser.add_argument('--template', nargs='?', default=False,
            help='template to use for HTML output')
    parser.add_argument('--pylab', action='store_true',
            help='start notebook with pylab enabled')
    parser.add_argument('--matplotlib', action='store_true',
            help='start notebook with matplotlib inlined')
    parser.add_argument('--skip-exceptions', '-s', action='store_true',
            help='if an exception occurs in a cell, continue running the subsequent cells')
    parser.add_argument('--stdout', action='store_true',
            help='print notebook to stdout (or use - as output_file')
    parser.add_argument('--stdin', action='store_true',
            help='read notebook from stdin (or use - as input_file)')
    parser.add_argument('--no-chdir', action='store_true',
            help="do not change directory to notebook's at kernel startup")
    parser.add_argument('--profile-dir',
            help="set the profile location directly")
    args = parser.parse_args()


    if args.overwrite:
        if args.output_file is not None:
            print('Error: output_filename must not be provided if '
                    '--overwrite (-o) given', file=stderr)
            exit(1)
        else:
            args.output_file = args.input_file

    if not args.quiet:
        logging.basicConfig(level=logging.INFO, format=log_format, datefmt=log_datefmt)

    working_dir = None

    if args.input_file == '-' or args.stdin:  # force stdin
        payload = stdin
    elif not args.input_file and stdin.isatty():  # no force, empty stdin
        parser.print_help()
        exit()
    elif not args.input_file:  # no file -> default stdin
        payload = stdin
    else:  # must have specified normal input_file
        payload = open(args.input_file)
        working_dir = os.path.dirname(args.input_file)

    if args.no_chdir:
        working_dir = None

    if args.profile_dir:
        profile_dir = os.path.expanduser(args.profile_dir)
    else:
        profile_dir = None

    logging.info('Reading notebook %s', payload.name)
    nb = read(payload, 'json')
    nb_runner = NotebookRunner(nb, args.pylab, args.matplotlib, profile_dir, working_dir)

    exit_status = 0
    try:
        nb_runner.run_notebook(skip_exceptions=args.skip_exceptions)
    except NotebookError:
        exit_status = 1

    if args.output_file and args.output_file != '-':
        logging.info('Saving to %s', args.output_file)
        write(nb_runner.nb, open(args.output_file, 'w'), 'json')

    if args.stdout or args.output_file == '-':
        write(nb_runner.nb, stdout, 'json')
        print()

    if args.html is not False:
        if args.html is None:
            # if --html is given but no filename is provided,
            # come up with a sane output name based on the
            # input filename
            if args.input_file.endswith('.ipynb'):
                args.html = args.input_file[:-6] + '.html'
            else:
                args.html = args.input_file + '.html'

        if args.template is False:
            exporter = HTMLExporter()
        else:
            exporter = HTMLExporter(
                    config=Config({'HTMLExporter':{'template_file':args.template, 'template_path': ['.', '/']}}))

        logging.info('Saving HTML snapshot to %s' % args.html)
        output, resources = exporter.from_notebook_node(nb_runner.nb)
        codecs.open(args.html, 'w', encoding='utf-8').write(output)

    nb_runner.shutdown_kernel()

    if exit_status != 0:
        logging.warning('Exiting with nonzero exit status')
    exit(exit_status)
Пример #50
0
def main():
    """
    main function for command line usage
    """
    # parse commandline arguments
    cmd_parser = ArgumentParser(description='Log Work to a Kimai instance')
    cmd_parser.add_argument('--configFile', type=str, default='log2kimai.cfg', help='default: log2kimai.cfg')
    cmd_parser.add_argument('-v', '--verbose', action='store_true')
    cmd_parser.add_argument('-d', '--dry', action='store_true', help='dryrun; just validating input')
    cmd_parser.add_argument('action', nargs='+', help='add, info projects/activities')
    cmd_args = cmd_parser.parse_args()
    config_file = ConfigParser()
    try:
        config_file.readfp(open(cmd_args.configFile))
    except IOError:
        exit('Error: Specified config file was not found or not readable.')
    # info mode
    if len(cmd_args.action) == 2 and cmd_args.action[0] == 'info':
        kimai = KimaiMessage(config_file.get('kimai', 'baseurl'),
                             config_file.get('kimai', 'user'),
                             config_file.get('kimai', 'pass'),
                             config_file.get('kimai', 'version'))
        if cmd_args.action[1] == 'activities':
            for key in kimai.activity:
                print ' '.join([str(key), ':', kimai.activity[key]])
        elif cmd_args.action[1] == 'projects':
            for key in kimai.projects:
                print ' '.join([str(key), ':', kimai.projects[key]])
        exit()
    elif len(cmd_args.action) == 1 and cmd_args.action[0] == 'add':
        # add mode
        # check stdin
        if stdin.isatty():
            exit()
        # read and validate stdin
        add_list = []
        line_counter = 0
        for line in stdin.readlines():
            line_counter += 1
            line = sub(r'\n', r'', ''.join(line))
            input_list = line.split('|')
            # validate number of arguments per line
            if len(input_list) != 5:
                print ' '.join(['error parsing stdin line', str(line_counter)])
            # validate startdate
            try:
                datetime_start = datetime.strptime(input_list[0], '%y%m%d-%H%M')
            except ValueError:
                exit(' '.join(['Error parsing start date (format is supposed to be yymmdd-HHmm)', str(line_counter)]))
            # validate duration
            try:
                datetime_end = datetime_start + timedelta(minutes=+int(input_list[1]))
            except ValueError:
                exit(' '.join(['Error parsing duration (supposed to be an integer) in line', str(line_counter)]))
            # validate project id
            try:
                project_id = int(input_list[2])
            except ValueError:
                exit(' '.join(['Error parsing project_id (supposed to be an integer) in line', str(line_counter)]))
            # validate activity id
            try:
                activity_id = int(input_list[3])
            except ValueError:
                exit(' '.join(['Error parsing activity_id (supposed to be an integer) in line', str(line_counter)]))
            comment = input_list[4]
            add_list.append((datetime_start, datetime_end, project_id, activity_id, comment))
            if cmd_args.verbose:
                print (datetime_start, datetime_end, project_id, activity_id, comment)
        if not cmd_args.dry and len(cmd_args.action) > 0 and cmd_args.action[0] == 'add':
            # send requests to log work
            kimai = KimaiMessage(config_file.get('kimai', 'baseurl'),
                                 config_file.get('kimai', 'user'),
                                 config_file.get('kimai', 'pass'),
                                 config_file.get('kimai', 'version'))
            for (start, end, pid, aid, comment) in add_list:
                kimai.log_work(start, end, pid, aid, comment)
    else:
        cmd_parser.print_usage()