Пример #1
0
 def install_packages(self, cmd, packages):
     installed = 0
     for pkg in packages:
         install_cmd = cmd_split(cmd.format(packages=pkg))
         install_output = Popen(install_cmd)
         while install_output.poll() is None:
             sleep(0.5)
         output = install_output.returncode
         Log.debug("Running (npm) %s ... %r" % (install_cmd, output == 0))
         if 0 == output:
             installed += 1
     return installed
Пример #2
0
 def run(self):
     while self.is_running:
         # TODO: Handle malformed commands
         try:
             line = cmd_split(self.prompt())
         except Exception as e:
             print('-esh: %s' % e)
             continue
         line = [expandvars(self, s) for s in line]
         if len(line) > 0:
             cmd = line[0]
             args = line[1:]
             self.do_command(cmd, *args)
Пример #3
0
def parse_env_str(environ_str):
    """Parse a quoted environment string generated by format_env_dict, or `typeset` builtin.

    environ_str must be encoded in utf-8
    """

    try:
        split_envs = [e.split('=', 1) for e in cmd_split(environ_str.decode())]
        return {e[0]: e[1] for e in split_envs if len(e) == 2}
    except ValueError:
        print('WARNING: Could not parse env string: `{}`'.format(environ_str),
              file=sys.stderr)
        raise
Пример #4
0
 def install_packages(self, cmd, packages):
     installed = 0
     for pkg in packages:
         install_cmd = cmd_split(cmd.format(packages=pkg))
         install_output = Popen(install_cmd)
         while install_output.poll() is None:
             sleep(0.5)
         output = install_output.returncode
         log_status = (self.env.os_name, install_cmd, output == 0)
         Log.debug("Running (%s) %s ... %r" % log_status)
         if 0 == output:
             installed += 1
     return installed
Пример #5
0
def parse_env_str(environ_str):
    """Parse a quoted environment string generated by format_env_dict, or `typeset` builtin."""

    try:
        split_envs = [e.split('=', 1) for e in cmd_split(environ_str)]
        return {
            e[0]: e[1] for e
            in split_envs
            if len(e) == 2
        }
    except ValueError:
        print('WARNING: Could not parse env string: `{}`'.format(environ_str),
              file=sys.stderr)
        raise
Пример #6
0
 def run(self, cmd=None, *args, **kwargs):
     safe_cmd = cmd_split(cmd)
     output_args = {"stderr": STDOUT}
     if self.env.shell_args is not None:
         if self.env.shell_args.unsafe_shell:
             output_args.update({"shell": True})
         else:
             cmd = safe_cmd
     try:
         output = check_output(cmd, **output_args)
         if output is None:
             output = "n/a"
         self.success(u"Output => %s" % output.decode('utf-8').strip())
     except CalledProcessError as e:
         self.fail(e.output)
     except Exception as e:
         self.fail(str(e))
Пример #7
0
 def run(self, srv=None, *args, **kwargs):
     cmd = StopService.check_systemd()
     if cmd is None:
         return self.fail("Unsupported OS: %s" % self.env.os_name)
     try:
         service_cmd = cmd.format(service=srv)
         log_status = (self.env.os_name, service_cmd)
         Log.debug("Service OS (%s) stop: %s ..." % log_status)
         service_output = Popen(cmd_split(service_cmd))
         while service_output.poll() is None:
             sleep(0.5)
         if 0 != service_output.returncode:
             return self.fail(u"Service '%s' => failed to stop" % srv)
         self.success(u"Service '%s' => stopped" % srv)
     except CalledProcessError as e:
         self.fail(e.output)
     except Exception as e:
         self.fail(str(e))
Пример #8
0
 def get_service_status(cls, service_cmd):
     proc = Popen(cmd_split(service_cmd), stdout=PIPE)
     stdout, _ = proc.communicate()
     for line in stdout.split("\n"):
         # https://www.freedesktop.org/software/systemd/man/systemctl.html
         if not line.lower().strip().startswith("active: "):
             continue
         if "active (running)" in line.lower():
             return True, "active"
         elif "deactivating" in line.lower():
             return False, "deactivating"
         elif "activating" in line.lower():
             return True, "activating"
         elif "failed" in line.lower():
             return False, "failed"
         elif "inactive" in line.lower():
             return False, "inactive"
     return False, "n/a"
