Exemple #1
0
def run_exec(exec: List[str], stdin: str, timeout: int) -> CompletedProcess:
    """Run an executable.

    Args:
        exec (List[str]): executable to run (can be followed by arguments).
        stdin (str): input of the program.
        timeout (int): timeout (in sec).

    Returns:
        CompletedProcess: the completed process.

    Raises:
        TimeoutExpired: if the timeout expired.
    """
    try:  # Python >= 3.7
        return sprun(exec,
                     input=stdin,
                     timeout=timeout,
                     capture_output=True,
                     text=True)
    except:  # Python < 3.7
        return sprun(exec,
                     input=stdin,
                     timeout=timeout,
                     stdout=PIPE,
                     stderr=PIPE,
                     universal_newlines=True)
Exemple #2
0
def open_macosx_terminal(
    cmd: Union[str, Iterable[str]],
    app: Optional[str] = 'Terminal.app',
    wait: bool = True,
    with_tempfile: bool = False,
    tempfile_suffix: str = '.command',
    shebang: str = '#!/bin/sh',
) -> CompletedProcess:
    open_cmd = ['open']
    if wait:
        open_cmd.append('-W')
    if app:
        open_cmd.extend(('-a', app))
    if with_tempfile:
        with NamedTemporaryFile(suffix=tempfile_suffix, mode='w') as f:
            sprun(['chmod', '+x', f.name], check=True)
            if not isinstance(cmd, str):
                cmd = shlex_join(cmd)
                cmd = cast(str, cmd)
            f.write('%s\n%s\n' % (shebang, cmd))
            f.flush()
            open_cmd.append(f.name)
            return sprun(open_cmd, check=True)
    else:
        if isinstance(cmd, str):
            open_cmd.append(cmd)
        else:
            open_cmd.extend(cmd)
        return sprun(open_cmd, check=True)
Exemple #3
0
def start_macosx_terminal(
    cmd: Union[str, Iterable[str]],
    app: str = 'Terminal.app',
    wait: bool = True,
    wait_event: Union[int, str,
                      AppleScriptWaitEvent] = AppleScriptWaitEvent.exists,
    with_tempfile: bool = False,
    tempfile_suffix: str = '.command',
    shebang: str = '#!/bin/sh',
) -> CompletedProcess:
    if not isinstance(cmd, str):
        cmd = shlex_join(cmd)
        cmd = cast(str, cmd)
    if wait:
        tpl_command = '''
tell application "{app}"
    activate
    set w to do script "{script}"
    repeat while w %s
        delay 0.1
    end repeat
end tell''' % _get_wait_for_str(wait_event)
    else:
        tpl_command = 'tell application "{app}" to do script "{script}"'
    if with_tempfile:
        with NamedTemporaryFile(suffix=tempfile_suffix, mode='w') as f:
            sprun(['chmod', '+x', f.name], check=True)
            f.write('%s\n%s\n' % (shebang, cmd))
            f.flush()
            command = tpl_command.format(app=app, script=f.name)
            return sprun(['osascript', '-e', command], check=True)
    else:
        command = tpl_command.format(app=app, script=cmd.replace('"', '\\"'))
        return sprun(['osascript', '-e', command], check=True)
Exemple #4
0
def install_dependencies():
    modulespath = modules_path()

    try:
        from subprocess import run as sprun
        try:
            import pip
        except:
            print("Installing pip... "),
            pyver = ""
            if sys.platform != "win32":
                pyver = "python{}.{}".format(sys.version_info.major,
                                             sys.version_info.minor)

            ensurepip = os.path.normpath(
                os.path.join(os.path.dirname(bpy.app.binary_path_python), "..",
                             "lib", pyver, "ensurepip"))
            # install pip using the user scheme using the Python
            # version bundled with Blender
            res = sprun([bpy.app.binary_path_python, ensurepip, "--user"])

            if res.returncode == 0:
                import pip
            else:
                raise Exception("Failed to install pip.")

        print("Installing rhino3dm to {}... ".format(modulespath)),

        # if we eventually want to pin a certain version
        # we can add here something like "==0.0.5".
        # for now assume latest available is ok
        rhino3dm_version = ""

        pip3 = "pip3"
        if sys.platform == "darwin":
            pip3 = os.path.normpath(
                os.path.join(os.path.dirname(bpy.app.binary_path_python), "..",
                             "bin", pip3))

        # call pip in a subprocess so we don't have to mess
        # with internals. Also, this ensures the Python used to
        # install pip is going to be used
        res = sprun([
            pip3, "install", "--upgrade", "--target", modulespath,
            "rhino3dm{}".format(rhino3dm_version)
        ])
        if res.returncode != 0:
            print(
                "Please try manually installing rhino3dm with: pip3 install --upgrade --target {} rhino3dm"
                .format(modulespath))
            raise Exception(
                "Failed to install rhino3dm. See console for manual install instruction."
            )
    except:
        raise Exception(
            "Failed to install dependencies. Please make sure you have pip installed."
        )
