python类execv()的实例源码

apk_operations.py 文件源码 项目:nojs 作者: chrisdickinson 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def _RunGdb(device, package_name, output_directory, target_cpu, extra_args,
            verbose):
  gdb_script_path = os.path.dirname(__file__) + '/adb_gdb'
  cmd = [
      gdb_script_path,
      '--package-name=%s' % package_name,
      '--output-directory=%s' % output_directory,
      '--adb=%s' % adb_wrapper.AdbWrapper.GetAdbPath(),
      '--device=%s' % device.serial,
      # Use one lib dir per device so that changing between devices does require
      # refetching the device libs.
      '--pull-libs-dir=/tmp/adb-gdb-libs-%s' % device.serial,
  ]
  # Enable verbose output of adb_gdb if it's set for this script.
  if verbose:
    cmd.append('--verbose')
  if target_cpu:
    cmd.append('--target-arch=%s' % _TargetCpuToTargetArch(target_cpu))
  cmd.extend(extra_args)
  logging.warning('Running: %s', ' '.join(pipes.quote(x) for x in cmd))
  print _Colorize('YELLOW', 'All subsequent output is from adb_gdb script.')
  os.execv(gdb_script_path, cmd)
apk_operations.py 文件源码 项目:nojs 作者: chrisdickinson 项目源码 文件源码 阅读 46 收藏 0 点赞 0 评论 0
def _RunShell(devices, package_name, cmd):
  if cmd:
    parallel_devices = device_utils.DeviceUtils.parallel(devices)
    outputs = parallel_devices.RunShellCommand(
        cmd, run_as=package_name).pGet(None)
    for output in _PrintPerDeviceOutput(devices, outputs):
      for line in output:
        print line
  else:
    adb_path = adb_wrapper.AdbWrapper.GetAdbPath()
    cmd = [adb_path, '-s', devices[0].serial, 'shell']
    # Pre-N devices do not support -t flag.
    if devices[0].build_version_sdk >= version_codes.NOUGAT:
      cmd += ['-t', 'run-as', package_name]
    else:
      print 'Upon entering the shell, run:'
      print 'run-as', package_name
      print
    os.execv(adb_path, cmd)
__main__.py 文件源码 项目:cheribuild 作者: CTSRD-CHERI 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def updateCheck():
    from pathlib import Path
    if not shutil.which("git"):
        return
    # check if new commits are available
    projectDir = str(Path(__file__).parent)
    subprocess.call(["git", "fetch"], cwd=projectDir)
    output = subprocess.check_output(["git", "status", "-uno"], cwd=projectDir)
    behindIndex = output.find(b"Your branch is behind ")
    if behindIndex > 0:
        msgEnd = output.find(b"\n  (use \"git pull\" to update your local branch)")
        if msgEnd > 0:
            output = output[behindIndex:msgEnd]
        statusUpdate("Current CheriBuild checkout can be updated: ", output.decode("utf-8"))
        if input("Would you like to update before continuing? y/[n] (Enter to skip) ").lower().startswith("y"):
            subprocess.check_call(["git", "pull", "--rebase"], cwd=projectDir)
            os.execv(sys.argv[0], sys.argv)
master.py 文件源码 项目:mitogen 作者: dw 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def _first_stage():
        import os,sys,zlib
        R,W=os.pipe()
        r,w=os.pipe()
        if os.fork():
            os.dup2(0,100)
            os.dup2(R,0)
            os.dup2(r,101)
            for f in R,r,W,w:os.close(f)
            os.environ['ARGV0']=e=sys.executable
            os.execv(e,['mitogen:CONTEXT_NAME'])
        os.write(1,'EC0\n')
        C=zlib.decompress(sys.stdin.read(input()))
        os.fdopen(W,'w',0).write(C)
        os.fdopen(w,'w',0).write('%s\n'%len(C)+C)
        os.write(1,'EC1\n')
        sys.exit(0)
