• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sh.which函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: make_bootable

    def make_bootable(self):
        """ Tworzenie dysku bootowalnego
        """
        # self.uuid = re.search("UUID=\"(\w*)\"", str(sh.blkid(self.device + "1"))).group(1)
        # print("Device UUID:", self.uuid)

        # W niektórych wersjach windows katalog ten jest z drukowanej
        def try_move(old_file, new_file):
            try: sh.mv(old_file, new_file)
            except:
                print("File {} already exists, nothing to move".format(new_file))

        self.boot_folder = self.destination_mount + "/boot"
        try_move(self.destination_mount + "/BOOT", self.boot_folder)
        try_move(self.destination_mount + "/BOOTMGR", self.destination_mount + "/bootmgr")

        # Instalownie bootloadera
        # grub-install --target=i386-pc --boot-directory="/<USB_mount_folder>/boot" /dev/sdX
        installer = sh.Command(sh.which("grub-install")
                               or sh.which("grub2-install"))
        installer(self.device, target="i386-pc", skip_fs_probe=True, force=True, boot_directory=self.destination_mount + "/boot")

        # Tworzenie konfiguracji GRUBa
        with open( "{}/{}/grub.cfg".format( self.boot_folder, "grub2" if str(installer).find("grub2") != -1 else "grub")
                 , "wt"
                 ) as config:
            config.write("""
                set menu_color_normal=white/black
                set menu_color_highlight=black/light-gray
                menuentry 'Install Windows' {
                    ntldr /bootmgr
                }
            """)
开发者ID:codeneomatrix,项目名称:pyWinUSB,代码行数:33,代码来源:creator.py


示例2: check_required_programs

def check_required_programs():
    # Check that mediainfo is installed
    if sh.which("mediainfo") is None:
        print("%s: Cannot find mediainfo, please install before continuing.") % (PROG_NAME)
        exit(1)

    # Check that ffmpeg is installed
    if sh.which("ffmpeg") is None:
        print("%s: Cannot find ffmpeg. " "Please install ffmpeg version 1.0 or later.") % (PROG_NAME)

    out = StringIO()
    try:
        sh.ffmpeg("-encoders", _out=out)
    except sh.ErrorReturnCode:
        print("%s: unsupported version of ffmpeg installed. " "Install ffmpeg version 1.0 or higher") % PROG_NAME

    if "libx264" not in out.getvalue():
        print(
            "%s: Installed version of ffmeg doesn't include libx264 support. "
            "Install version of ffmpeg that supports libx264."
        ) % PROG_NAME
        exit(1)

    config.extra_opts = ["-strict", "experimental"]
    config.audio_encoder = "libfaac"
    if "libfaac" not in out.getvalue():
        config.audio_encoder = "aac"
开发者ID:skonakov,项目名称:2mp4,代码行数:27,代码来源:__init__.py


示例3: get_virtualenv_executable

def get_virtualenv_executable():
    virtualenv = None
    if virtualenv is None:
        virtualenv = sh.which('virtualenv2')
    if virtualenv is None:
        virtualenv = sh.which('virtualenv-2.7')
    if virtualenv is None:
        virtualenv = sh.which('virtualenv')
    return virtualenv
开发者ID:PKRoma,项目名称:python-for-android,代码行数:9,代码来源:util.py


示例4: test_command_wrapper

    def test_command_wrapper(self):
        from sh import Command, which
        
        ls = Command(which("ls"))
        wc = Command(which("wc"))

        c1 = int(wc(ls("-A1"), l=True))
        c2 = len(os.listdir("."))

        self.assertEqual(c1, c2)
开发者ID:ahhentz,项目名称:sh,代码行数:10,代码来源:test.py


示例5: new

    def new(cls, filename):
        if hasattr(settings, "LEDGER_BIN"):
            ledger_bin = settings.LEDGER_BIN
        else:
            ledger_bin = sh.which("ledger")

        return Ledger(sh.Command(ledger_bin).bake(_tty_out=False, no_color=True, file=filename), filename=filename)