Пример #9
0
def get_verb_aliases(path=catkin_config_path):
    if not os.path.isdir(path):
        raise RuntimeError(
            "Cannot get verb aliases because the catkin config path ('{0}') does not exist or is a file."
            .format(path))
    verb_aliases_path = os.path.join(path, 'verb_aliases')
    if not os.path.isdir(verb_aliases_path):
        raise RuntimeError(
            "Cannot get verb aliases because the verb aliases config path ('{0}') does not exist or is a file."
            .format(verb_aliases_path))
    verb_aliases = {}
    for file_name in sorted(os.listdir(verb_aliases_path)):
        if file_name.endswith('.yaml'):
            full_path = os.path.join(verb_aliases_path, file_name)
            with open(full_path, 'r') as f:
                yaml_dict = yaml.safe_load(f)
            if yaml_dict is None:
                continue
            if not isinstance(yaml_dict, dict):
                raise RuntimeError(
                    "Invalid alias file ('{0}'), expected a dict but got a {1}"
                    .format(full_path, type(yaml_dict)))
            for key, value in yaml_dict.items():
                if not isinstance(key, str):
                    raise RuntimeError(
                        "Invalid alias in file ('{0}'), expected a string but got '{1}' of type {2}"
                        .format(full_path, key, type(key)))
                parsed_value = None
                if isinstance(value, str):
                    # Parse using shlex
                    parsed_value = cmd_split(value)
                elif isinstance(value, list) or isinstance(value, type(None)):
                    # Take plainly
                    parsed_value = value
                else:
                    raise RuntimeError(
                        "Invalid alias expansion in file ('{0}'), expected a string or a list but got '{1}' of type {2}"
                        .format(full_path, value, type(value)))
                verb_aliases[key] = parsed_value
    for alias, value in dict(verb_aliases).items():
        if not value:
            del verb_aliases[alias]
    return verb_aliases