Exemple #5
0
def test_mkdir(tmpworkdir, u8):
    if 'win' in sys.platform:
        return True
    sprun(txcmd + " " + Z + fr" - . -c 'a/b/d.c/d..a/u,v,x,g\.x'", shell=True)
    t1 = txdir.TxDir.fromfs('a')
    shutil.rmtree('a')
    sprun('mkdir -p a/{b,c}/d a/u a/v a/x a/g.x', shell=True)
    t2 = txdir.TxDir.fromfs('a')
    shutil.rmtree('a')
    tt1 = t1.view()
    tt2 = t2.view()
    assert tt1 == tt2
Exemple #6
0
def test_cmd_copydir(b_with_a, u8):
    r = sprun(txcmd + " " + Z + " b | " + txcmd + " " + Z + " - witha",
              shell=True)
    assert r.returncode == 0
    assert os.path.exists('witha/a')
    assert os.path.isdir('witha/a')
    shutil.rmtree('witha')
Exemple #7
0
 def run(self):
     cp = sprun(RADEX_BUILD,
                stdout=PIPE,
                stderr=PIPE,
                cwd='ndradex/bin',
                check=True)
     build.run(self)
Exemple #8
0
def b_with_a(tmpworkdir):
    r = sprun(f"echo a/ | " + txcmd + " " + Z + " - b", shell=True)
    assert r.returncode == 0
    assert os.path.exists('b/a')
    assert os.path.isdir('b/a')
    yield r
    shutil.rmtree('b')
Exemple #9
0
def check_unit(name: str):
    # lazy way to check if it's linked
    if not os.path.isfile('/etc/systemd/system/' + name + '.service'):
        return UNLINKED

    is_enabled = sprun(['systemctl', 'is-enabled', name], stdout=PIPE, stderr=PIPE)
    if is_enabled.stdout.startswith(b'linked'):
        return DISABLED

    is_active = sprun(['systemctl', 'is-active', name], stdout=PIPE, stderr=PIPE)
    if is_active.stdout.startswith(b'inactive'):
        return NOT_RUNNING
    elif is_active.stdout.startswith(b'failed'):
        return FAILED
    elif is_active.stdout.startswith(b'active'):
        return RUNNING

    return UNKNOWN
def install_dependencies():
    # Copied and adapted from https://github.com/jesterKing/import_3dm/blob/9f96e644e40edd571829cbaf777d6bda63dbb5db/import_3dm/read3dm.py
    modulespath = modules_path()

    try:
        from subprocess import run as sprun
        try:
            import pip
        except:
            print("LilySurfaceScrapper: Installing pip... "),
            pyver = ""
            if sys.platform != "win32":
                pyver = "python{}.{}".format(
                    sys.version_info.major,
                    sys.version_info.minor
                )

            ensurepip = os.path.normpath(
                os.path.join(
                    os.path.dirname(bpy.app.binary_path_python),
                    "..", "lib", pyver, "ensurepip"
                )
            )
            # install pip using the user scheme using the Python
            # version bundled with Blender
            res = sprun([bpy.app.binary_path_python, ensurepip, "--user"])

            if res.returncode == 0:
                import pip
            else:
                raise Exception("Failed to install pip.")

        print("LilySurfaceScrapper: Installing lxml to {}... ".format(modulespath)),

        # call pip in a subprocess so we don't have to mess
        # with internals. Also, this ensures the Python used to
        # install pip is going to be used
        res = sprun([bpy.app.binary_path_python, "-m", "pip", "install", "--upgrade", "--target", modulespath, "lxml"])
        if res.returncode!=0:
            print("LilySurfaceScrapper: Please try manually installing lxml with: pip3 install --upgrade --target {} lxml".format(modulespath))
            raise Exception("Failed to install lxml. See console for manual install instruction.")
    except:
        raise Exception("Failed to install dependencies. Please make sure you have pip installed.")
Exemple #11
0
def start_windows_terminal(
    cmd: Union[str, Iterable[str]],
    app: Optional[str] = 'powershell',
    wait: bool = True,
    with_tempfile: bool = False,
    tempfile_suffix: str = '.cmd',
    app_args: Union[None, Tuple[str]] = None,
) -> CompletedProcess:
    start_cmd = ['start']
    if wait:
        start_cmd.append('/wait')
    if app:
        start_cmd.append(app)
        if app_args is None:
            if app in ('cmd', 'cmd.exe'):
                start_cmd.append('/c')
        else:
            start_cmd.extend(app_args)
    if with_tempfile:
        # In Windows, file is occupied when is opening, until it is closed.
        # Like lock, anyone cannot open the file while it is occupied.
        # So we should close it first, then give it to any other, and finally delete it.
        f = NamedTemporaryFile(suffix=tempfile_suffix, mode='w', delete=False)
        try:
            with f:
                if not isinstance(cmd, str):
                    cmd = ' '.join(map(_win_quote, cmd))
                    cmd = cast(str, cmd)
                f.write(cmd)
            start_cmd.append(f.name)
            return sprun(start_cmd, check=True, shell=True)
        finally:
            # TODO: We may need to wait until the file is no longer occupied before deleting it.
            os.remove(f.name)
    else:
        if isinstance(cmd, str):
            if app in ('powershell', 'powershell.exe'):
                # [The call operator &](https://ss64.com/ps/call.html)
                start_cmd.append("& " + cmd)
        else:
            start_cmd.extend(cmd)
        return sprun(start_cmd, check=True, shell=True)