开发者ID:Ikke,项目名称:ledger-dashboard,代码行数:7,代码来源:ledger.py


示例6: exists

def exists():
    """
    Determines whether or not ser2sock exists in our path.

    :returns: Whether or not ser2sock exists in the path.
    """
    return sh.which('ser2sock') is not None
开发者ID:Gerguis,项目名称:alarmdecoder-webapp,代码行数:7,代码来源:ser2sock.py


示例7: new_ws

def new_ws(cmd, args):
    """Create a new workspace by using the first free number > 0."""
    nums = (w["num"] for w in i3.get_workspaces())
    nums = filter(lambda n: n is not None and n >= 0, nums)

    try:
        exe = args[args.index("--exec")+1]
    except (IndexError, ValueError):
        exe = None

    i = -1 # fallback if `nums` happens to be empty
    for i,n in enumerate(sorted(nums)):
        if i != n:
            cmd(str(i))
            break
    else:
        cmd(str(i+1))

    if exe:
        # We use i3.exec_ here instead of sh.Command, as we do not want the
        # exe to be a child of this script's process
        # Also we get startup notification support for free :-)
        if sh.which(exe): # i3 exec always yields 'success'
            i3.exec_(exe)
        else:
            nag("Command '%s' not found!" % exe)
开发者ID:tonk,项目名称:dotfiles,代码行数:26,代码来源:workspaces.py


示例8: pip

        def pip(self):
            ctx = Context()
            for recipe in Recipe.list_recipes():
                key = "{}.build_all".format(recipe)
                if key not in ctx.state:
                    continue
                recipe = Recipe.get_recipe(recipe, ctx)
                recipe.init_with_ctx(ctx)
            print(ctx.site_packages_dir)
            if not hasattr(ctx, "site_packages_dir"):
                print("ERROR: python must be compiled before using pip")
                sys.exit(1)

            pip_env = {
                "CC": "/bin/false",
                "CXX": "/bin/false",
                "PYTHONPATH": ctx.site_packages_dir,
                "PYTHONOPTIMIZE": "2",
                "PIP_INSTALL_TARGET": ctx.site_packages_dir
            }
            print(pip_env)
            pip_path = sh.which("pip")
            args = [pip_path] + sys.argv[2:]
            if not pip_path:
                print("ERROR: pip not found")
                sys.exit(1)
            import os
            print("-- execute pip with: {}".format(args)) 
            os.execve(pip_path, args, pip_env)
开发者ID:cbenhagen,项目名称:kivy-ios,代码行数:29,代码来源:toolchain.py


示例9: parallel_blast

def parallel_blast(inputfile, outfile, ninst, db, blasttype, task, blastoptions):
    '''
    Runs blast commands in parallel on a given fasta file

    :param str inputfile: Input fasta path
    :param str outfile: Output file path
    :param int ninst: number of cpus to use if not in PBS or SGE job
    :param str db: Database path to blast against
    :param str blasttype: Blast exe to use(blastn, blastx, blastp)
    :param str task: Blast task to run with -task option for blasttype or 
        None if blastx/blastp
    :param str blastoptions: other options to pass to blast
    '''
    if set(STATIC_BLAST_ARGS).intersection(shlex.split(blastoptions)):
        raise ValueError("You cannot supply any of the arguments inside of {0} as" \
            " optional arguments to blast".format(STATIC_BLAST_ARGS))
    args = list(PARALLEL_ARGS)
    args += generate_sshlogins(ninst)
    blast_path = sh.which(blasttype)
    blast_cmd = [blast_path]
    if blast_path is None:
        raise ValueError("{0} is not in your path(Maybe not installed?)".format(
            blasttype
        ))
    if task is not None:
        blast_cmd += ['-task', task]
    blast_cmd += ['-db', db,]
    blast_cmd += [blastoptions]
    blast_cmd += ['-query', '{}']
    args += [' '.join(blast_cmd)]
    cmd = sh.Command('parallel')
    run(cmd, *args, _in=open(inputfile), _out=open(outfile,'w'))