seen.py 文件源码 项目:Taigabot 作者: FrozenPigs 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def seen_sieve(paraml, input=None, db=None, bot=None, notice=None, say=None):
    if not db_ready: db_init(db, bot)

    if re.match(r'^(s|S)/.*/.*\S*$', input.msg):
        correction(input,db,notice,say)
        return

    # keep private messages private
    if input.chan[:1] == "#":
        #try:
        db.execute("insert or replace into seen(name, time, quote, chan, host) values(?,?,?,?,?)", (input.nick.lower(), time.time(), input.msg.replace('\"', "").replace("'", ""), input.chan, input.mask))
        db.commit()
        #except:
        #    for botcon in bot.conns:
        #        if inp:
        #            bot.conns[botcon].cmd("QUIT", ["Restarted by {} ({})".format(nick, inp)])
        #        else:
        #            bot.conns[botcon].cmd("QUIT", ["Restarted by {}.".format(nick)])
        #    time.sleep(5)
        #    args = sys.argv[:]
        #    args.insert(0, sys.executable)
        #    os.execv(sys.executable, args)
SocketProcess.py 文件源码 项目:jumpscale_portal 作者: jumpscale7 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def restartInProcess(self, app):
        args = sys.argv[:]
        args.insert(0, sys.executable)
        apppath = j.system.fs.joinPaths(j.dirs.appDir, app)
        max_fd = 1024
        for fd in range(3, max_fd):
            try:
                flags = fcntl.fcntl(fd, fcntl.F_GETFD)
            except IOError:
                continue
            fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
        os.chdir(apppath)
        os.execv(sys.executable, args)

    # def getRedisClient(self,appname,actorname):

        # if ini.checkSection("redis"):
            # redisip=ini.getValue("redis","ipaddr")
            # redisport=ini.getValue("redis","port")
            #redisclient=redis.StrictRedis(host=redisip, port=int(redisport), db=0)
        # else:
            # redisclient=None
        # return redisclient
PortalServer.py 文件源码 项目:jumpscale_portal 作者: jumpscale7 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def restartInProcess(self, app):
        import fcntl
        args = sys.argv[:]
        args.insert(0, sys.executable)
        apppath = j.system.fs.joinPaths(j.dirs.appDir, app)
        max_fd = 1024
        for fd in range(3, max_fd):
            try:
                flags = fcntl.fcntl(fd, fcntl.F_GETFD)
            except IOError:
                continue
            fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
        os.chdir(apppath)
        os.execv(sys.executable, args)
venv.py 文件源码 项目:performance 作者: python 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def exec_in_virtualenv(options):
    venv = VirtualEnvironment(options)

    venv.create()
    venv_python = venv.get_python_program()

    args = [venv_python, "-m", "performance"] + \
        sys.argv[1:] + ["--inside-venv"]
    # os.execv() is buggy on windows, which is why we use run_cmd/subprocess
    # on windows.
    # * https://bugs.python.org/issue19124
    # * https://github.com/python/benchmarks/issues/5
    if os.name == "nt":
        venv.run_cmd(args, verbose=False)
        sys.exit(0)
    else:
        os.execv(args[0], args)
os.py 文件源码 项目:My-Web-Server-Framework-With-Python2.7 作者: syjsu 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def spawnd(path, args, pidfile=None):
    """
    Run a command as a daemon. This method is really just shorthand for the
    following code:

    .. python::

        daemonize(pidfile=pidfile)
        _os.execv(path, args)

    :Parameters:
        path : str
            Full path to program to run

        args : list
            List of command arguments. The first element in this list must
            be the command name (i.e., arg0).

        pidfile : str
            Path to file to which to write daemon's process ID. The string may
            contain a ``${pid}`` token, which is replaced with the process ID
            of the daemon. e.g.: ``/var/run/myserver-${pid}``
    """
    daemonize(no_close=True, pidfile=pidfile)
    _os.execv(path, args)
