当前位置: 首页>>代码示例>>Python>>正文


Python shutil.which函数代码示例

本文整理汇总了Python中shutil.which函数的典型用法代码示例。如果您正苦于以下问题:Python which函数的具体用法?Python which怎么用?Python which使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了which函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: start_daemon

def start_daemon():
    """ Starts the zerotier daemon if it is installed on your system

    Returns:
       str: output of the subprocess call to check_output

    Raises:
        EnvironmentError: if you your ststem is not yet supported.
        CalledProcessError: if the command to start the daemon failed.
    """
    if not is_installed():
        logger.info(uxstring.UxString.install_zerotier)
        sys.exit(1)

    if platform.system() in "Linux":
        if shutil.which("systemctl"):
            cmd = ('sudo', 'systemctl', 'start', 'zerotier-one.service')
        elif shutil.which("service"):
            cmd = ('sudo', 'service', 'zerotier-one', 'start')
        else:
            raise EnvironmentError("Do not know how to start zerotier deamon on your system")
    elif platform.system() in "Darwin":
        # ZT post install for Macs already load the daemon
        return ""
    else:
        raise EnvironmentError("Do not know how to start zerotier deamon on your system")

    return subprocess.check_output(cmd)
开发者ID:0xDeX,项目名称:two1-python,代码行数:28,代码来源:zerotier.py

示例2: detect_d_compiler

    def detect_d_compiler(self, want_cross):
        is_cross = False
        # Search for a D compiler.
        # We prefer LDC over GDC unless overridden with the DC
        # environment variable because LDC has a much more
        # up to date language version at time (2016).
        if 'DC' in os.environ:
            exelist = shlex.split(os.environ['DC'])
        elif self.is_cross_build() and want_cross:
            exelist = mesonlib.stringlistify(self.cross_info.config['binaries']['d'])
            is_cross = True
        elif shutil.which("ldc2"):
            exelist = ['ldc2']
        elif shutil.which("ldc"):
            exelist = ['ldc']
        elif shutil.which("gdc"):
            exelist = ['gdc']
        elif shutil.which("dmd"):
            exelist = ['dmd']
        else:
            raise EnvironmentException('Could not find any supported D compiler.')

        try:
            p, out = Popen_safe(exelist + ['--version'])[0:2]
        except OSError:
            raise EnvironmentException('Could not execute D compiler "%s"' % ' '.join(exelist))
        version = search_version(out)
        full_version = out.split('\n', 1)[0]
        if 'LLVM D compiler' in out:
            return compilers.LLVMDCompiler(exelist, version, is_cross, full_version=full_version)
        elif 'gdc' in out:
            return compilers.GnuDCompiler(exelist, version, is_cross, full_version=full_version)
        elif 'The D Language Foundation' in out or 'Digital Mars' in out:
            return compilers.DmdDCompiler(exelist, version, is_cross, full_version=full_version)
        raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
开发者ID:textshell,项目名称:meson,代码行数:35,代码来源:environment.py

示例3: build_dist

    def build_dist(self):
        for sdir in self.staging_dirs:
            if os.path.exists(sdir):
                shutil.rmtree(sdir)
        main_stage, ninja_stage = self.staging_dirs
        modules = [os.path.splitext(os.path.split(x)[1])[0] for x in glob(os.path.join('mesonbuild/modules/*'))]
        modules = ['mesonbuild.modules.' + x for x in modules if not x.startswith('_')]
        modules += ['distutils.version']
        modulestr = ','.join(modules)
        python = shutil.which('python')
        cxfreeze = os.path.join(os.path.dirname(python), "Scripts", "cxfreeze")
        if not os.path.isfile(cxfreeze):
            print("ERROR: This script requires cx_freeze module")
            sys.exit(1)

        subprocess.check_call([python,
                               cxfreeze,
                               '--target-dir',
                               main_stage,
                               '--include-modules',
                               modulestr,
                               'meson.py'])
        if not os.path.exists(os.path.join(main_stage, 'meson.exe')):
            sys.exit('Meson exe missing from staging dir.')
        os.mkdir(ninja_stage)
        shutil.copy(shutil.which('ninja'), ninja_stage)
        if not os.path.exists(os.path.join(ninja_stage, 'ninja.exe')):
            sys.exit('Ninja exe missing from staging dir.')