开发者ID:nyoung85,项目名称:bio_bits,代码行数:32,代码来源:parallel_blast.py


示例10: parallel_diamond

def parallel_diamond(inputfile, outfile, ninst, db, task, diamondoptions):
    '''
    Runs diamond commands in parallel on a given fasta file

    Will not run more than 1 diamond process per host as diamond utilizes
    threads better than blast

    Since diamond v0.7.9 produces a daa file, diamond view is required to output
    the tsv format that is similar to blast's output format. diamond view is
    automatically called on the produced .daa file so that GNU Parallel can combine
    all output into a single stream.

    :param str inputfile: Input fasta path
    :param str outfile: Output file path
    :param int ninst: number of threads to use if not in PBS or SGE job
    :param str db: Database path to blast against
    :param str task: blastx or blastp
    :param str diamondoptions: other options to pass to blast
    '''
    if set(STATIC_DIAMOND_ARGS).intersection(shlex.split(diamondoptions)):
        raise ValueError("You cannot supply any of the arguments inside of {0} as" \
            " optional arguments to diamond".format(STATIC_DIAMOND_ARGS))
    # This seems kinda stupid that we are just replacing cpu count for each
    # node with 1, but it is easier than refactoring other code to be better
    sshlogins = generate_sshlogins(ninst)
    for i in range(0,len(sshlogins),2):
        cpu,host = sshlogins[i+1].split('/')
        sshlogins[i+1] = '1/{0}'.format(host)
    dmnd_path = sh.which('diamond')
    if dmnd_path is None:
        raise ValueError("diamond is not in your path(Maybe not installed?)")
    # Diamond base command arguments
    # parallel replaces {} with the temporary file it is using
    #  and replaces {#} with the current file segment it is using
    # After diamond is finished, diamond view will be used to output the tsv
    # format of the file
    diamond_cmd = [
        dmnd_path, task, '--threads', str(ninst), '--db', db, '--query', '{}',
        '--daa', '{}.{#}', ';', dmnd_path, 'view', '--daa', '{}.{#}.daa'
    ]
    if len(sshlogins) > 2:
        args = list(PARALLEL_ARGS)
        args += sshlogins
        diamond_cmd_str = ' '.join(diamond_cmd) + diamondoptions
        args += [diamond_cmd_str]
        cmd = sh.Command('parallel')
        run(cmd, *args, _in=open(inputfile), _out=open(outfile,'w'))
    else:
        dcmd = sh.Command('diamond')
        args = [task]
        if diamondoptions:
            args += shlex.split(diamondoptions)
        p = run(
            dcmd, *args, threads=ninst, db=db, query=inputfile, daa=outfile
        )
        p = run(
            dcmd, 'view', daa=outfile+'.daa', _out=open(outfile,'w')
        )
开发者ID:nyoung85,项目名称:bio_bits,代码行数:58,代码来源:parallel_blast.py