Пример #10
0
def build_barcodes_pdf(barcodes):
    # 36 barcodes per page
    pages = int(ceil(len(barcodes) / 36.0))

    # assuming N * 8.5in x 11in
    PAGE_WIDTH = 1275
    PAGE_HEIGHT = 1650

    # create blank pdfs
    blanks = [
        Image.new('RGB', (PAGE_WIDTH, PAGE_HEIGHT), (255, 255, 255))
        for i in range(pages)
    ]

    # padding set empirically for
    # Electronic Imaging Materials
    # Part #80402
    START_LEFT = 18
    START_UPPER = 59
    HORIZ_GAP = 23
    VERT_GAP = 17
    BOX_WIDTH = 300
    BOX_HEIGHT = 150

    # center barcode, assuming barcode images are 300x150px
    # will adjust per image if 202x100px
    SHIFT_RIGHT = 0
    SHIFT_DOWN = 0

    # set starting points
    cur_left = START_LEFT
    cur_upper = START_UPPER
    page = -1
    idx = 0
    for i in get_image(barcodes):
        # if we have 36 barcodes we have filled a page
        if idx % 36 == 0:
            page += 1
            cur_upper = START_UPPER
            cur_left = START_LEFT

        # verify the barcode is the expected size, shift accordingly
        width, height = i.size
        if i.size == (202, 100):
            SHIFT_RIGHT = 49
            SHIFT_DOWN = 25
        elif i.size == (300, 150):
            SHIFT_RIGHT = 0
            SHIFT_DOWN = 0
        else:
            tmp = "image %s is an unsupported size"
            raise AttributeError(tmp % i.shape)

        # shift to new row
        if cur_left + width > PAGE_WIDTH:
            cur_left = START_LEFT
            cur_upper = cur_upper + HORIZ_GAP + BOX_HEIGHT

        # paste into the image
        blanks[page].paste(i, (cur_left + SHIFT_RIGHT, cur_upper + SHIFT_DOWN))

        # shift right
        cur_left += BOX_WIDTH + VERT_GAP

        idx += 1

    # write out each page
    tmpdir = "tmp_%s" % ''.join(
        [choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ") for i in range(5)])
    while path.exists(tmpdir):
        tmpdir = "tmp_%s" % ''.join(
            [choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ") for i in range(5)])
    mkdir(tmpdir)

    temp_pages = "squash_barcode_page_%d.pdf"
    for page, blank in enumerate(blanks):
        blank.save(path.join(tmpdir, temp_pages % page), quality=100)

    match_pages = ' '.join([
        path.join(tmpdir, "squash_barcode_page_%d.pdf" % i)
        for i in range(len(blanks))
    ])

    # magically squash all the pages
    cmd = cmd_split('gs -r150 -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH' +
                    ' -sDEVICE=pdfwrite -sOutputFile=- %s' % match_pages)
    p = Popen(cmd, stdout=PIPE)
    output, _ = p.communicate()
    rmtree(tmpdir)
    # return PDF text
    return output
Пример #11
0
def build_barcodes_pdf(barcodes):
    # 36 barcodes per page
    pages = int(ceil(len(barcodes) / 36.0))

    # assuming N * 8.5in x 11in
    PAGE_WIDTH = 1275
    PAGE_HEIGHT = 1650

    # create blank pdfs
    blanks = [Image.new('RGB', (PAGE_WIDTH, PAGE_HEIGHT), (255, 255, 255))
              for i in range(pages)]

    # padding set empirically for
    # Electronic Imaging Materials
    # Part #80402
    START_LEFT = 18
    START_UPPER = 59
    HORIZ_GAP = 23
    VERT_GAP = 17
    BOX_WIDTH = 300
    BOX_HEIGHT = 150

    # center barcode, assuming barcode images are 300x150px
    # will adjust per image if 202x100px
    SHIFT_RIGHT = 0
    SHIFT_DOWN = 0

    # set starting points
    cur_left = START_LEFT
    cur_upper = START_UPPER
    page = -1
    idx = 0
    for i in get_image(barcodes):
        # if we have 36 barcodes we have filled a page
        if idx % 36 == 0:
            page += 1
            cur_upper = START_UPPER
            cur_left = START_LEFT

        # verify the barcode is the expected size, shift accordingly
        width, height = i.size
        if i.size == (202, 100):
            SHIFT_RIGHT = 49
            SHIFT_DOWN = 25
        elif i.size == (300, 150):
            SHIFT_RIGHT = 0
            SHIFT_DOWN = 0
        else:
            tmp = "image %s is an unsupported size"
            raise AttributeError(tmp % i.shape)

        # shift to new row
        if cur_left + width > PAGE_WIDTH:
            cur_left = START_LEFT
            cur_upper = cur_upper + HORIZ_GAP + BOX_HEIGHT

        # paste into the image
        blanks[page].paste(i, (cur_left + SHIFT_RIGHT, cur_upper + SHIFT_DOWN))

        # shift right
        cur_left += BOX_WIDTH + VERT_GAP

        idx += 1

    # write out each page
    tmpdir = "tmp_%s" % ''.join([choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
                                 for i in range(5)])
    while path.exists(tmpdir):
        tmpdir = "tmp_%s" % ''.join([choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
                                     for i in range(5)])
    mkdir(tmpdir)

    temp_pages = "squash_barcode_page_%d.pdf"
    for page, blank in enumerate(blanks):
        blank.save(path.join(tmpdir, temp_pages % page), quality=100)

    match_pages = ' '.join([path.join(tmpdir, "squash_barcode_page_%d.pdf" % i)
                            for i in range(len(blanks))])

    # magically squash all the pages
    cmd = cmd_split('gs -r150 -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH' +
                    ' -sDEVICE=pdfwrite -sOutputFile=- %s' % match_pages)
    p = Popen(cmd, stdout=PIPE)
    output, _ = p.communicate()
    rmtree(tmpdir)
    # return PDF text
    return output