Python os.linesep() Examples

The following are 30 code examples of os.linesep(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: test_gsb.py    From baseband with GNU General Public License v3.0 6 votes vote down vote up
def test_rawdump_header_seek_offset(self):
        fh = open(SAMPLE_RAWDUMP_HEADER, 'rt')

        header = gsb.GSBHeader.fromfile(fh, verify=True)
        # Includes 1 trailing blank space, one line separator
        header_nbytes = header.nbytes
        assert (header_nbytes
                == len(' '.join(header.words) + ' ' + os.linesep))
        assert header.seek_offset(1) == header_nbytes
        assert header.seek_offset(12) == 12 * header_nbytes

        # Note that text pointers can't seek from current position.
        # Seek 2nd header.
        fh.seek(header.seek_offset(1))
        header1 = gsb.GSBHeader.fromfile(fh, verify=True)
        assert abs(header1.time
                   - Time('2015-04-27T13:15:00.251658480')) < 1.*u.ns

        fh.seek(header.seek_offset(9))
        header2 = gsb.GSBHeader.fromfile(fh, verify=True)
        assert abs(header2.time
                   - Time('2015-04-27T13:15:02.264924400')) < 1.*u.ns

        fh.close() 
Example #2
Source File: small_parallel_enja.py    From lineflow with MIT License 6 votes vote down vote up
def get_small_parallel_enja() -> Dict[str, Tuple[List[str]]]:

    en_url = 'https://raw.githubusercontent.com/odashi/small_parallel_enja/master/{}.en'
    ja_url = 'https://raw.githubusercontent.com/odashi/small_parallel_enja/master/{}.ja'
    root = download.get_cache_directory(os.path.join('datasets', 'small_parallel_enja'))

    def creator(path):
        dataset = {}
        for split in ('train', 'dev', 'test'):
            en_path = gdown.cached_download(en_url.format(split))
            ja_path = gdown.cached_download(ja_url.format(split))
            with io.open(en_path, 'rt') as en, io.open(ja_path, 'rt') as ja:
                dataset[split] = [(x.rstrip(os.linesep), y.rstrip(os.linesep))
                                  for x, y in zip(en, ja)]

        with io.open(path, 'wb') as f:
            pickle.dump(dataset, f)
        return dataset

    def loader(path):
        with io.open(path, 'rb') as f:
            return pickle.load(f)

    pkl_path = os.path.join(root, 'enja.pkl')
    return download.cache_or_load_file(pkl_path, creator, loader) 
Example #3
Source File: test_spinner.py    From tox with MIT License 6 votes vote down vote up
def test_spinner_report(capfd, monkeypatch):
    monkeypatch.setattr(sys.stdout, "isatty", lambda: False)
    with spinner.Spinner(refresh_rate=100) as spin:
        spin.stream.write(os.linesep)
        spin.add("ok")
        spin.add("fail")
        spin.add("skip")
        spin.succeed("ok")
        spin.fail("fail")
        spin.skip("skip")
    out, err = capfd.readouterr()
    lines = out.split(os.linesep)
    del lines[0]
    expected = [
        "\r{}✔ OK ok in 0.0 seconds".format(spin.CLEAR_LINE),
        "\r{}✖ FAIL fail in 0.0 seconds".format(spin.CLEAR_LINE),
        "\r{}⚠ SKIP skip in 0.0 seconds".format(spin.CLEAR_LINE),
        "\r{}".format(spin.CLEAR_LINE),
    ]
    assert lines == expected
    assert not err 
Example #4
Source File: abpttsclient.py    From ABPTTS with GNU General Public License v2.0 6 votes vote down vote up
def ShowUsage():
	print 'Usage: %s -c CONFIG_FILE_1 -c CONFIG_FILE_2 [...] -c CONFIG_FILE_n -u FORWARDINGURL -f LOCALHOST1:LOCALPORT1/TARGETHOST1:TARGETPORT1 -f LOCALHOST2:LOCALPORT2/TARGETHOST2:TARGETPORT2 [...] LOCALHOSTn:LOCALPORTn/TARGETHOSTn:TARGETPORTn [--debug]' % (sys.argv[0])
	print os.linesep
	print 'Example: %s -c CONFIG_FILE_1 -u https://vulnerableserver/EStatus/ -f 127.0.0.1:28443/10.10.20.11:8443' % (sys.argv[0])
	print os.linesep
	print 'Example: %s  -c CONFIG_FILE_1 -c CONFIG_FILE_2 -u https://vulnerableserver/EStatus/ -f 127.0.0.1:135/10.10.20.37:135 -f 127.0.0.1:139/10.10.20.37:139 -f 127.0.0.1:445/10.10.20.37:445' % (sys.argv[0])
	print os.linesep
	print 'Data from configuration files is applied in sequential order, to allow partial customization files to be overlayed on top of more complete base files.'
	print os.linesep
	print 'IE if the same parameter is defined twice in the same file, the later value takes precedence, and if it is defined in two files, the value in whichever file is specified last on the command line takes precedence.'
	print os.linesep
	print '--debug will enable verbose output.'
	print os.linesep
	print '--unsafetls will disable TLS/SSL certificate validation when connecting to the server, if the connection is over HTTPS'
	# logging-related options not mentioned because file output is buggy - just redirect stdout to a file instead
	#print os.linesep
	#print '--log LOGFILEPATH will cause all output to be written to the specified file (as well as the console, unless --quiet is also specified).'
	#print os.linesep
	#print '--quiet will suppress console output (but still allow log file output if that option is enabled).' 
Example #5
Source File: config.py    From ciftify with MIT License 6 votes vote down vote up
def wb_command_version():
    '''
    Returns version info about wb_command.

    Will raise an error if wb_command is not found, since the scripts that use
    this depend heavily on wb_command and should crash anyway in such
    an unexpected situation.
    '''
    wb_path = find_workbench()
    if wb_path is None:
        raise EnvironmentError("wb_command not found. Please check that it is "
                "installed.")
    wb_help = util.check_output('wb_command')
    wb_version = wb_help.split(os.linesep)[0:3]
    sep = '{}    '.format(os.linesep)
    wb_v = sep.join(wb_version)
    all_info = 'wb_command:{0}Path: {1}{0}{2}'.format(sep,wb_path,wb_v)
    return(all_info) 
Example #6
Source File: ciftify_recon_all.py    From ciftify with MIT License 6 votes vote down vote up
def write_cras_file(freesurfer_folder, cras_mat):
    '''read info about the surface affine matrix from freesurfer output and
    write it to a tmpfile'''
    mri_info = get_stdout(['mri_info', os.path.join(freesurfer_folder, 'mri',
            'brain.finalsurfs.mgz')])

    for line in mri_info.split(os.linesep):
        if 'c_r' in line:
            bitscr = line.split('=')[4]
            matrix_x = bitscr.replace(' ','')
        elif 'c_a' in line:
            bitsca = line.split('=')[4]
            matrix_y = bitsca.replace(' ','')
        elif 'c_s' in line:
            bitscs = line.split('=')[4]
            matrix_z = bitscs.replace(' ','')

    with open(cras_mat, 'w') as cfile:
        cfile.write('1 0 0 {}\n'.format(matrix_x))
        cfile.write('0 1 0 {}\n'.format(matrix_y))
        cfile.write('0 0 1 {}\n'.format(matrix_z))
        cfile.write('0 0 0 1{}\n') 
Example #7
Source File: abpttsfactory.py    From ABPTTS with GNU General Public License v2.0 6 votes vote down vote up
def ShowUsage():
	print 'This utility generates a configuration file and matching server-side code (JSP, etc.) to be used with the ABPTTS client component.'
	print os.linesep
	print 'Usage: %s -c CONFIG_FILE_1 -c CONFIG_FILE_2 [...] -c CONFIG_FILE_n -o BASE_OUTPUT_DIRECTORY [--output-filename OUTPUT_CONFIG_FILE] [-w OUTPUT_WRAPPER_TEMLATE_FILE] [--ignore-defaults] [--wordlist WORDLIST_FILE] [--debug]' % (sys.argv[0])
	print os.linesep
	print 'Example: %s -c CONFIG_FILE_1 -o /home/blincoln/abptts/config/10.87.134.12' % (sys.argv[0])
	print os.linesep
	print 'Example: %s -c CONFIG_FILE_1 -c CONFIG_FILE_2 -o /home/blincoln/abptts/config/supervulnerable.goingtogethacked.internet' % (sys.argv[0])
	print os.linesep
	print 'Data from configuration files is applied in sequential order, to allow partial customization files to be overlayed on top of more complete base files.'
	print os.linesep
	print 'IE if the same parameter is defined twice in the same file, the later value takes precedence, and if it is defined in two files, the value in whichever file is specified last on the command line takes precedence.'
	print os.linesep
	print '--output-filename specifies an alternate output filename for the configuration (as opposed to the default of "config.txt")'	
	print os.linesep
	print '-w specifies a template file to use for generating the response wrapper prefix/suffix - see the documentation for details'	
	print os.linesep
	print '--ignore-defaults prevents loading the default configuration as the base. For example, use this mode to merge two or more custom configuration overlay files without including options not explicitly defined in them. IMPORTANT: this will disable generation of server-side files (because if the defaults are not available, it would be very complicated to determine if all necessary parameters have been specified).'
	print os.linesep
	print '--wordlist allows specification of a custom wordlist file (for random parameter name/value generation) instead of the default.'
	print os.linesep
	print '--debug will enable verbose output.' 
Example #8
Source File: testing.py    From recruit with Apache License 2.0 6 votes vote down vote up
def convert_rows_list_to_csv_str(rows_list):
    """
    Convert list of CSV rows to single CSV-formatted string for current OS.

    This method is used for creating expected value of to_csv() method.

    Parameters
    ----------
    rows_list : list
        The list of string. Each element represents the row of csv.

    Returns
    -------
    expected : string
        Expected output of to_csv() in current OS
    """
    sep = os.linesep
    expected = sep.join(rows_list) + sep
    return expected 
Example #9
Source File: config.py    From ciftify with MIT License 6 votes vote down vote up
def freesurfer_version():
    '''
    Returns version info for freesurfer
    '''
    fs_path = find_freesurfer()
    if fs_path is None:
        raise EnvironmentError("Freesurfer cannot be found. Please check that "
            "it is installed.")
    try:
        fs_buildstamp = os.path.join(os.path.dirname(fs_path),
                'build-stamp.txt')
        with open(fs_buildstamp, "r") as text_file:
            bstamp = text_file.read()
    except:
        return "freesurfer build information not found."
    bstamp = bstamp.replace(os.linesep,'')
    info = "freesurfer:{0}Path: {1}{0}Build Stamp: {2}".format(
            '{}    '.format(os.linesep),fs_path, bstamp)
    return info 
Example #10
Source File: config.py    From ciftify with MIT License 6 votes vote down vote up
def fsl_version():
    '''
    Returns version info for FSL
    '''
    fsl_path = find_fsl()
    if fsl_path is None:
        raise EnvironmentError("FSL not found. Please check that it is "
                "installed")
    try:
        fsl_buildstamp = os.path.join(fsl_path, 'etc',
                'fslversion')
        with open(fsl_buildstamp, "r") as text_file:
            bstamp = text_file.read()
    except:
        return "FSL build information not found."
    bstamp = bstamp.replace(os.linesep,'')
    info = "FSL:{0}Path: {1}{0}Version: {2}".format('{}    '.format(os.linesep),
            fsl_path, bstamp)
    return info 
Example #11
Source File: ciftify_subject_fmri.py    From ciftify with MIT License 6 votes vote down vote up
def print_settings(self):
        logger.info("{}---### Start of User Settings ###---".format(os.linesep))
        logger.info('Arguments:')
        logger.info("\tInput_fMRI: {}".format(self.func_4D))
        logger.info('\t\tNumber of TRs: {}'.format(self.num_TR))
        logger.info('\t\tTR(ms): {}'.format(self.TR_in_ms))
        logger.info("\tCIFTIFY_WORKDIR: {}".format(self.work_dir))
        logger.info("\tSubject: {}".format(self.subject.id))
        logger.info("\tfMRI Output Label: {}".format(self.fmri_label))
        logger.info("\t{}".format(self.func_ref.descript))
        logger.info("\tSurface Registration Sphere: {}".format(self.surf_reg))
        logger.info("\tT1w intermiadate for registation: {}".format(self.registered_to_this_T1w))
        if self.smoothing.sigma > 0:
            logger.info("\tSmoothingFWHM: {}".format(self.smoothing.fwhm))
            logger.info("\tSmoothing Sigma: {}".format(self.smoothing.sigma))
        else:
            logger.info("\tNo smoothing will be applied")
        if self.dilate_percent_below:
            logger.info("\tWill fill holes defined as data with intensity below {} percentile".format(self.dilate_percent_below))
        logger.info('\tMulthreaded subprocesses with use {} threads'.format(self.n_cpus))
        logger.info("{}---### End of User Settings ###---".format(os.linesep))
        logger.info("\nThe following settings are set by default:")
        logger.info("\tGrayordinatesResolution: {}".format(self.grayord_res))
        logger.info('\tLowResMesh: {}k'.format(self.low_res)) 
Example #12
Source File: password-pwncheck.py    From password_pwncheck with MIT License 6 votes vote down vote up
def logmsg(request,type,message,args):
    is_dst = time.daylight and time.localtime().tm_isdst > 0
    tz =  - (time.altzone if is_dst else time.timezone) / 36
    if tz>=0:
        tz="+%04d"%tz
    else:
        tz="%05d"%tz
    datestr = '%d/%b/%Y %H:%M:%S'
    user = getattr(logStore,'user','')
    isValid = getattr(logStore,'isValid','')
    code = getattr(logStore,'code','')
    args = getLogDateTime(args)
    log = '%s %s,%s,%s,%s,%s,%s' % (datetime.now().strftime(datestr),tz,request.address_string(),user,isValid,code, message % args)
    with logLock:
        with open(cfg.logpath,'a') as fw:
            fw.write(log+os.linesep)
    return log 
Example #13
Source File: test_utils.py    From Watson with MIT License 6 votes vote down vote up
def test_build_csv_multiple_cols():
    lt = os.linesep
    dm = csv.get_dialect('excel').delimiter
    data = [
        co.OrderedDict([('col1', 'value'),
                        ('col2', 'another value'),
                        ('col3', 'more')]),
        co.OrderedDict([('col1', 'one value'),
                        ('col2', 'two value'),
                        ('col3', 'three')])
    ]
    result = lt.join([
        dm.join(['col1', 'col2', 'col3']),
        dm.join(['value', 'another value', 'more']),
        dm.join(['one value', 'two value', 'three'])
        ]) + lt
    assert build_csv(data) == result


# sorted_groupby 
Example #14
Source File: __init__.py    From pyhanlp with Apache License 2.0 6 votes vote down vote up
def write_config(root=None):
    if root and os.name == 'nt':
        root = root.replace('\\', '/')  # For Windows
    if root and platform.system().startswith('CYGWIN'):  # For cygwin
        if root.startswith('/usr/lib'):
            cygwin_root = os.popen('cygpath -w /').read().strip().replace('\\', '/')
            root = cygwin_root + root[len('/usr'):]
        elif STATIC_ROOT.startswith('/cygdrive'):
            driver = STATIC_ROOT.split('/')
            cygwin_driver = '/'.join(driver[:3])
            win_driver = driver[2].upper() + ':'
            root = root.replace(cygwin_driver, win_driver)
    content = []
    with open_(PATH_CONFIG, encoding='utf-8') as f:
        for line in f:
            if root:
                if line.startswith('root'):
                    line = 'root={}{}'.format(root, os.linesep)
            content.append(line)
    with open_(PATH_CONFIG, 'w', encoding='utf-8') as f:
        f.writelines(content) 
Example #15
Source File: penn_treebank.py    From lineflow with MIT License 6 votes vote down vote up
def get_penn_treebank() -> Dict[str, List[str]]:

    url = 'https://raw.githubusercontent.com/wojzaremba/lstm/master/data/ptb.{}.txt'
    root = download.get_cache_directory(os.path.join('datasets', 'ptb'))

    def creator(path):
        dataset = {}
        for split in ('train', 'dev', 'test'):
            data_path = gdown.cached_download(url.format(split if split != 'dev' else 'valid'))
            with io.open(data_path, 'rt') as f:
                dataset[split] = [line.rstrip(os.linesep) for line in f]

        with io.open(path, 'wb') as f:
            pickle.dump(dataset, f)
        return dataset

    def loader(path):
        with io.open(path, 'rb') as f:
            return pickle.load(f)

    pkl_path = os.path.join(root, 'ptb.pkl')
    return download.cache_or_load_file(pkl_path, creator, loader) 
Example #16
Source File: streams.py    From TerminalView with MIT License 6 votes vote down vote up
def __init__(self, to=sys.stdout, only=(), *args, **kwargs):
        super(DebugStream, self).__init__(*args, **kwargs)

        def safe_str(chunk):
            if isinstance(chunk, bytes):
                chunk = chunk.decode("utf-8")
            elif not isinstance(chunk, str):
                chunk = str(chunk)

            return chunk

        class Bugger(object):
            __before__ = __after__ = lambda *args: None

            def __getattr__(self, event):
                def inner(*args, **kwargs):
                    to.write(event.upper() + " ")
                    to.write("; ".join(map(safe_str, args)))
                    to.write(" ")
                    to.write(", ".join("{0}: {1}".format(k, safe_str(v))
                                       for k, v in kwargs.items()))
                    to.write(os.linesep)
                return inner

        self.attach(Bugger(), only=only) 
Example #17
Source File: tandem_plugin.py    From tandem with Apache License 2.0 6 votes vote down vote up
def _handle_apply_patches(self, message):
        for patch in message.patch_list:
            start = patch["oldStart"]
            end = patch["oldEnd"]
            text = patch["newText"]

            target_buffer_contents = self._target_buffer[:]

            before_in_new_line = target_buffer_contents[start["row"]][:start["column"]]
            after_in_new_line = target_buffer_contents[end["row"]][end["column"]:]

            new_lines = text.split(os.linesep)
            if len(new_lines) > 0:
                new_lines[0] = before_in_new_line + new_lines[0]
            else:
                new_lines = [before_in_new_line]

            new_lines[-1] = new_lines[-1] + after_in_new_line

            self._target_buffer[start["row"] : end["row"] + 1] = new_lines

        self._buffer_contents = self._target_buffer[:]
        self._vim.command(":redraw") 
Example #18
Source File: test_smbclient_os.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_write_exclusive_text_file(smb_share):
    file_path = "%s\\%s" % (smb_share, "file.txt")
    file_contents = u"File Contents\nNewline"

    with smbclient.open_file(file_path, mode='x') as fd:
        assert isinstance(fd, io.TextIOWrapper)
        assert fd.closed is False

        with pytest.raises(IOError):
            fd.read()

        assert fd.tell() == 0
        fd.write(file_contents)
        assert int(fd.tell()) == (len(file_contents) - 1 + len(os.linesep))

    assert fd.closed is True

    with smbclient.open_file(file_path, mode='r') as fd:
        assert fd.read() == file_contents

    with pytest.raises(OSError, match=re.escape("[NtStatus 0xc0000035] File exists: ")):
        smbclient.open_file(file_path, mode='x')

    assert fd.closed is True 
Example #19
Source File: git_multimail_upstream.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def check_setup(environment):
    environment.check()
    show_env(environment, sys.stdout)
    sys.stdout.write(
        "Now, checking that git-multimail's standard input "
        "is properly set ..." + os.linesep
    )
    sys.stdout.write(
        "Please type some text and then press Return" + os.linesep
    )
    stdin = sys.stdin.readline()
    sys.stdout.write("You have just entered:" + os.linesep)
    sys.stdout.write(stdin)
    sys.stdout.write("git-multimail seems properly set up." + os.linesep) 
Example #20
Source File: test_utils.py    From Watson with MIT License 5 votes vote down vote up
def test_build_csv_one_col():
    lt = os.linesep
    data = [{'col': 'value'}, {'col': 'another value'}]
    result = lt.join(['col', 'value', 'another value']) + lt
    assert build_csv(data) == result 
Example #21
Source File: replication_test.py    From cassandra-dtest with Apache License 2.0 5 votes vote down vote up
def wait_for_nodes_on_racks(self, nodes, expected_racks):
        """
        Waits for nodes to match the expected racks.
        """
        regex = re.compile(r"^UN(?:\s*)127\.0\.0(?:.*)\s(.*)$", re.IGNORECASE)
        for i, node in enumerate(nodes):
            wait_expire = time.time() + 120
            while time.time() < wait_expire:
                out, err, _ = node.nodetool("status")

                logger.debug(out)
                if len(err.strip()) > 0:
                    logger.debug("Error trying to run nodetool status: {}".format(err))

                racks = []
                for line in out.split(os.linesep):
                    m = regex.match(line)
                    if m:
                        racks.append(m.group(1))
                racks.sort() #order is not deterministic
                if racks == sorted(expected_racks.copy()):
                    # great, the topology change is propagated
                    logger.debug("Topology change detected on node {}".format(i))
                    break
                else:
                    logger.debug("Waiting for topology change on node {}".format(i))
                    time.sleep(5)
            else:
                raise RuntimeError("Ran out of time waiting for topology to change on node {}".format(i)) 
Example #22
Source File: scp_api.py    From single_cell_portal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def do_browser_login(self, dry_run=False):
        '''
        Authenticate through the browser

        :param dry_run: If true, will do a dry run with no actual execution of functionality.
        :return: Authentication token
        '''

        if self.verbose: print("BROWSER LOGIN")
        if dry_run:
            if self.verbose: print("DRY_RUN:: Did not login")
            return("DRY_RUN_TOKEN")
        cmdline.func_CMD(command="gcloud auth application-default login")
        cmd_ret = cmdline.func_CMD(command="gcloud auth application-default print-access-token",stdout=True)
        return(cmd_ret.decode("ASCII").strip(os.linesep)) 
Example #23
Source File: test_session.py    From tox with MIT License 5 votes vote down vote up
def test_command_prev_fail_command_skip_post_run(cmd, initproj, mock_venv):
    initproj(
        "pkg_command_test_123-0.7",
        filedefs={
            "tox.ini": """
                [tox]
                envlist = py

                [testenv]
                commands_pre = python -c 'raise SystemExit(2)'
                commands = python -c 'print("command")'
                commands_post = python -c 'print("post")'
            """,
        },
    )
    result = cmd()
    result.assert_fail()
    expected = textwrap.dedent(
        """
            py run-test-pre: commands[0] | python -c 'raise SystemExit(2)'
            ERROR: InvocationError for command {} -c 'raise SystemExit(2)' (exited with code 2)
            py run-test-post: commands[0] | python -c 'print("post")'
            post
            ___________________________________ summary ___________________________________{}
            ERROR:   py: commands failed
        """.format(
            pipes.quote(sys.executable), "_" if sys.platform != "win32" else "",
        ),
    )
    have = result.out.replace(os.linesep, "\n")
    actual = have[len(have) - len(expected) :]
    assert actual == expected 
Example #24
Source File: test_session.py    From tox with MIT License 5 votes vote down vote up
def test_command_prev_post_ok(cmd, initproj, mock_venv):
    initproj(
        "pkg_command_test_123-0.7",
        filedefs={
            "tox.ini": """
            [tox]
            envlist = py

            [testenv]
            commands_pre = python -c 'print("pre")'
            commands = python -c 'print("command")'
            commands_post = python -c 'print("post")'
        """,
        },
    )
    result = cmd()
    result.assert_success()
    expected = textwrap.dedent(
        """
        py run-test-pre: commands[0] | python -c 'print("pre")'
        pre
        py run-test: commands[0] | python -c 'print("command")'
        command
        py run-test-post: commands[0] | python -c 'print("post")'
        post
        ___________________________________ summary ___________________________________{}
          py: commands succeeded
          congratulations :)
    """.format(
            "_" if sys.platform != "win32" else "",
        ),
    ).lstrip()
    have = result.out.replace(os.linesep, "\n")
    actual = have[len(have) - len(expected) :]
    assert actual == expected 
Example #25
Source File: test_parallel.py    From tox with MIT License 5 votes vote down vote up
def test_parallel_error_report(cmd, initproj, monkeypatch, live):
    monkeypatch.setenv(str("_TOX_SKIP_ENV_CREATION_TEST"), str("1"))
    initproj(
        "pkg123-0.7",
        filedefs={
            "tox.ini": """
            [tox]
            isolated_build = true
            envlist = a
            [testenv]
            skip_install = true
            commands=python -c "import sys, os; sys.stderr.write(str(12345) + os.linesep);\
             raise SystemExit(17)"
            whitelist_externals = {}
        """.format(
                sys.executable,
            ),
        },
    )
    args = ["-o"] if live else []
    result = cmd("-p", "all", *args)
    result.assert_fail()
    msg = result.out
    # for live we print the failure logfile, otherwise just stream through (no logfile present)
    assert "(exited with code 17)" in result.out, msg
    if not live:
        assert "ERROR: invocation failed (exit code 1), logfile:" in result.out, msg
    assert any(line for line in result.outlines if line == "12345"), result.out

    # single summary at end
    summary_lines = [j for j, l in enumerate(result.outlines) if " summary " in l]
    assert len(summary_lines) == 1, msg

    assert result.outlines[summary_lines[0] + 1 :] == ["ERROR:   a: parallel child exit code 1"] 
Example #26
Source File: spinner.py    From tox with MIT License 5 votes vote down vote up
def finalize(self, key, status, **kwargs):
        start_at = self._envs[key]
        del self._envs[key]
        if self.enabled:
            self.clear()
        self.stream.write(
            "{} {} in {}{}".format(
                status, key, td_human_readable(datetime.now() - start_at), os.linesep,
            ),
            **kwargs
        )
        if not self._envs:
            self.__exit__(None, None, None) 
Example #27
Source File: tb_gateway_remote_configurator.py    From thingsboard-gateway with Apache License 2.0 5 votes vote down vote up
def __update_logs_configuration(self):
        global LOG
        try:
            LOG = getLogger('service')
            logs_conf_file_path = self.__gateway.get_config_path() + 'logs.conf'
            new_logging_level = findall(r'level=(.*)', self.__new_logs_configuration.replace("NONE", "NOTSET"))[-1]
            new_logging_config = self.__new_logs_configuration.replace("NONE", "NOTSET").replace("\r\n", linesep)
            logs_config = ConfigParser(allow_no_value=True)
            logs_config.read_string(new_logging_config)
            for section in logs_config:
                if "handler_" in section and section != "handler_consoleHandler":
                    args = tuple(logs_config[section]["args"]
                                 .replace('(', '')
                                 .replace(')', '')
                                 .split(', '))
                    path = args[0][1:-1]
                    LOG.debug("Checking %s...", path)
                    if not exists(dirname(path)):
                        raise FileNotFoundError
            with open(logs_conf_file_path, 'w', encoding="UTF-8") as logs:
                logs.write(self.__new_logs_configuration.replace("NONE", "NOTSET")+"\r\n")
            fileConfig(logs_config)
            LOG = getLogger('service')
            # self.__gateway.remote_handler.deactivate()
            self.__gateway.remote_handler = TBLoggerHandler(self.__gateway)
            self.__gateway.main_handler.setLevel(new_logging_level)
            self.__gateway.main_handler.setTarget(self.__gateway.remote_handler)
            if new_logging_level == "NOTSET":
                self.__gateway.remote_handler.deactivate()
            else:
                self.__gateway.remote_handler.activate(new_logging_level)
            LOG.debug("Logs configuration has been updated.")
        except Exception as e:
            LOG.error("Remote logging configuration is wrong!")
            LOG.exception(e) 
Example #28
Source File: editor.py    From tandem with Apache License 2.0 5 votes vote down vote up
def _handle_check_document_sync(self, message):
        document_text_content = self._document.get_document_text()

        # TODO: ignore all other messages until we receive an ack
        contents = os.linesep.join(message.contents) + os.linesep

        if (contents != document_text_content):
            document_lines = document_text_content.split(os.linesep)
            apply_text = em.serialize(em.ApplyText(document_lines))
            io_data = self._std_streams.generate_io_data(apply_text)
            self._std_streams.write_io_data(io_data) 
Example #29
Source File: editor.py    From tandem with Apache License 2.0 5 votes vote down vote up
def _handle_check_document_sync(self, message):
        document_text_content = self._document.get_document_text()

        # TODO: ignore all other messages until we receive an ack
        contents = os.linesep.join(message.contents) + os.linesep

        if (contents != document_text_content):
            document_lines = document_text_content.split(os.linesep)
            apply_text = em.serialize(em.ApplyText(document_lines))
            io_data = self._std_streams.generate_io_data(apply_text)
            self._std_streams.write_io_data(io_data) 
Example #30
Source File: test_refactor.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_crlf_newlines(self):
        old_sep = os.linesep
        os.linesep = "\r\n"
        try:
            fn = os.path.join(TEST_DATA_DIR, "crlf.py")
            fixes = refactor.get_fixers_from_package("lib2to3.fixes")
            self.check_file_refactoring(fn, fixes)
        finally:
            os.linesep = old_sep