开发者ID:MathieuDuponchelle,项目名称:meson,代码行数:28,代码来源:createmsi.py

示例4: detect_tests_to_run

def detect_tests_to_run():
    # Name, subdirectory, skip condition.
    all_tests = [
        ('common', 'common', False),
        ('failing-meson', 'failing', False),
        ('failing-build', 'failing build', False),
        ('failing-tests', 'failing tests', False),

        ('platform-osx', 'osx', not mesonlib.is_osx()),
        ('platform-windows', 'windows', not mesonlib.is_windows() and not mesonlib.is_cygwin()),
        ('platform-linux', 'linuxlike', mesonlib.is_osx() or mesonlib.is_windows()),

        ('java', 'java', backend is not Backend.ninja or mesonlib.is_osx() or not have_java()),
        ('C#', 'csharp', backend is not Backend.ninja or not shutil.which('mcs')),
        ('vala', 'vala', backend is not Backend.ninja or not shutil.which('valac')),
        ('rust', 'rust', backend is not Backend.ninja or not shutil.which('rustc')),
        ('d', 'd', backend is not Backend.ninja or not have_d_compiler()),
        ('objective c', 'objc', backend not in (Backend.ninja, Backend.xcode) or mesonlib.is_windows() or not have_objc_compiler()),
        ('fortran', 'fortran', backend is not Backend.ninja or not shutil.which('gfortran')),
        ('swift', 'swift', backend not in (Backend.ninja, Backend.xcode) or not shutil.which('swiftc')),
        ('python3', 'python3', backend is not Backend.ninja),
    ]
    gathered_tests = [(name, gather_tests('test cases/' + subdir), skip) for name, subdir, skip in all_tests]
    if mesonlib.is_windows():
        # TODO: Set BOOST_ROOT in .appveyor.yml
        gathered_tests += [('framework', ['test cases/frameworks/1 boost'], 'BOOST_ROOT' not in os.environ)]
    elif mesonlib.is_osx() or mesonlib.is_cygwin():
        gathered_tests += [('framework', gather_tests('test cases/frameworks'), True)]
    else:
        gathered_tests += [('framework', gather_tests('test cases/frameworks'), False)]
    return gathered_tests
开发者ID:pombredanne,项目名称:meson,代码行数:31,代码来源:run_project_tests.py

示例5: __init__

 def __init__(self, environment, kwargs):
     Dependency.__init__(self)
     self.name = 'qt5'
     self.root = '/usr'
     mods = kwargs.get('modules', [])
     self.cargs = []
     self.largs = []
     self.is_found = False
     if isinstance(mods, str):
         mods = [mods]
     if len(mods) == 0:
         raise DependencyException('No Qt5 modules specified.')
     type_text = 'native'
     if environment.is_cross_build() and kwargs.get('native', False):
         type_text = 'cross'
         self.pkgconfig_detect(mods, environment, kwargs)
     elif not environment.is_cross_build() and shutil.which('pkg-config') is not None:
         self.pkgconfig_detect(mods, environment, kwargs)
     elif shutil.which('qmake') is not None:
         self.qmake_detect(mods, kwargs)
     else:
         self.version = 'none'
     if not self.is_found:
         mlog.log('Qt5 %s dependency found: ' % type_text, mlog.red('NO'))
     else:
         mlog.log('Qt5 %s dependency found: ' % type_text, mlog.green('YES'))
开发者ID:vinszent,项目名称:meson,代码行数:26,代码来源:dependencies.py

示例6: _determineHostType

    def _determineHostType():

        if sys.platform.startswith("win"):
            import winreg
            try:
                # the Core key indicates which VMware core product is installed (VMware Player vs VMware Workstation)
                hkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Wow6432Node\VMware, Inc.")
                output, _ = winreg.QueryValueEx(hkey, "Core")
                winreg.CloseKey(hkey)
            except OSError:
                return "ws"
        elif sys.platform.startswith("darwin"):
            return "fusion"
        else:
            vmware_path = shutil.which("vmware")
            if vmware_path is None:
                vmware_path = shutil.which("vmplayer")
                if vmware_path is not None:
                    return "player"
            if vmware_path:
                command = [vmware_path, "-v"]
                log.debug("Executing vmware with command: {}".format(command))
                try:
                    output = subprocess.check_output(command).decode("utf-8", errors="ignore").strip()
                except (OSError, subprocess.SubprocessError) as e:
                    log.error("Could not execute {}: {}".format("".join(command), e))
                    return "ws"
            else:
                log.error("vmware command not found")
                return "ws"
        if "VMware Player" in output:
            return "player"
        # Workstation is the default
        return "ws"