示例11: get_env

    def get_env(self):
        include_dirs = [
            "-I{}/{}".format(
                self.ctx.include_dir,
                d.format(arch=self))
            for d in self.ctx.include_dirs]

        env = {}
        ccache = sh.which('ccache')
        cc = sh.xcrun("-find", "-sdk", self.sdk, "clang").strip()
        if ccache:
            ccache = ccache.strip()
            use_ccache = environ.get("USE_CCACHE", "1")
            if use_ccache != '1':
                env["CC"] = cc
            else:
                if not self._ccsh:
                    self._ccsh = ccsh = sh.mktemp().strip()
                    with open(ccsh, 'w') as f:
                        f.write('#!/bin/sh\n')
                        f.write(ccache + ' ' + cc + ' "[email protected]"\n')
                    sh.chmod('+x', ccsh)
                else:
                    ccsh = self._ccsh
                env["USE_CCACHE"] = '1'
                env["CCACHE"] = ccache
                env["CC"] = ccsh

                env.update({k: v for k, v in environ.items() if k.startswith('CCACHE_')})
                env.setdefault('CCACHE_MAXSIZE', '10G')
                env.setdefault('CCACHE_HARDLINK', 'true')
                env.setdefault('CCACHE_SLOPPINESS', ('file_macro,time_macros,'
                    'include_file_mtime,include_file_ctime,file_stat_matches'))
        else:
            env["CC"] = cc
        env["AR"] = sh.xcrun("-find", "-sdk", self.sdk, "ar").strip()
        env["LD"] = sh.xcrun("-find", "-sdk", self.sdk, "ld").strip()
        env["OTHER_CFLAGS"] = " ".join(include_dirs)
        env["OTHER_LDFLAGS"] = " ".join([
            "-L{}/{}".format(self.ctx.dist_dir, "lib"),
        ])
        env["CFLAGS"] = " ".join([
            "-arch", self.arch,
            "-pipe", "-no-cpp-precomp",
            "--sysroot", self.sysroot,
            #"-I{}/common".format(self.ctx.include_dir),
            #"-I{}/{}".format(self.ctx.include_dir, self.arch),
            "-O3",
            self.version_min
        ] + include_dirs)
        env["LDFLAGS"] = " ".join([
            "-arch", self.arch,
            "--sysroot", self.sysroot,
            "-L{}/{}".format(self.ctx.dist_dir, "lib"),
            "-lsqlite3",
            self.version_min
        ])
        return env
开发者ID:cbenhagen,项目名称:kivy-ios,代码行数:58,代码来源:toolchain.py


示例12: stop_wireless

def stop_wireless():
    ''' Try official ways to stop wireless such as nmcli and rfkill.

        These often leave the service enabled, or the service is re-enabled
        on boot.

        To do: check rmcomm piconets
    '''

    if not sh.which('nm'):
        sh.aptitude('install', 'nmcli')
    assert sh.which('nm')

    if not sh.which('service'):
        service_path = '/usr/local/sbin/service'
        with open(service_path, 'w') as service_file:
            service_file.write(service_script_text)
        os.chmod(service_path, 0o755)
    assert sh.which('service')

    try:
        sh.nmcli('nm', 'wifi', 'off')
        sh.nmcli('nm', 'wwan', 'off')
    except:
        pass

    # rfkill block all
    try:
        #if not sh.which ('rfkill'):
        #    sh.aptitude('install', 'rfkill')
        #assert sh.which ('rfkill')
        sh.rfkill('block', 'all')
    except:
        # some variants of linux don't have /dev/rfkill,
        # so there's no program rfkill
        pass

    # /etc/init.d/bluetooth stop
    try:
        sh.service(Bluetooth, 'stop')
    except:
        try:
            sh.service(Bluetooth+'-unused', 'stop')
        except:
            pass
开发者ID:goodcrypto,项目名称:goodcrypto-libs,代码行数:45,代码来源:harden.py


示例13: sh_command

    def sh_command(self, program):
        ''' return sh.Command(program), or None if program not found. '''

        # sh.Command requires an absolute path
        program = sh.which(program)
        if not program:
            raise CliException('program not found: {}'.format(program))

        return sh.Command(program)
开发者ID:goodcrypto,项目名称:goodcrypto-libs,代码行数:9,代码来源:cli.py


示例14: test_run_command_with_debug

def test_run_command_with_debug(mocker, patched_print_debug):
    cmd = sh.ls.bake(_env={'ANSIBLE_FOO': 'foo', 'MOLECULE_BAR': 'bar'})
    util.run_command(cmd, debug=True)
    x = [
        mocker.call('ANSIBLE ENVIRONMENT', '---\nANSIBLE_FOO: foo\n'),
        mocker.call('MOLECULE ENVIRONMENT', '---\nMOLECULE_BAR: bar\n'),
        mocker.call('COMMAND', sh.which('ls'))
    ]

    assert x == patched_print_debug.mock_calls
开发者ID:kireledan,项目名称:molecule,代码行数:10,代码来源:test_util.py