script_commands.py 文件源码 项目:taktyk 作者: kosior 项目源码 文件源码 阅读 49 收藏 0 点赞 0 评论 0
def process_unimported(self):
        msg = 'Brak modu?u pip!\nNie mo?na zainstalowa?:\n%s'
        msg_dec = 'Wymagane modu?y:\n{}\nChcesz zainstalowa? (T/n)? '
        self.to_import = list(self.unimported)
        modules_text = '\n'.join([' {} - {}'.format(ins, ver) for _, ins, ver in self.unimported])
        if self.try_import('pip', add=False):
            msg_dec = msg_dec.format(modules_text)
            decision = Decision(msg_dec, {'T': {self.install_unimported: (self.unimported,)},
                                          'n': sys.exit})
            decision.run()
            if all(self.import_all(reload=True)):
                logging.info('...ponowne uruchamianie')
                os.execv(sys.executable, ['python'] + sys.argv)
            else:
                logging.critical('Nie uda?o si? zainstalowa? modu?ów.')
                raise SystemExit
        else:
            logging.critical(msg, modules_text)
            raise SystemExit
wspbus.py 文件源码 项目:autosub-bootstrapbill 作者: BenjV 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _set_cloexec(self):
        """Set the CLOEXEC flag on all open files (except stdin/out/err).

        If self.max_cloexec_files is an integer (the default), then on
        platforms which support it, it represents the max open files setting
        for the operating system. This function will be called just before
        the process is restarted via os.execv() to prevent open files
        from persisting into the new process.

        Set self.max_cloexec_files to 0 to disable this behavior.
        """
        for fd in range(3, self.max_cloexec_files):  # skip stdin/out/err
            try:
                flags = fcntl.fcntl(fd, fcntl.F_GETFD)
            except IOError:
                continue
            fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
service.py 文件源码 项目:ccs-twistedextensions 作者: apple 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def reExec(self):
        """
        Removes pidfile, registers an exec to happen after shutdown, then
        stops the reactor.
        """
        self.log.warn("SIGHUP received - restarting")
        try:
            self.log.info("Removing pidfile: {log_source.pidfilePath}")
            os.remove(self.pidfilePath)
        except OSError:
            pass
        self.reactor.addSystemEventTrigger(
            "after", "shutdown", os.execv,
            sys.executable, [sys.executable] + sys.argv
        )
        self.reactor.stop()
cid_deploy_test.py 文件源码 项目:cid-tool 作者: futoin 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_05_multiapp(self):
        os.mkdir('webroot')

        self._writeFiles()

        self._call_cid(['prepare'])
        self._call_cid(['build'])

        pid = os.fork()

        if not pid:
            self._redirectAsyncStdIO()
            os.execv(self.CIDTEST_BIN, [self.CIDTEST_BIN, 'devserve'])

        try:
            self._testApps()

        finally:
            os.kill(pid, signal.SIGTERM)
            try: os.waitpid(pid, 0)
            except OSError: pass
cid_realapp_test.py 文件源码 项目:cid-tool 作者: futoin 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test02_execute(self):
        pid = os.fork()

        if not pid:
            self._redirectAsyncStdIO()
            os.execv(self.CIDTEST_BIN, [self.CIDTEST_BIN, 'service', 'master'])

        try:
            res = self._firstGet('http://127.0.0.1:1234/plugin_assets/file.txt')
            self.assertEqual('STATICFILE', res.text.strip())

            res = self._firstGet('http://127.0.0.1:1234/')

            if res.text.find('redmine') < 0:
                print(res)
                self.assertFalse(True)

        finally:
            os.kill(pid, signal.SIGTERM)
            try: os.waitpid(pid, 0)
            except OSError: pass
cid_realapp_test.py 文件源码 项目:cid-tool 作者: futoin 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test02_execute(self):
        return # TODO:
        pid = os.fork()

        if not pid:
            self._redirectAsyncStdIO()
            os.execv(self.CIDTEST_BIN, [self.CIDTEST_BIN, 'service', 'master'])

        try:
            res = self._firstGet('http://127.0.0.1:1234/plugin_assets/file.txt')
            self.assertEqual('STATICFILE', res.text.strip())

            res = self._firstGet('http://127.0.0.1:1234/')

            if res.text.find('redmine') < 0:
                print(res)
                self.assertFalse(True)

        finally:
            os.kill(pid, signal.SIGTERM)
            try: os.waitpid(pid, 0)
            except OSError: pass
wspbus.py 文件源码 项目:watcher 作者: nosmokingbandit 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _do_execv(self):
        """Re-execute the current process.

        This must be called from the main thread, because certain platforms
        (OS X) don't allow execv to be called in a child thread very well.
        """
        args = sys.argv[:]
        self.log('Re-spawning %s' % ' '.join(args))

        self._extend_pythonpath(os.environ)

        if sys.platform[:4] == 'java':
            from _systemrestart import SystemRestart
            raise SystemRestart
        else:
            args.insert(0, sys.executable)
            if sys.platform == 'win32':
                args = ['"%s"' % arg for arg in args]

            os.chdir(_startup_cwd)
            if self.max_cloexec_files:
                self._set_cloexec()
            os.execv(sys.executable, args)
wspbus.py 文件源码 项目:watcher 作者: nosmokingbandit 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _set_cloexec(self):
        """Set the CLOEXEC flag on all open files (except stdin/out/err).

        If self.max_cloexec_files is an integer (the default), then on
        platforms which support it, it represents the max open files setting
        for the operating system. This function will be called just before
        the process is restarted via os.execv() to prevent open files
        from persisting into the new process.

        Set self.max_cloexec_files to 0 to disable this behavior.
        """
        for fd in range(3, self.max_cloexec_files):  # skip stdin/out/err
            try:
                flags = fcntl.fcntl(fd, fcntl.F_GETFD)
            except IOError:
                continue
            fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
posix.py 文件源码 项目:ptterm 作者: jonathanslenders 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def from_command(cls, command, before_exec_func=None):
        """
        Create Process from command,
        e.g. command=['python', '-c', 'print("test")']

        :param before_exec_func: Function that is called before `exec` in the
            process fork.
        """
        assert isinstance(command, list)
        assert before_exec_func is None or callable(before_exec_func)

        def execv():
            if before_exec_func:
                before_exec_func()

            for p in os.environ['PATH'].split(':'):
                path = os.path.join(p, command[0])
                if os.path.exists(path) and os.access(path, os.X_OK):
                    os.execv(path, command)

        return cls(execv)
upgrade_requirements.py 文件源码 项目:requirements-tools 作者: Yelp 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def reexec(*cmd, **kwargs):
    reason = kwargs.pop('reason')
    assert not kwargs, kwargs
    print(color('*** exec-ing: {}'.format(reason), '\033[33m'))
    print(fmt_cmd(cmd))
    # Never returns
    os.execv(cmd[0], cmd)
reloader.py 文件源码 项目:uzdevsbot 作者: Uzbek-Developers 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def reload():
    """ Reload process """
    try:
        # Reload and replace current process
        os.execv(sys.executable, [sys.executable] + sys.argv)

    except OSError:
        # Ugh, that failed
        # Try spawning a new process and exitj
        os.spawnv(
            os.P_NOWAIT,
            sys.executable,
            [sys.executable] + sys.argv,
        )
        os._exit(os.EX_OK)
linux_pty.py 文件源码 项目:TerminalView 作者: Wramberg 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __init__(self, cmd, cwd):
        self._cmd_return_code = 0
        self._cmd_kill_signal = 0
        self._shell_pid, self._master_fd = pty.fork()
        if self._shell_pid == pty.CHILD:
            os.environ["TERM"] = "linux"
            os.chdir(cwd)
            os.execv(cmd[0], cmd)
main.py 文件源码 项目:ScraXBRL 作者: tooksoi 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def run(self):
        try:
            scrape_and_extract.scrape_list()
        except (requests.exceptions.ConnectionError, OSError, IOError):
            os.execv(sys.executable, [sys.executable] + [os.path.abspath(__file__)])