开发者ID:george7878099,项目名称:gns3-gui,代码行数:34,代码来源:__init__.py

示例7: diff_render

def diff_render(a, b):
    if use_git and which('git'):
        return diff_render_with_git(a, b)
    elif use_diff and which('diff'):
        return diff_render_with_diff(a, b)
    else:
        return diff_render_with_difflib(a, b)
开发者ID:minrk,项目名称:nbdime,代码行数:7,代码来源:prettyprint.py

示例8: findVmrun

    def findVmrun():
        """
        Finds the vmrun path.

        :return: path to vmrun
        """

        vmrun_path = None
        if sys.platform.startswith("win"):
            vmrun_path = shutil.which("vmrun")
            if vmrun_path is None:
                # look for vmrun.exe using the VMware Workstation directory listed in the registry
                vmrun_path = VMware._findVmrunRegistry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware Workstation")
                if vmrun_path is None:
                    # look for vmrun.exe using the VIX directory listed in the registry
                    vmrun_path = VMware._findVmrunRegistry(r"SOFTWARE\Wow6432Node\VMware, Inc.\VMware VIX")
        elif sys.platform.startswith("darwin"):
            vmware_fusion_vmrun_path = None
            try:
                output = subprocess.check_output(["mdfind", "kMDItemCFBundleIdentifier == 'com.vmware.fusion'"]).decode("utf-8", errors="ignore").strip()
                if len(output):
                    vmware_fusion_vmrun_path = os.path.join(output, "Contents/Library/vmrun")
            except (OSError, subprocess.SubprocessError) as e:
                pass
            if vmware_fusion_vmrun_path is None:
                vmware_fusion_vmrun_path = "/Applications/VMware Fusion.app/Contents/Library/vmrun"
            if os.path.exists(vmware_fusion_vmrun_path):
                vmrun_path = vmware_fusion_vmrun_path
        else:
            vmrun_path = shutil.which("vmrun")

        if vmrun_path is None:
            return ""
        return os.path.abspath(vmrun_path)
开发者ID:DINKIN,项目名称:gns3-gui,代码行数:34,代码来源:__init__.py

示例9: run

    def run(self):
        # 同步数据库
        if not os.path.exists("config.ini"):
            raise Exception("你必须先创建项目")

        pg_dump = shutil.which('pg_dump')
        if pg_dump is None:
            raise Exception("确保系统具备pg_dump命令")

        psql = shutil.which('psql')
        if pg_dump is None:
            raise Exception("确保系统具备psql命令")

        parser = ConfigParser()
        parser.read("config.ini")
        dumps = self.dump(parser)
        content = SQL_TPL.format(up=dumps)

        if not os.path.exists("migrations"):
            os.makedirs("migrations")

        with open("migrations/001_init.sql", "w") as handle:
            handle.write(content)

        self.create_migration_table(parser)
        self.insert_init_record(parser)
开发者ID:EnochZg,项目名称:chunyun,代码行数:26,代码来源:init_command.py

示例10: checkCopasiSE

	def checkCopasiSE(self, copasiPath):
		"""
		Checks whether a given CopasiSE program exists and if it is the right version. If a program defined by the user is not existing, the standard names in the $PATH are checked (i.e. copasise and CopasiSE).

		:param copasiPath: A user-given path to Copasi (may also contain just the name for calling, like "copasise", if the program is in the PATH)
		:returns: A valid Copasi path or name
		"""

		# Check for existance of a given CopasiSE path or the standard names.
		if which(copasiPath) is None:
			if which('CopasiSE') is None:
				if which('copasise') is None:
					self._errorReport('CopasiSE not found. Neither in the given path ({}), nor as "CopasiSE".'.format(copasiPath), fatal = True)
				else:
					self._errorReport('"{}" not found, switching to "copasise"'.format(copasiPath))
					copasiPath = 'copasise'
			else:
				self._errorReport('"{}" not found, switching to "CopasiSE"'.format(copasiPath))
				copasiPath = 'CopasiSE'

		# Check the program version of the given CopasiSE. Call e.g. copasise -h and only keep the stdout, not stderr
		output = subprocess.check_output([copasiPath, "-h"], universal_newlines = True, stderr=subprocess.DEVNULL)
		if self.version not in output:
			self._errorReport('The version of the given CopasiSE ({}) is not the same as for the given Copasi file ({}).'.format(output.split('\n')[0][7:], self.version))

		return copasiPath