示例15: IsInstalled

 def IsInstalled(self):
     logging.debug("def IsInstalled(self):")
     out = sh.which(self.digitemp_cmd_str)
     if out is None:
         logging.error('digitemp_DS2490 not found on the system, use sudo apt-get install digitemp')
         self._installed = False             
     else:
         logging.info("Found digitemp_DS2490 in : %s" % out)
         self._installed = True
     return self._installed
开发者ID:borand,项目名称:ablib,代码行数:10,代码来源:digitemp.py


示例16: test_run_command_with_debug_handles_no_env

def test_run_command_with_debug_handles_no_env(mocker, patched_print_debug):
    cmd = sh.ls.bake()
    util.run_command(cmd, debug=True)
    x = [
        mocker.call('ANSIBLE ENVIRONMENT', '--- {}\n'),
        mocker.call('MOLECULE ENVIRONMENT', '--- {}\n'),
        mocker.call('COMMAND', sh.which('ls'))
    ]

    assert x == patched_print_debug.mock_calls
开发者ID:kireledan,项目名称:molecule,代码行数:10,代码来源:test_util.py


示例17: test_execute_raises

def test_execute_raises(patched_print_error, shell_instance):
    shell_instance._command = sh.false.bake()
    with pytest.raises(SystemExit) as e:
        shell_instance.execute()

    assert 1 == e.value.code

    false_path = sh.which('false')
    msg = "\n\n  RAN: '{}'\n\n  STDOUT:\n\n\n  STDERR:\n".format(false_path)
    patched_print_error.assert_called_once_with(msg)
开发者ID:davidfischer-ch,项目名称:molecule,代码行数:10,代码来源:test_shell.py


示例18: run_test

 def run_test(version):
     py_version = "python%s" % version
     py_bin = sh.which(py_version)
     
     if py_bin:
         print("Testing %s" % py_version.capitalize())
         
         p = subprocess.Popen([py_bin, "test.py"] + sys.argv[2:])
         p.wait()
     else:
         print("Couldn't find %s, skipping" % py_version.capitalize())
开发者ID:dschexna,项目名称:fedemo,代码行数:11,代码来源:setup.py


示例19: exec_expander

def exec_expander(exefile):
    """
    determine full path executable
    """
    if os.path.exists(exefile):
        return exefile
    fp = sh.which(exefile).strip().split("\n")
    if len(fp) > 0:
        return fp[0]
    else:
        return exefile
开发者ID:mfiers,项目名称:mad2,代码行数:11,代码来源:transact.py


示例20: main

def main():
    if not sh.which('pip3'):
        print('installing pip3')
        sh.apt_get("install", "python3-pip", "-y")
        if not sh.which('pip3'):
            print('pip3 install failed.')
            return
        print('pip3 installed')

    print('installing python package')
    print('flask.')
    sh.pip3("install", "flask")
    print('rsa.')
    sh.pip3("install", "rsa")

    if not sh.which('supervisorctl'):
        print('installing supervisor')
        sh.apt_get("install", "supervisor", "-y")
        if not sh.which('supervisorctl'):
            print('supervisor install failed')
            return
        print('supervisor installed')

    ans = input('Do you want to copy files to /root? [y/N]')
    if ans == 'Y' or ans == 'y':
        print('copying files to /root/Adence')
        sh.cp('../Adence', '-R', '/root')
        print('config supervisor')
        cmd = r'''[program:Adence]
command=python3 /root/Adence/main.py
autostart=true
autorestart=true
stderr_logfile=/var/log/Adence.err.log
stdout_logfile=/var/log/Adence.out.log
'''
        with open('/etc/supervisor/conf.d/Adence.conf', 'w') as fp:
            fp.write(cmd)
        sh.service('supervisor', 'restart')
        print('done. you can visit http://localhost:9000 now.')
    else:
        print('environment settled.you need to run the main.py manually')
开发者ID:youzhonghui,项目名称:Adence,代码行数:41,代码来源:setup.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python git.add函数代码示例发布时间:2022-05-27
下一篇:
Python sh.wget函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap