Python distutils.spawn 模块,find_executable() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用distutils.spawn.find_executable()

项目:tvlinker    作者:ozmartian    | 项目源码 | 文件源码
def __init__(self, link_url: str, dl_path: str, parent=None):
        super(Downloader, self).__init__(parent)
        self.parent = parent
        self.dltool_cmd = find_executable(self.download_cmd)
        self.download_link = link_url
        self.download_path = dl_path
        if self.dltool_cmd.strip():
            self.dltool_args = self.dltool_args.format(dl_path=self.download_path, dl_link=self.download_link)
            self.console = QTextEdit(self.parent)
            self.console.setWindowTitle('%s Downloader' % qApp.applicationName())
            self.proc = QProcess(self.parent)
            layout = QVBoxLayout()
            layout.addWidget(self.console)
            self.setLayout(layout)
            self.setFixedSize(QSize(400, 300))
        else:
            QMessageBox.critical(self.parent, 'DOWNLOADER ERROR', '<p>The <b>aria2c</b> executable binary could not ' +
                                 'be found in your installation folders. The binary comes packaged with this ' +
                                 'application so it is likely that it was accidentally deleted via human ' +
                                 'intervntion or incorrect file permissions are preventing access to it.</p>' +
                                 '<p>You may either download and install <b>aria2</b> manually yourself, ensuring ' +
                                 'its installation location is globally accessible via PATH environmnt variables or ' +
                                 'simply reinstall this application again. If the issue is not resolved then try ' +
                                 'to download the application again incase the orignal you installed already was ' +
                                 'corrupted/broken.', buttons=QMessageBox.Close)
项目:qr-lipsync    作者:UbiCastTeam    | 项目源码 | 文件源码
def get_media_info(self, media_file):
        try:
            ffprobe = shutil.which('ffprobe')
        except Exception:
            # python2
            from distutils.spawn import find_executable
            ffprobe = find_executable('ffprobe')
        if ffprobe: 
            cmd = "ffprobe -v error -select_streams v -show_entries stream=width,height,avg_frame_rate,duration -of default=noprint_wrappers=1 -print_format json %s" % media_file
            result = subprocess.check_output(cmd.split(' '), universal_newlines=True)
            vjres = json.loads(result)['streams'][0]
            if not vjres.get('duration'):
                cmd = "ffprobe -v error -select_streams v -show_format_entry duration -of default=noprint_wrappers=1 -print_format json %s" % media_file
                result = subprocess.check_output(cmd.split(' '), universal_newlines=True)
                vjres['duration'] = json.loads(result)['format']['duration']
            cmd = "ffprobe -v error -select_streams a -show_entries stream=sample_rate -of default=noprint_wrappers=1 -print_format json %s" % media_file
            result = subprocess.check_output(cmd.split(' '), universal_newlines=True)
            ajres = json.loads(result)['streams'][0]
            vjres['sample_rate'] = ajres['sample_rate']
            return vjres
        else:
            logger.error('ffprobe is required')
            sys.exit()
项目:tile-generator    作者:cf-platform-eng    | 项目源码 | 文件源码
def ensure_bosh():
    bosh_exec = spawn.find_executable('bosh')
    ## check the version
    ## bosh --version
    ## version 2.0.1-74fad57-2017-02-15T20:17:00Z
    ##
    ## Succeeded
    ## bosh --version
    ## BOSH 1.3262.26.0

    if not bosh_exec:
        print("'bosh' command should be on the path. See https://bosh.io for installation instructions")
        sys.exit(1)

    if bosh_exec:
        output = subprocess.check_output(["bosh", "--version"], stderr=subprocess.STDOUT, cwd=".")
        if not output.startswith("version 2."):
            print("You are running older bosh version. Please upgrade to 'bosh 2.0' command should be on the path. See https://bosh.io/docs/cli-v2.html for installation instructions")
            sys.exit(1)
项目:dingdang-robot    作者:wzpan    | 项目源码 | 文件源码
def check_executable(executable):
    """
    Checks if an executable exists in $PATH.

    Arguments:
        executable -- the name of the executable (e.g. "echo")

    Returns:
        True or False
    """
    logger = logging.getLogger(__name__)
    logger.debug("Checking executable '%s'...", executable)
    executable_path = find_executable(executable)
    found = executable_path is not None
    if found:
        logger.debug("Executable '%s' found: '%s'", executable,
                     executable_path)
    else:
        logger.debug("Executable '%s' not found", executable)
    return found