开发者ID:MolecularBioinformatics,项目名称:PyCopasi,代码行数:26,代码来源:copasi.py

示例11: get_python_binary

    def get_python_binary(cls, minor_versions):
        python_path = bpy.app.binary_path_python

        # temporary OSX fix
        if sys.platform == "darwin" and python_path == "/usr/bin/python":

            # 1) try to find python in the distribution
            for mv in minor_versions:
                for suff in ["", "m"]:
                    path = normpath(os.path.join(
                        os.path.dirname(bpy.app.binary_path), "../Resources",
                        bpy.app.version_string[:4],"python", "bin", "python3.%s%s" % (mv, suff)))

                    if shutil.which(path):
                        return path

            # 2) try to find installed
            for mv in minor_versions:
                for suff in ["", "m"]:
                    path = "/Library/Frameworks/Python.framework/Versions/3.%s/bin/python3%s" % (minor_version, suff)
                    if shutil.which(path):
                        return path
        else:
            return python_path
        return None
开发者ID:JiangKevin,项目名称:Blend4Web,代码行数:25,代码来源:server.py

示例12: process_command_line

def process_command_line(argv):
    config = Config()

    import inspect
    import os.path

    i = 1

    ipython_exec_set = False
    maxima_jupyter_exec_set = False

    while i < len(argv):
        #print("cmd line option #{}: {}".format(i, argv[i]))

        if argv[i].startswith("--ipython-exec="):
            if ipython_exec_set:
                halt("Error: --ipython-exec option set twice")
            config.ipython_executable = shutil.which(argv[i][15:])
            ipython_exec_set = True
        elif argv[i].startswith("--maxima-jupyter-exec="):
            if maxima_jupyter_exec_set:
                halt("Error: --maxima-jupyter-exec option set twice")
            config.maxima_jupyter_executable = shutil.which(argv[i][len("--maxima-jupyter-exec="):])
            maxima_jupyter_exec_set = True
        else:
            halt("Error: unexpected option '{}'".format(argv[i]))

        i += 1

    return config
开发者ID:andrejv,项目名称:maxima-jupyter,代码行数:30,代码来源:install-maxima-jupyter.py

示例13: __init__

    def __init__(self, config, **kwargs):
        super(PanIndiDevice, self).__init__(config, **kwargs)

        self.logger = get_logger(self)
        name = getattr(self, 'name', 'INDI_DEVICE')
        driver = config.get('driver', 'indi_simulator_ccd')
        port = config.get('port')

        self.logger.info('Creating device {} ({})'.format(name, driver))

        self._getprop = shutil.which('indi_getprop')
        self._setprop = shutil.which('indi_setprop')

        assert self._getprop is not None, error.PanError("Can't find indi_getprop")
        assert self._setprop is not None, error.PanError("Can't find indi_setprop")

        self.name = name
        self.driver = driver
        self.port = port

        self.status_delay = kwargs.get('status_delay', 1.3)  # Why not
        self._status_thread = None

        self._driver_loaded = False
        self._properties = {}
        self._states = {}

        self.config = config
开发者ID:bsipocz,项目名称:POCS,代码行数:28,代码来源:device.py

示例14: which_exec

 def which_exec(self, cmd):
   path = ''
   if sublime.version() < '3000':
     path = os.popen('which ' + cmd).read().split('\n')[0]
   else:
     path = shutil.which(cmd) or shutil.which(cmd, path='/usr/local/bin')
   return path
开发者ID:amioka,项目名称:sublime-text-2-ruby-tests,代码行数:7,代码来源:run_ruby_test.py

示例15: isDockerInsalledOnOSX

def isDockerInsalledOnOSX():
    if shutil.which('docker') == None:
        return False
    if (shutil.which('boot2docker') == None
        and shutil.which('docker-machine') == None) :
        return False
    return True
开发者ID:gitmagic-bot,项目名称:sublime-docker,代码行数:7,代码来源:dockerutils.py


注:本文中的shutil.which函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。