start_esp.py 文件源码 项目:endpoints-tools 作者: cloudendpoints 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def start_nginx(nginx, nginx_conf):
    try:
        # Control is relinquished to nginx process after this line
        os.execv(nginx, ['nginx', '-p', '/usr', '-c', nginx_conf])
    except OSError as err:
        logging.error("Failed to launch NGINX: " + nginx)
        logging.error(err.strerror)
        sys.exit(3)
server.py 文件源码 项目:health-mosconi 作者: GNUHealth-Mosconi 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def restart(self):
        self.stop(False)
        args = ([sys.executable] + ['-W%s' % o for o in sys.warnoptions]
            + sys.argv)
        if sys.platform == "win32":
            args = ['"%s"' % arg for arg in args]
        os.execv(sys.executable, args)
_twistd_unix.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def launchWithName(name):
    if name and name != sys.argv[0]:
        exe = os.path.realpath(sys.executable)
        log.msg('Changing process name to ' + name)
        os.execv(exe, [name, sys.argv[0], '--originalname']+sys.argv[1:])
core_admin_global.py 文件源码 项目:Taigabot 作者: FrozenPigs 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def restart(inp, nick=None, conn=None, bot=None):
    """restart [reason] -- Restarts the bot with [reason] as its quit message."""
    for botcon in bot.conns:
        if inp:
            bot.conns[botcon].cmd("QUIT", ["Restarted by {} ({})".format(nick, inp)])
        else:
            bot.conns[botcon].cmd("QUIT", ["Restarted by {}.".format(nick)])
    time.sleep(5)
    #os.execl("./bot", "bot", "restart")
    args = sys.argv[:]
    args.insert(0, sys.executable)
    os.execv(sys.executable, args)
seen.py 文件源码 项目:Taigabot 作者: FrozenPigs 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def db_init(db, bot):
    "check to see that our db has the the seen table and return a connection."
    try:
        db.execute("create table if not exists seen(name, time, quote, chan, host, primary key(name, chan))")
    except:
        for botcon in bot.conns:
            bot.conns[botcon].cmd("QUIT", ["Restarted"])
        time.sleep(5)
        #os.execl("./bot", "bot", "restart")
        args = sys.argv[:]
        args.insert(0, sys.executable)
        os.execv(sys.executable, args)
    db.commit()
    db_ready = True
tester.py 文件源码 项目:runtests 作者: bccp 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _do_shell(self, args, config):
        capman = config.pluginmanager.getplugin('capturemanager')
        if capman:
            if hasattr(capman, 'suspend_global_capture'):
                capman.suspend_global_capture(in_=True)
            else:
                capman.suspendcapture(in_=True)

        shell = os.environ.get('SHELL', 'sh')
        print("Spawning a Unix shell...")
        with self._run_from_testdir(args):
            os.execv(shell, [shell] + config.args[1:])
            sys.exit(1)
__main__.py 文件源码 项目:Pext 作者: Pext 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _menu_restart_pext(self) -> None:
        # Call _shut_down manually because it isn't called when using os.execv
        _shut_down(self,
                   self.config_retriever)

        args = sys.argv[:]

        args.insert(0, sys.executable)
        if sys.platform == 'win32':
            args = ['"%s"' % arg for arg in args]

        os.chdir(os.getcwd())
        os.execv(sys.executable, args)
maintenance.py 文件源码 项目:Excalibot 作者: endreman0 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _restart(self):
        await self.bot.shutdown()
        script = sys.argv[0]
        if script.startswith(os.getcwd()):
            script = script[len(os.getcwd()):].lstrip(os.sep)

        if script.endswith('__main__.py'):
            args = [sys.executable, '-m', script[:-len('__main__.py')].rstrip(os.sep).replace(os.sep, '.')]
        else:
            args = [sys.executable, script]
        os.execv(sys.executable, args + sys.argv[1:])


问题


面经


文章

微信
公众号

扫码关注公众号