项目:piqueserver    作者:piqueserver    | 项目源码 | 文件源码
def get_git_rev():
    if not os.path.exists(".git"):
        return 'snapshot'

    from distutils.spawn import find_executable
    if find_executable("git") is None:
        return 'gitless'

    import subprocess
    pipe = subprocess.Popen(
        ["git", "rev-parse", "HEAD"],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    ret = pipe.stdout.read()[:40]
    if not ret:
        return 'unknown'
    return ret
项目:auditwheel    作者:pypa    | 项目源码 | 文件源码
def verify_patchelf():
    """This function looks for the ``patchelf`` external binary in the PATH,
    checks for the required version, and throws an exception if a proper
    version can't be found. Otherwise, silcence is golden
    """
    if not find_executable('patchelf'):
        raise ValueError('Cannot find required utility `patchelf` in PATH')
    try:
        version = check_output(['patchelf', '--version']).decode('utf-8')
    except CalledProcessError:
        raise ValueError('Could not call `patchelf` binary')

    m = re.match('patchelf\s+(\d+(.\d+)?)', version)
    if m and tuple(int(x) for x in m.group(1).split('.')) >= (0, 9):
        return
    raise ValueError(('patchelf %s found. auditwheel repair requires '
                      'patchelf >= 0.9.') %
                     version)
项目:networking-ovn    作者:netgroup-polito    | 项目源码 | 文件源码
def start(self):
        for ovsdb_process in self.ovsdb_server_processes:
            # create the db from the schema using ovsdb-tool
            ovsdb_tool_cmd = [spawn.find_executable('ovsdb-tool'),
                              'create', ovsdb_process['db_path'],
                              ovsdb_process['schema_path']]
            utils.execute(ovsdb_tool_cmd)

            # start the ovsdb-server
            ovsdb_server_cmd = [
                spawn.find_executable('ovsdb-server'),
                '--detach', '-vconsole:off',
                '--log-file=%s' % (ovsdb_process['log_file_path']),
                '--remote=punix:%s' % (ovsdb_process['remote_path']),
                '--unixctl=%s' % (ovsdb_process['unixctl_path']),
                ovsdb_process['db_path']]
            utils.execute(ovsdb_server_cmd)
项目:electron-crash-reporter    作者:lipis    | 项目源码 | 文件源码
def find_gae_path():
  global GAE_PATH
  if GAE_PATH:
    return GAE_PATH
  if IS_WINDOWS:
    gae_path = None
    for path in os.environ['PATH'].split(os.pathsep):
      if os.path.isfile(os.path.join(path, 'dev_appserver.py')):
        gae_path = path
  else:
    gae_path = spawn.find_executable('dev_appserver.py')
    if gae_path:
      gae_path = os.path.dirname(os.path.realpath(gae_path))
  if not gae_path:
    return ''
  gcloud_exec = 'gcloud.cmd' if IS_WINDOWS else 'gcloud'
  if not os.path.isfile(os.path.join(gae_path, gcloud_exec)):
    GAE_PATH = gae_path
  else:
    gae_path = os.path.join(gae_path, '..', 'platform', 'google_appengine')
    if os.path.exists(gae_path):
      GAE_PATH = os.path.realpath(gae_path)
  return GAE_PATH
项目:flanders    作者:bast    | 项目源码 | 文件源码
def run_cmake():
    """
    Runs CMake to determine configuration for this build.
    """
    if _spawn.find_executable('cmake') is None:
        print("CMake is required to build this package.")
        print("Please install/load CMake and re-run setup.")
        sys.exit(-1)

    _build_dir = os.path.join(os.path.split(__file__)[0], 'build')
    _dir_util.mkpath(_build_dir)
    os.chdir(_build_dir)

    try:
        _spawn.spawn(['cmake', '-DCMAKE_BUILD_TYPE=release', '-DENABLE_OPENMP=True', '..'])
    except _spawn.DistutilsExecError:
        print("Error while running CMake")
        sys.exit(-1)
项目:logrotated    作者:nir0s    | 项目源码 | 文件源码
def rotate(paths, name, deploy=False, generic=False, verbose=False, **params):
    lgr.setLevel(logging.DEBUG if verbose else logging.INFO)

    if generic:
        params = _generate_generic_config(params)
    if deploy and not find_executable('logrotate'):
        lgr.error('logrotate was not found on this system. aborting deploy.')
        sys.exit(1)
    params.update(dict(paths=paths, name=name))
    logrotate_config_path = _generate_tmp_file_path(name)
    lgr.info('Generating logrotate config...')
    _generate_from_template(logrotate_config_path, **params)

    if deploy:
        logrotate_destination_path = os.path.join(LOGROTATED_PATH, name)
        _deploy_logrotate_config(
            logrotate_config_path,
            logrotate_destination_path)
项目:logrotated    作者:nir0s    | 项目源码 | 文件源码
def _test_generate(self, sys):
        if sys == 'nssm':
            self.cmd = find_executable('python') or 'c:\\python27\\python'
        else:
            self.cmd = find_executable('python2') or '/usr/bin/python2'
        self.args = '-m SimpleHTTPServer'
        opts = {
            '-n': self.service,
            '-a': self.args,
            '-v': None,
            '--overwrite': None,
            '--init-system=': sys
        }
        additional_opts = {
            '--nice=': '5',
            '--limit-coredump=': '10',
            '--limit-physical-memory=': '20',
            '--var=': 'KEY1=VALUE1'
        }
        opts.update(additional_opts)
        self.init_script = self._get_file_for_system(sys)
        _invoke_click('generate', [self.cmd], opts)
        self.assertTrue(self.init_script)
        with open(self.init_script) as generated_file:
            self.content = generated_file.read()
项目:meet-notes    作者:lipis    | 项目源码 | 文件源码
def find_gae_path():
  global GAE_PATH
  if GAE_PATH:
    return GAE_PATH
  if IS_WINDOWS:
    gae_path = None
    for path in os.environ['PATH'].split(os.pathsep):
      if os.path.isfile(os.path.join(path, 'dev_appserver.py')):
        gae_path = path
  else:
    gae_path = spawn.find_executable('dev_appserver.py')
    if gae_path:
      gae_path = os.path.dirname(os.path.realpath(gae_path))
  if not gae_path:
    return ''
  gcloud_exec = 'gcloud.cmd' if IS_WINDOWS else 'gcloud'
  if not os.path.isfile(os.path.join(gae_path, gcloud_exec)):
    GAE_PATH = gae_path
  else:
    gae_path = os.path.join(gae_path, '..', 'platform', 'google_appengine')
    if os.path.exists(gae_path):
      GAE_PATH = os.path.realpath(gae_path)
  return GAE_PATH
项目:dd-trace-py    作者:DataDog    | 项目源码 | 文件源码
def main():
    if len(sys.argv) < 2 or sys.argv[1] == "-h":
        print(USAGE)
        return

    log.debug("sys.argv: %s", sys.argv)

    root_dir = _ddtrace_root()
    log.debug("ddtrace root: %s", root_dir)

    bootstrap_dir = os.path.join(root_dir, 'bootstrap')
    log.debug("ddtrace bootstrap: %s", bootstrap_dir)

    _add_bootstrap_to_pythonpath(bootstrap_dir)
    log.debug("PYTHONPATH: %s", os.environ['PYTHONPATH'])
    log.debug("sys.path: %s", sys.path)

    executable = sys.argv[1]

    # Find the executable path
    executable = spawn.find_executable(executable)
    log.debug("program executable: %s", executable)

    os.execl(executable, executable, *sys.argv[2:])
项目:vote4code    作者:welovecoding    | 项目源码 | 文件源码
def find_gae_path():
  global GAE_PATH
  if GAE_PATH:
    return GAE_PATH
  if IS_WINDOWS:
    gae_path = None
    for path in os.environ['PATH'].split(os.pathsep):
      if os.path.isfile(os.path.join(path, 'dev_appserver.py')):
        gae_path = path
  else:
    gae_path = spawn.find_executable('dev_appserver.py')
    if gae_path:
      gae_path = os.path.dirname(os.path.realpath(gae_path))
  if not gae_path:
    return ''
  gcloud_exec = 'gcloud.cmd' if IS_WINDOWS else 'gcloud'
  if not os.path.isfile(os.path.join(gae_path, gcloud_exec)):
    GAE_PATH = gae_path
  else:
    gae_path = os.path.join(gae_path, '..', 'platform', 'google_appengine')
    if os.path.exists(gae_path):
      GAE_PATH = os.path.realpath(gae_path)
  return GAE_PATH
项目:freezer-dr    作者:openstack    | 项目源码 | 文件源码
def __init__(self, host, username, password, verbose=False,
                 interface='lanplus'):
        self._IPMI = spawn.find_executable('ipmitool')
        if not self._IPMI:
            self._IPMI = spawn.find_executable('ipmitool',
                                               path=':'.join(sys.path))
        if interface not in self._SUPPORTED_INTERFACES:
            raise Exception("Provided Interface is not supported")

        self._host = host
        self._username = username
        self._password = password
        self._verbose = verbose
        self._interface = interface

        self._update_cmd_credentials(
            host=host,
            username=username,
            password=password,
            interface=interface
        )
        LOG.debug('IPMI Interface initialized')
项目:run-google-java-format    作者:plume-lib    | 项目源码 | 文件源码
def under_git(dir, filename):
    """Return true if filename in dir is under git control."""
    if not spawn.find_executable("git"):
        if debug:
            print("no git executable found")
        return False
    FNULL = open(os.devnull, 'w')
    p = subprocess.Popen(["git", "ls-files", filename, "--error-unmatch"], cwd=dir, stdout=FNULL, stderr=subprocess.STDOUT)
    p.wait()
    if debug:
        print("p.returncode", p.returncode)
    return p.returncode == 0

# Don't replace local with remote if local is under version control.
# It would be better to just test whether the remote is newer than local,
# But raw GitHub URLs don't have the necessary last-modified information.
项目:run-google-java-format    作者:plume-lib    | 项目源码 | 文件源码
def under_git(dir, filename):
    """Return true if filename in dir is under git control."""
    if not spawn.find_executable("git"):
        if debug:
            print("no git executable found")
        return False
    FNULL = open(os.devnull, 'w')
    p = subprocess.Popen(["git", "ls-files", filename, "--error-unmatch"], cwd=dir, stdout=FNULL, stderr=subprocess.STDOUT)
    p.wait()
    if debug:
        print("p.returncode", p.returncode)
    return p.returncode == 0

# Don't replace local with remote if local is under version control.
# It would be better to just test whether the remote is newer than local,
# But raw GitHub URLs don't have the necessary last-modified information.
项目:vidcutter    作者:ozmartian    | 项目源码 | 文件源码
def findBackends() -> Munch:
        tools = Munch(ffmpeg=None, ffprobe=None, mediainfo=None)
        for backend in tools.keys():
            for exe in VideoService.config.binaries[os.name][backend]:
                binpath = QDir.toNativeSeparators('{0}/bin/{1}'.format(VideoService.getAppPath(), exe))
                if binpath is not None and os.path.isfile(binpath):
                    tools[backend] = binpath
                    break
                else:
                    binpath = find_executable(exe)
                    if binpath is not None and os.path.isfile(binpath):
                        tools[backend] = binpath
                        break
        if tools.ffmpeg is None:
            raise FFmpegNotFoundException('Could not locate any ffmpeg or libav executable on your operating system')
        return tools
项目:beesly    作者:bincyber    | 项目源码 | 文件源码
def get_group_membership(username):
    """
    Returns a list of groups the user is a member of to support Role-Based Access Control.
    The `id` command is used because it reports all (POSIX) groups that the user
    is a member of including external groups from Identity Management systems (AD, IdM, FreeIPA).

    Arguments
    ----------
    username : string
      the username to get group membership for
    """
    exe = find_executable('id')
    p = subprocess.Popen([exe, '-Gn', username], stdout=subprocess.PIPE)
    groups = p.stdout.read().split()
    groups.remove(username)
    return groups
项目:toil-vg    作者:vgteam    | 项目源码 | 文件源码
def get_vg_script(job, runner, script_name, work_dir):
    """
    getting the path to a script in vg/scripts is different depending on if we're
    in docker or not.  wrap logic up here, where we get the script from wherever it
    is then put it in the work_dir
    """
    vg_container_type = runner.container_for_tool('vg')

    if vg_container_type != 'None':
        # we copy the scripts out of the container, assuming vg is at /vg
        cmd = ['cp', os.path.join('/vg', 'scripts', script_name), '.']
        runner.call(job, cmd, work_dir = work_dir, tool_name='vg')
    else:
        # we copy the script from the vg directory in our PATH
        scripts_path = os.path.join(os.path.dirname(find_executable('vg')), '..', 'scripts')
        shutil.copy2(os.path.join(scripts_path, script_name), os.path.join(work_dir, script_name))
    return os.path.join(work_dir, script_name)
项目:nvim-cm-swift-completer    作者:dafufer    | 项目源码 | 文件源码
def __init__(self, nvim):
        super(Source, self).__init__(nvim)

        # dependency check
        try:
            from distutils.spawn import find_executable
            if not find_executable("sourcekitten"):
                self.message('error', 'Can not find sourcekitten for completion, you need to install https://github.com/jpsim/SourceKitten')

            if not find_executable("swift") and self._check_xcode_path():
                self.message('error', 'Can not find swift or XCode: https://swift.org')

        except Exception as ex:
            logger.exception(ex)

        self.__spm = self.nvim.eval('swift_completer#get_spm_module()')
        self.__target = self.nvim.eval('swift_completer#get_target()')
        self.__sdk = self.nvim.eval('swift_completer#get_sdk()')
项目:kapsel    作者:conda    | 项目源码 | 文件源码
def test_notebook_command():
    def check_notebook_command(dirname):
        project = project_no_dedicated_env(dirname)
        command = project.default_command
        assert command.notebook == 'test.ipynb'
        assert command.unix_shell_commandline is None
        assert command.windows_cmd_commandline is None
        assert command.conda_app_entry is None

        environ = minimal_environ(PROJECT_DIR=dirname)
        cmd_exec = command.exec_info_for_environment(environ)
        path = os.pathsep.join([environ['PROJECT_DIR'], environ['PATH']])
        jupyter_notebook = find_executable('jupyter-notebook', path)
        assert cmd_exec.args == [jupyter_notebook, os.path.join(dirname, 'test.ipynb'),
                                 '--NotebookApp.default_url=/notebooks/test.ipynb']
        assert cmd_exec.shell is False

    with_directory_contents_completing_project_file(
        {DEFAULT_PROJECT_FILENAME: "commands:\n default:\n    notebook: test.ipynb\n"}, check_notebook_command)
项目:kapsel    作者:conda    | 项目源码 | 文件源码
def test_notebook_command_extra_args():
    def check_notebook_command_extra_args(dirname):
        project = project_no_dedicated_env(dirname)
        command = project.default_command
        assert command.notebook == 'test.ipynb'
        assert command.unix_shell_commandline is None
        assert command.windows_cmd_commandline is None
        assert command.conda_app_entry is None

        environ = minimal_environ(PROJECT_DIR=dirname)
        cmd_exec = command.exec_info_for_environment(environ, extra_args=['foo', 'bar'])
        path = os.pathsep.join([environ['PROJECT_DIR'], environ['PATH']])
        jupyter_notebook = find_executable('jupyter-notebook', path)
        assert cmd_exec.args == [jupyter_notebook, os.path.join(dirname, 'test.ipynb'),
                                 '--NotebookApp.default_url=/notebooks/test.ipynb', 'foo', 'bar']
        assert cmd_exec.shell is False

    with_directory_contents_completing_project_file(
        {DEFAULT_PROJECT_FILENAME: "commands:\n default:\n    notebook: test.ipynb\n"},
        check_notebook_command_extra_args)
项目:kapsel    作者:conda    | 项目源码 | 文件源码
def test_bokeh_command():
    def check_bokeh_command(dirname):
        project = project_no_dedicated_env(dirname)
        command = project.default_command
        assert command.bokeh_app == 'test.py'
        assert command.notebook is None
        assert command.unix_shell_commandline is None
        assert command.windows_cmd_commandline is None
        assert command.conda_app_entry is None

        environ = minimal_environ(PROJECT_DIR=dirname)
        cmd_exec = command.exec_info_for_environment(environ)
        path = os.pathsep.join([environ['PROJECT_DIR'], environ['PATH']])
        bokeh = find_executable('bokeh', path)
        assert cmd_exec.args == [bokeh, 'serve', os.path.join(dirname, 'test.py'), '--show']
        assert cmd_exec.shell is False

    with_directory_contents_completing_project_file(
        {DEFAULT_PROJECT_FILENAME: "commands:\n default:\n    bokeh_app: test.py\n"}, check_bokeh_command)
项目:kapsel    作者:conda    | 项目源码 | 文件源码
def test_bokeh_command_with_extra_args():
    def check_bokeh_command_extra_args(dirname):
        project = project_no_dedicated_env(dirname)
        command = project.default_command
        assert command.bokeh_app == 'test.py'
        assert command.notebook is None
        assert command.unix_shell_commandline is None
        assert command.windows_cmd_commandline is None
        assert command.conda_app_entry is None

        environ = minimal_environ(PROJECT_DIR=dirname)
        cmd_exec = command.exec_info_for_environment(environ, extra_args=['--foo'])
        path = os.pathsep.join([environ['PROJECT_DIR'], environ['PATH']])
        bokeh = find_executable('bokeh', path)
        assert cmd_exec.args == [bokeh, 'serve', os.path.join(dirname, 'test.py'), '--show', '--foo']
        assert cmd_exec.shell is False

    with_directory_contents_completing_project_file(
        {DEFAULT_PROJECT_FILENAME: "commands:\n default:\n    bokeh_app: test.py\n"}, check_bokeh_command_extra_args)
项目:kapsel    作者:conda    | 项目源码 | 文件源码
def test_bokeh_command_with_kapsel_http_args():
    def check(dirname):
        project = project_no_dedicated_env(dirname)
        command = project.default_command
        assert command.bokeh_app == 'test.py'
        assert command.notebook is None
        assert command.unix_shell_commandline is None
        assert command.windows_cmd_commandline is None
        assert command.conda_app_entry is None
        assert command.supports_http_options

        environ = minimal_environ(PROJECT_DIR=dirname)
        cmd_exec = command.exec_info_for_environment(
            environ,
            extra_args=['--foo', '--kapsel-url-prefix', 'blah', '--kapsel-port', '1234', '--kapsel-host', 'example.com',
                        '--kapsel-no-browser', '--kapsel-iframe-hosts=foo1.com *.foo2.com', '--kapsel-use-xheaders'])
        path = os.pathsep.join([environ['PROJECT_DIR'], environ['PATH']])
        bokeh = find_executable('bokeh', path)
        assert cmd_exec.args == [bokeh, 'serve', os.path.join(dirname, 'test.py'), '--host', 'example.com', '--port',
                                 '1234', '--prefix', 'blah', '--use-xheaders', '--foo']
        assert cmd_exec.shell is False

    with_directory_contents_completing_project_file(
        {DEFAULT_PROJECT_FILENAME: "commands:\n default:\n    bokeh_app: test.py\n"}, check)
项目:kapsel    作者:conda    | 项目源码 | 文件源码
def test_bokeh_command_with_multiple_host_args():
    def check(dirname):
        project = project_no_dedicated_env(dirname)
        command = project.default_command
        assert command.bokeh_app == 'test.py'
        assert command.notebook is None
        assert command.unix_shell_commandline is None
        assert command.windows_cmd_commandline is None
        assert command.conda_app_entry is None
        assert command.supports_http_options

        environ = minimal_environ(PROJECT_DIR=dirname)
        cmd_exec = command.exec_info_for_environment(
            environ,
            extra_args=['--kapsel-host', 'example.com', '--kapsel-host', 'example2.com'])
        path = os.pathsep.join([environ['PROJECT_DIR'], environ['PATH']])
        bokeh = find_executable('bokeh', path)
        assert cmd_exec.args == [bokeh, 'serve', os.path.join(dirname, 'test.py'), '--host', 'example.com', '--host',
                                 'example2.com', '--show']
        assert cmd_exec.shell is False

    with_directory_contents_completing_project_file(
        {DEFAULT_PROJECT_FILENAME: "commands:\n default:\n    bokeh_app: test.py\n"}, check)
项目:kapsel    作者:conda    | 项目源码 | 文件源码
def test_bokeh_command_with_value_missing_for_kapsel_http_args():
    def check(dirname):
        project = project_no_dedicated_env(dirname)
        command = project.default_command
        assert command.bokeh_app == 'test.py'
        assert command.notebook is None
        assert command.unix_shell_commandline is None
        assert command.windows_cmd_commandline is None
        assert command.conda_app_entry is None
        assert command.supports_http_options

        environ = minimal_environ(PROJECT_DIR=dirname)
        cmd_exec = command.exec_info_for_environment(
            environ,
            extra_args=['--foo', '--kapsel-url-prefix', '--kapsel-port', '--kapsel-host'])
        path = os.pathsep.join([environ['PROJECT_DIR'], environ['PATH']])
        bokeh = find_executable('bokeh', path)
        assert cmd_exec.args == [bokeh, 'serve', os.path.join(dirname, 'test.py'), '--host', '', '--show', '--port', '',
                                 '--prefix', '', '--foo']
        assert cmd_exec.shell is False

    with_directory_contents_completing_project_file(
        {DEFAULT_PROJECT_FILENAME: "commands:\n default:\n    bokeh_app: test.py\n"}, check)
项目:jessy    作者:jessy-project    | 项目源码 | 文件源码
def check_executable(executable):
    """
    Checks if an executable exists in $PATH.

    Arguments:
        executable -- the name of the executable (e.g. "echo")

    Returns:
        True or False
    """
    logger = logging.getLogger(__name__)
    logger.debug("Checking executable '%s'...", executable)
    executable_path = find_executable(executable)
    found = executable_path is not None
    if found:
        logger.debug("Executable '%s' found: '%s'", executable,
                     executable_path)
    else:
        logger.debug("Executable '%s' not found", executable)
    return found
项目:pygdbmi    作者:cs01    | 项目源码 | 文件源码
def __init__(self,
                    gdb_path='gdb',
                    gdb_args=['--nx', '--quiet', '--interpreter=mi2'],
                    time_to_check_for_additional_output_sec=DEFAULT_TIME_TO_CHECK_FOR_ADDITIONAL_OUTPUT_SEC,
                    verbose=False):
        self.verbose = verbose
        self.abs_gdb_path = None  # abs path to gdb executable
        self.cmd = []  # the shell command to run gdb
        self.time_to_check_for_additional_output_sec = time_to_check_for_additional_output_sec
        self.gdb_process = None
        self._allow_overwrite_timeout_times = self.time_to_check_for_additional_output_sec > 0

        if not gdb_path:
            raise ValueError('a valid path to gdb must be specified')
        else:
            abs_gdb_path = find_executable(gdb_path)
            if abs_gdb_path is None:
                raise ValueError('gdb executable could not be resolved from "%s"' % gdb_path)
            else:
                self.abs_gdb_path = abs_gdb_path

        self.cmd = [self.abs_gdb_path] + gdb_args
        self.spawn_new_gdb_subprocess()
项目:PressSecBotPlus    作者:robmathers    | 项目源码 | 文件源码
def html_to_png(html):
    # Use a temp file in the current working directory so that wkhtmltoimage handles relative URLs properly
    temp_file = '.temp.html'
    with open(temp_file, 'w') as f:
        f.write(html.encode('utf-8'))

    command = ['wkhtmltoimage']
    if not find_executable(command[0]):
        raise ImportError('%s not found' % command[0])

    command += ['-f', 'png'] # format output as PNG
    command += ['--zoom', '2'] # retina image
    command += ['--width', '750'] # viewport 750px wide
    command += [temp_file] # read from stdin
    command += ['-'] # write to stdout

    wkhtml_process = Popen(command, stdout=PIPE, stderr=PIPE)
    (output, err) = wkhtml_process.communicate()

    os.remove(temp_file)

    image = Image.open(BytesIO(output))
    image = set_transparent_pixel(image)

    return image
项目:websauna    作者:websauna    | 项目源码 | 文件源码
def __init__(self, port:int, auth_token:str, subdomain:str):
        """Build ngrok HTTP tunnel

        Assume ngrok version 2.x. A temporary ngrok configuration file is created where the ngrok token is stored for running the command.

        :param port: localhost port forwarded through tunnel

        :param auth_token: Ngrok auth token to use

        :param subdomain: Use this subdomain for the tunnelling
        """
        assert find_executable("ngrok"), "ngrok command must be installed, see https://ngrok.com/"
        self.port = port
        self.auth_token = auth_token
        self.subdomain = subdomain
        self.ngrok = None
        self.config_file_handle, self.config_file = tempfile.mkstemp()
项目:zq    作者:vulogov    | 项目源码 | 文件源码
def run_cmake(arg=""):
    """
    Forcing to run cmake
    """
    if ds.find_executable('cmake') is None:
        print "CMake  is required to build zql"
        print "Please install cmake version >= 2.8 and re-run setup"
        sys.exit(-1)

    print "Configuring zql build with CMake.... "
    cmake_args = arg
    try:
        build_dir = op.join(op.split(__file__)[0], 'build')
        dd.mkpath(build_dir)
        os.chdir("build")
        ds.spawn(['cmake', '..'] + cmake_args.split())
        ds.spawn(['make', 'clean'])
        ds.spawn(['make'])
        os.chdir("..")
    except ds.DistutilsExecError:
        print "Error while running cmake"
        print "run 'setup.py build --help' for build options"
        print "You may also try editing the settings in CMakeLists.txt file and re-running setup"
        sys.exit(-1)
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def _use_header(new_header):
        """
        Should _adjust_header use the replaced header?

        On non-windows systems, always use. On
        Windows systems, only use the replaced header if it resolves
        to an executable on the system.
        """
        clean_header = new_header[2:-1].strip('"')
        return sys.platform != 'win32' or find_executable(clean_header)
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
def _use_header(new_header):
        """
        Should _adjust_header use the replaced header?

        On non-windows systems, always use. On
        Windows systems, only use the replaced header if it resolves
        to an executable on the system.
        """
        clean_header = new_header[2:-1].strip('"')
        return sys.platform != 'win32' or find_executable(clean_header)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def get_versions():
    """ Try to find out the versions of gcc and ld.
        If not possible it returns None for it.
    """
    from distutils.version import StrictVersion
    from distutils.spawn import find_executable
    import re

    gcc_exe = find_executable('gcc')
    if gcc_exe:
        out = os.popen(gcc_exe + ' -dumpversion','r')
        try:
            out_string = out.read()
        finally:
            out.close()
        result = re.search('(\d+\.\d+\.\d+)',out_string)
        if result:
            gcc_version = StrictVersion(result.group(1))
        else:
            gcc_version = None
    else:
        gcc_version = None
    # EMX ld has no way of reporting version number, and we use GCC
    # anyway - so we can link OMF DLLs
    ld_version = None
    return (gcc_version, ld_version)
项目:Flask_Blog    作者:sugarguo    | 项目源码 | 文件源码
def get_editor():
    # Get the editor from the environment.  Prefer VISUAL to EDITOR
    editor = os.environ.get('VISUAL') or os.environ.get('EDITOR')
    if editor:
        return editor

    # None found in the environment.  Fallback to platform-specific defaults.
    for ed in get_default_editors():
        path = find_executable(ed)
        if path is not None:
            return path

    raise EditorError("Unable to find a viable editor on this system."
        "Please consider setting your %s variable" % get_platform_editor_var())
项目:swjtu-pyscraper    作者:Desgard    | 项目源码 | 文件源码
def _use_header(new_header):
        """
        Should _adjust_header use the replaced header?

        On non-windows systems, always use. On
        Windows systems, only use the replaced header if it resolves
        to an executable on the system.
        """
        clean_header = new_header[2:-1].strip('"')
        return sys.platform != 'win32' or find_executable(clean_header)
项目:noc-orchestrator    作者:DirceuSilvaLabs    | 项目源码 | 文件源码
def _use_header(new_header):
        """
        Should _adjust_header use the replaced header?

        On non-windows systems, always use. On
        Windows systems, only use the replaced header if it resolves
        to an executable on the system.
        """
        clean_header = new_header[2:-1].strip('"')
        return sys.platform != 'win32' or find_executable(clean_header)
项目:jira_worklog_scanner    作者:pgarneau    | 项目源码 | 文件源码
def _use_header(new_header):
        """
        Should _adjust_header use the replaced header?

        On non-windows systems, always use. On
        Windows systems, only use the replaced header if it resolves
        to an executable on the system.
        """
        clean_header = new_header[2:-1].strip('"')
        return sys.platform != 'win32' or find_executable(clean_header)
项目:python-ceph-cfg    作者:oms4suse    | 项目源码 | 文件源码
def path():
        doc = "the path to the exeutable"

        def fget(self):
            if not self._path is None:
                return self._path
            self._path = find_executable(self.name)
            if self._path is None:
                msg = "Could not find executable:{executable}".format(executable=self.name)
                log.error(msg)
                raise ExecutableNotFound(msg)
            return self._path
        return locals()
项目:zanph    作者:zanph    | 项目源码 | 文件源码
def _use_header(new_header):
        """
        Should _adjust_header use the replaced header?

        On non-windows systems, always use. On
        Windows systems, only use the replaced header if it resolves
        to an executable on the system.
        """
        clean_header = new_header[2:-1].strip('"')
        return sys.platform != 'win32' or find_executable(clean_header)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def get_versions():
    """ Try to find out the versions of gcc and ld.
        If not possible it returns None for it.
    """
    from distutils.version import StrictVersion
    from distutils.spawn import find_executable
    import re

    gcc_exe = find_executable('gcc')
    if gcc_exe:
        out = os.popen(gcc_exe + ' -dumpversion','r')
        try:
            out_string = out.read()
        finally:
            out.close()
        result = re.search('(\d+\.\d+\.\d+)',out_string)
        if result:
            gcc_version = StrictVersion(result.group(1))
        else:
            gcc_version = None
    else:
        gcc_version = None
    # EMX ld has no way of reporting version number, and we use GCC
    # anyway - so we can link OMF DLLs
    ld_version = None
    return (gcc_version, ld_version)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def test_run(self):
        pkg_dir, dist = self.create_dist()
        cmd = build_clib(dist)

        foo_c = os.path.join(pkg_dir, 'foo.c')
        self.write_file(foo_c, 'int main(void) { return 1;}\n')
        cmd.libraries = [('foo', {'sources': [foo_c]})]

        build_temp = os.path.join(pkg_dir, 'build')
        os.mkdir(build_temp)
        cmd.build_temp = build_temp
        cmd.build_clib = build_temp

        # before we run the command, we want to make sure
        # all commands are present on the system
        # by creating a compiler and checking its executables
        from distutils.ccompiler import new_compiler
        from distutils.sysconfig import customize_compiler

        compiler = new_compiler()
        customize_compiler(compiler)
        for ccmd in compiler.executables.values():
            if ccmd is None:
                continue
            if find_executable(ccmd[0]) is None:
                self.skipTest('The %r command is not found' % ccmd[0])

        # this should work
        cmd.run()

        # let's check the result
        self.assertIn('libfoo.a', os.listdir(build_temp))
项目:dragonchain    作者:dragonchain    | 项目源码 | 文件源码
def finalize_options(self):
        self.root = os.path.abspath(os.path.dirname(__file__))
        self.thrift = find_executable('thrift1')
        if self.thrift is None:
            self.thrift = find_executable('thrift')
项目:Sci-Finder    作者:snverse    | 项目源码 | 文件源码
def _use_header(new_header):
        """
        Should _adjust_header use the replaced header?

        On non-windows systems, always use. On
        Windows systems, only use the replaced header if it resolves
        to an executable on the system.
        """
        clean_header = new_header[2:-1].strip('"')
        return sys.platform != 'win32' or find_executable(clean_header)
项目:Sci-Finder    作者:snverse    | 项目源码 | 文件源码
def _use_header(new_header):
        """
        Should _adjust_header use the replaced header?

        On non-windows systems, always use. On
        Windows systems, only use the replaced header if it resolves
        to an executable on the system.
        """
        clean_header = new_header[2:-1].strip('"')
        return sys.platform != 'win32' or find_executable(clean_header)
项目:django-devfixtures    作者:dolphinkiss    | 项目源码 | 文件源码
def _check_dependencies(self):
        not_found = []
        for executable in REQUIRED_EXEC:
            if not find_executable(executable):
                not_found.append(executable)
        if not_found:
            raise CommandError('The following executables are required: %s, missing: %s' % (REQUIRED_EXEC, not_found))
项目:kcli    作者:karmab    | 项目源码 | 文件源码
def add_image(self, image, pool, cmd=None):
        shortimage = os.path.basename(image).split('?')[0]
        if pool is not None:
            pool = [p['path'] for p in self._pool_info() if p['name'] == pool]
            if pool:
                poolpath = pool[0]
            else:
                print("Pool not found. Leaving....")
                return
        downloadcmd = 'curl -Lo %s -f %s/%s' % (shortimage, poolpath, image)
        os.system(downloadcmd)
        if cmd is not None and find_executable('virt-customize') is not None:
            cmd = "virt-customize -a %s/%s %s" % (poolpath, image, cmd)
        os.system(cmd)
        return {'result': 'success'}