Exemple #12
0
def install_dependencies():
    import sys
    import os
    try:
        try:
            import pip
        except:
            print("Installing pip... "),
            from subprocess import run as sprun
            res = sprun([bpy.app.binary_path_python, "-m", "ensurepip"])

            if res.returncode == 0:
                import pip
            else:
                raise Exception("Failed to install pip.")

        modulespath = modules_path()

        if not os.path.exists(modulespath):
            os.makedirs(modulespath)

        print("Installing speckle to {}... ".format(modulespath)),
        from subprocess import run as sprun
        res = sprun([
            bpy.app.binary_path_python, "-m", "pip", "install", "-q", "-t",
            "{}".format(modulespath), "--no-deps", "pydantic"
        ])
        res = sprun([
            bpy.app.binary_path_python, "-m", "pip", "install", "-q", "-t",
            "{}".format(modulespath), "speckle"
        ])

    except:
        raise Exception(
            "Failed to install dependencies. Please make sure you have pip installed."
        )
Exemple #13
0
def run(input,
        radex=None,
        timeout=None,
        cleanup=True,
        logfile='radex.log',
        encoding='utf-8'):
    """Run RADEX and get result as tuple of string.

    Note that this function only reads the last line of RADEX outfile.
    This means that only the values of the transition at the highest
    frequency spacified in the RADEX input will be returned.

    Args:
        input (str or sequence): RADEX input. See examples below.
        radex (str or path, optional): RADEX path. If not spacified,
            then the builtin RADEX with uniform geometry will be used.
        timeout (int, optional): Timeout of a RADEX run in units of second.
            Default is None (unlimited run time is permitted).
        cleanup (bool, optional): If True (default), then the RADEX outfile
            (e.g. radex.out) and logfile (e.g., radex.log) will be deleted.
        logfile (str or path, optional): Path of logfile. This is only used
            for identifying the path of logfile in the cleanup method.
        encoding (str, optional): File encofing. Default is utf-8.

    Returns:
        output (tuple of str): RADEX output values.

    Examples:
        To get the values of CO(1-0) @ T_kin = 100 K, n_H2 = 1e3 cm^-3,
        N_CO = 1e15 cm^-2, T_bg = 2.73 K, and dv = 1.0 km s^-1:

            >>> input = ['co.dat', 'radex.out', '110 120', '100',
                        '1', 'H2', '1e3', '2.73', '1e15', '1.0', 0]
            >>> output = run(input)

    """
    if radex is None:
        radex = ndradex.RADEX_BINPATH / 'radex-uni'

    try:
        input, outfile = ensure_input(input, encoding)
    except (AttributeError, IndexError, TypeError):
        logger.warning('RADEX did not run due to invalid input')
        return ERROR_OUTPUT

    try:
        cp = sprun([radex],
                   input=input,
                   timeout=timeout,
                   stdout=PIPE,
                   stderr=PIPE,
                   check=True)
        return ensure_output(cp, outfile, encoding)
    except FileNotFoundError:
        logger.warning('RADEX path or moldata does not exist')
        return ERROR_OUTPUT
    except CalledProcessError:
        logger.warning('RADEX failed due to invalid input')
        return ERROR_OUTPUT
    except TimeoutExpired:
        logger.warning('RADEX interrupted due to timeout')
        return ERROR_OUTPUT
    except RuntimeError:
        logger.warning('RADEX version is not valid')
        return ERROR_OUTPUT
    finally:
        if cleanup:
            remove_file(logfile)
            remove_file(outfile)
Exemple #14
0
def run(x, **kwargs):
    if 'win' in sys.platform:
        return sprun(x, shell=True, **kwargs)
    else:
        return sprun(x, shell=False, **kwargs)
Exemple #15
0
from os import getcwd, listdir
from subprocess import run as sprun

dirpath = getcwd()
print(dirpath)

# テキストファイルのリスト
files = listdir(dirpath)
print(files)

count = 1
while True:
    check_in = f'in_{count}.txt'
    if check_in not in files:
        break

    check_sp = sprun(['python', 'main.py', f'< {check_in}'])

    with open(f'{dirpath}/out_{count}.txt', 'r') as f:
        check_out = f.read()

    if check_sp.stdout == check_out:
        print('AC')
    else:
        print('WA')

    count += 1
Exemple #16
0
def test_cmd_file1(tmpworkdir, u8):
    r = sprun("echo a | " + txcmd + " " + Z + " - .", shell=True)
    assert r.returncode == 0
    assert os.path.exists('a')
    with pytest.raises(NotADirectoryError):
        shutil.rmtree('a')
Exemple #17
0
def test_cmd_dir1(tmpworkdir, u8):
    r = sprun(f"echo a/ | " + txcmd + " " + Z + " - .", shell=True)
    assert r.returncode == 0
    assert os.path.exists('a')
    shutil.rmtree('a')