Python os.execv() Examples

The following are 30 code examples of os.execv(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: wspbus.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
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) 
Example #2
Source File: b2bua_radius.py    From b2bua with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def GClector(self):
        print('GC is invoked, %d calls in map' % len(self.ccmap))
        if self.debug_mode:
            print(self.global_config['_sip_tm'].tclient, self.global_config['_sip_tm'].tserver)
            for cc in tuple(self.ccmap):
                try:
                    print(cc.uaA.state, cc.uaO.state)
                except AttributeError:
                    print(None)
        else:
            print('[%d]: %d client, %d server transactions in memory' % \
              (os.getpid(), len(self.global_config['_sip_tm'].tclient), len(self.global_config['_sip_tm'].tserver)))
        if self.safe_restart:
            if len(self.ccmap) == 0:
                self.global_config['_sip_tm'].userv.close()
                os.chdir(self.global_config['_orig_cwd'])
                argv = [sys.executable,]
                argv.extend(self.global_config['_orig_argv'])
                os.execv(sys.executable, argv)
                # Should not reach this point!
            self.el.ival = 1
        #print gc.collect()
        if len(gc.garbage) > 0:
            print(gc.garbage) 
Example #3
Source File: entrypoint.py    From iris-relay with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def main():
    config_path = os.environ.get('iris-relay_CFG_PATH', '/home/iris-relay/config/config.yaml')
    with open(config_path, 'r') as config_file:
        iris_relay_config = yaml.safe_load(config_file)
    mysql_config = iris_relay_config['db']['conn']['kwargs']

    # It often takes several seconds for MySQL to start up. iris-relay dies upon start
    # if it can't immediately connect to MySQL, so we have to wait for it.
    wait_for_mysql(mysql_config)

    if 'DOCKER_DB_BOOTSTRAP' in os.environ:
        if not os.path.exists(initializedfile):
            initialize_mysql_schema(mysql_config)

    os.execv('/usr/bin/uwsgi',
             ['', '--yaml', '/home/iris-relay/daemons/uwsgi.yaml:prod']) 
Example #4
Source File: modelaccessor.py    From xos with Apache License 2.0 6 votes vote down vote up
def keep_trying(client, reactor):
    # Keep checking the connection to wait for it to become unavailable.
    # Then reconnect. The strategy is to send NoOp operations, one per second, until eventually a NoOp throws an
    # exception. This will indicate the server has reset. When that happens, we force the client to reconnect, and
    # it will download a new API from the server.

    from xosapi.xos_grpc_client import Empty

    try:
        client.utility.NoOp(Empty())
    except Exception as e:
        # If we caught an exception, then the API has become unavailable.
        # So reconnect.

        log.exception("exception in NoOp", e=e)
        log.info("restarting synchronizer")

        os.execv(sys.executable, ["python"] + sys.argv)
        return

    reactor.callLater(1, functools.partial(keep_trying, client, reactor)) 
Example #5
Source File: spawn.py    From Computable with MIT License 6 votes vote down vote up
def _spawn_posix(cmd, search_path=1, verbose=0, dry_run=0):
    log.info(' '.join(cmd))
    if dry_run:
        return
    exec_fn = search_path and os.execvp or os.execv
    pid = os.fork()

    if pid == 0:  # in the child
        try:
            exec_fn(cmd[0], cmd)
        except OSError, e:
            sys.stderr.write("unable to execute %s: %s\n" %
                             (cmd[0], e.strerror))
            os._exit(1)

        sys.stderr.write("unable to execute %s for unknown reasons" % cmd[0])
        os._exit(1) 
Example #6
Source File: service.py    From ccs-twistedextensions with Apache License 2.0 6 votes vote down vote up
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() 
Example #7
Source File: xos_grpc_client.py    From xos with Apache License 2.0 6 votes vote down vote up
def hash_check(self, pb2_file_name, pb2_grpc_file_name):
        # If the protobufs have changed, then it's likely that new models
        # have been downloaded. One way we have dealt with this in the past
        # is to force a reload() of the affected modules. However, it seems
        # safer to force a full synchronizer restart as this will allow
        # the synchronizer to perform a version check against the core, and
        # it will refresh any data structures that might be affected by the
        # new models.

        pb2_hash = hashlib.sha256(open(pb2_file_name).read())
        pb2_grpc_hash = hashlib.sha256(open(pb2_grpc_file_name).read())

        if (pb2_file_name in self.hashes) or (pb2_grpc_file_name in self.hashes):
            if (pb2_hash != self.hashes[pb2_file_name]) or (pb2_grpc_hash != self.hashes[pb2_grpc_file_name]):
                log.warning(
                    "Protobuf change detected, restarting the synchronzier"
                )
                os.execv(sys.executable, ["python"] + sys.argv)

        self.hashes[pb2_file_name] = pb2_hash
        self.hashes[pb2_grpc_file_name] = pb2_grpc_hash 
Example #8
Source File: dispatch.py    From accelerator with Apache License 2.0 6 votes vote down vote up
def run(cmd, close_in_child, keep_in_child, with_pgrp=True):
	child = os.fork()
	if child:
		return child
	if with_pgrp:
		os.setpgrp() # this pgrp is killed if the job fails
	for fd in close_in_child:
		os.close(fd)
	keep_in_child = set(keep_in_child)
	keep_in_child.add(int(os.getenv('BD_STATUS_FD')))
	keep_in_child.add(int(os.getenv('BD_TERM_FD')))
	close_fds(keep_in_child)
	# unreadable stdin - less risk of stuck jobs
	devnull = os.open('/dev/null', os.O_RDONLY)
	os.dup2(devnull, 0)
	os.close(devnull)
	if PY3:
		keep_in_child.update([1, 2])
		for fd in keep_in_child:
			os.set_inheritable(fd, True)
	os.execv(cmd[0], cmd)
	os._exit() 
Example #9
Source File: spawn.py    From meddle with MIT License 6 votes vote down vote up
def _spawn_posix(cmd, search_path=1, verbose=0, dry_run=0):
    log.info(' '.join(cmd))
    if dry_run:
        return
    exec_fn = search_path and os.execvp or os.execv
    pid = os.fork()

    if pid == 0:  # in the child
        try:
            exec_fn(cmd[0], cmd)
        except OSError, e:
            sys.stderr.write("unable to execute %s: %s\n" %
                             (cmd[0], e.strerror))
            os._exit(1)

        sys.stderr.write("unable to execute %s for unknown reasons" % cmd[0])
        os._exit(1) 
Example #10
Source File: process.py    From vanilla with MIT License 6 votes vote down vote up
def bootstrap(self, f, *a, **kw):
        import marshal
        import cPickle as pickle

        pipe_r, pipe_w = os.pipe()
        os.write(pipe_w, pickle.dumps((marshal.dumps(f.func_code), a, kw)))
        os.close(pipe_w)

        bootstrap = '\n'.join(x.strip() for x in ("""
            import cPickle as pickle
            import marshal
            import types
            import sys
            import os

            code, a, kw = pickle.loads(os.read(%(pipe_r)s, 4096))
            os.close(%(pipe_r)s)

            f = types.FunctionType(marshal.loads(code), globals(), 'f')
            f(*a, **kw)
        """ % {'pipe_r': pipe_r}).split('\n') if x)

        argv = [sys.executable, '-u', '-c', bootstrap]
        os.execv(argv[0], argv) 
Example #11
Source File: xos_grpc_client.py    From xos with Apache License 2.0 6 votes vote down vote up
def hash_check(self, pb2_file_name, pb2_grpc_file_name):
        # If the protobufs have changed, then it's likely that new models
        # have been downloaded. One way we have dealt with this in the past
        # is to force a reload() of the affected modules. However, it seems
        # safer to force a full synchronizer restart as this will allow
        # the synchronizer to perform a version check against the core, and
        # it will refresh any data structures that might be affected by the
        # new models.

        pb2_hash = hashlib.sha256(open(pb2_file_name).read())
        pb2_grpc_hash = hashlib.sha256(open(pb2_grpc_file_name).read())

        if (pb2_file_name in self.hashes) or (pb2_grpc_file_name in self.hashes):
            if (pb2_hash != self.hashes[pb2_file_name]) or (pb2_grpc_hash != self.hashes[pb2_grpc_file_name]):
                log.warning(
                    "Protobuf change detected, restarting the synchronzier"
                )
                os.execv(sys.executable, ["python"] + sys.argv)

        self.hashes[pb2_file_name] = pb2_hash
        self.hashes[pb2_grpc_file_name] = pb2_grpc_hash 
Example #12
Source File: LPHK.py    From LPHK with GNU General Public License v3.0 6 votes vote down vote up
def shutdown():
    if lp_events.timer != None:
        lp_events.timer.cancel()
    scripts.to_run = []
    for x in range(9):
        for y in range(9):
            if scripts.threads[x][y] != None:
                scripts.threads[x][y].kill.set()
    if window.lp_connected:
        scripts.unbind_all()
        lp_events.timer.cancel()
        launchpad_connector.disconnect(lp)
        window.lp_connected = False
    logger.stop()
    if window.restart:
        if IS_EXE:
            os.startfile(sys.argv[0])
        else:
            os.execv(sys.executable, ["\"" + sys.executable + "\""] + sys.argv)
    sys.exit("[LPHK] Shutting down...") 
Example #13
Source File: bash.py    From BashBot with MIT License 6 votes vote down vote up
def open(self, loop):
        pid, self.fd = os.forkpty()
        if pid == 0:
            if bot.settings.get("user") and "login" in bot.settings.get("user") and bot.settings.get("user")["login"]:
                    os.execv(bot.settings.get("terminal")["su_path"],
                             [bot.settings.get("terminal")["su_path"], "-", bot.settings.get("user")["login"], "-s", bot.settings.get("terminal")["shell_path"]])
            else:
                os.execv(bot.settings.get("terminal")["shell_path"], [bot.settings.get("terminal")["shell_path"], ])

            sys.exit(0)
        else:
            self.status = "working"

            pty_output = threading.Thread(target=self.watch_output)
            pty_output.start()

            self.update_output(loop)

        return self 
Example #14
Source File: modelaccessor.py    From xos with Apache License 2.0 6 votes vote down vote up
def keep_trying(client, reactor):
    # Keep checking the connection to wait for it to become unavailable.
    # Then reconnect. The strategy is to send NoOp operations, one per second, until eventually a NoOp throws an
    # exception. This will indicate the server has reset. When that happens, we force the client to reconnect, and
    # it will download a new API from the server.

    from xosapi.xos_grpc_client import Empty

    try:
        client.utility.NoOp(Empty())
    except Exception as e:
        # If we caught an exception, then the API has become unavailable.
        # So reconnect.

        log.exception("exception in NoOp", e=e)
        log.info("restarting synchronizer")

        os.execv(sys.executable, ["python"] + sys.argv)
        return

    reactor.callLater(1, functools.partial(keep_trying, client, reactor)) 
Example #15
Source File: process.py    From vanilla with MIT License 5 votes vote down vote up
def execv(self, args, env=None, stderrtoout=False):
        def tryexec(f, *a, **kw):
            try:
                f(*a, **kw)
            except OSError, e:
                if e.errno == errno.ENOENT:
                    os._exit(127)
                if e.errno == errno.EACCES:
                    os._exit(126)
                raise 
Example #16
Source File: test_os.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _execvpe_mockup(defpath=None):
    """
    Stubs out execv and execve functions when used as context manager.
    Records exec calls. The mock execv and execve functions always raise an
    exception as they would normally never return.
    """
    # A list of tuples containing (function name, first arg, args)
    # of calls to execv or execve that have been made.
    calls = []

    def mock_execv(name, *args):
        calls.append(('execv', name, args))
        raise RuntimeError("execv called")

    def mock_execve(name, *args):
        calls.append(('execve', name, args))
        raise OSError(errno.ENOTDIR, "execve called")

    try:
        orig_execv = os.execv
        orig_execve = os.execve
        orig_defpath = os.defpath
        os.execv = mock_execv
        os.execve = mock_execve
        if defpath is not None:
            os.defpath = defpath
        yield calls
    finally:
        os.execv = orig_execv
        os.execve = orig_execve
        os.defpath = orig_defpath 
Example #17
Source File: gazee.py    From gazee with GNU General Public License v3.0 5 votes vote down vote up
def restart(self):
        cherrypy.engine.exit()
        if (os.path.exists(os.path.join(gazee.DATA_DIR, 'db.lock'))):
            os.remove(os.path.join(gazee.DATA_DIR, 'db.lock'))
        popen_list = [sys.executable, gazee.FULL_PATH]
        popen_list += gazee.ARGS
        print("Gazee is restarting")
        logging.info('Restarting Gazee with ' + str(popen_list))
        if sys.platform == 'win32':
            subprocess.Popen(popen_list, cwd=os.getcwd())
            os._exit(0)
        else:
            os.execv(sys.executable, popen_list)
        logging.info('Gazee is restarting...')
        return 
Example #18
Source File: test_os.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _execvpe_mockup(defpath=None):
    """
    Stubs out execv and execve functions when used as context manager.
    Records exec calls. The mock execv and execve functions always raise an
    exception as they would normally never return.
    """
    # A list of tuples containing (function name, first arg, args)
    # of calls to execv or execve that have been made.
    calls = []

    def mock_execv(name, *args):
        calls.append(('execv', name, args))
        raise RuntimeError("execv called")

    def mock_execve(name, *args):
        calls.append(('execve', name, args))
        raise OSError(errno.ENOTDIR, "execve called")

    try:
        orig_execv = os.execv
        orig_execve = os.execve
        orig_defpath = os.defpath
        os.execv = mock_execv
        os.execve = mock_execve
        if defpath is not None:
            os.defpath = defpath
        yield calls
    finally:
        os.execv = orig_execv
        os.execve = orig_execve
        os.defpath = orig_defpath 
Example #19
Source File: entrypoint.py    From iris with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
    iris_config = load_config(
        os.environ.get('IRIS_CFG_PATH', '/home/iris/config/config.yaml'))
    mysql_config = iris_config['db']['conn']['kwargs']

    # It often takes several seconds for MySQL to start up. iris dies upon start
    # if it can't immediately connect to MySQL, so we have to wait for it.
    wait_for_mysql(mysql_config)

    if 'DOCKER_DB_BOOTSTRAP' in os.environ:
        if not os.path.exists(initializedfile):
            initialize_mysql_schema(mysql_config)

    os.execv('/usr/bin/uwsgi',
             ['', '--yaml', os.environ.get('UWSGI_CONFIG', '/home/iris/daemons/uwsgi.yaml:prod')]) 
Example #20
Source File: utils.py    From gibMacOS with MIT License 5 votes vote down vote up
def elevate(self, file):
        # Runs the passed file as admin
        if self.check_admin():
            return
        if os.name == "nt":
            ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, file, None, 1)
        else:
            try:
                p = subprocess.Popen(["which", "sudo"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                c = p.communicate()[0].decode("utf-8", "ignore").replace("\n", "")
                os.execv(c, [ sys.executable, 'python'] + sys.argv)
            except:
                exit(1) 
Example #21
Source File: utils.py    From scapy with GNU General Public License v2.0 5 votes vote down vote up
def restart():
    """Restarts scapy"""
    if not conf.interactive or not os.path.isfile(sys.argv[0]):
        raise OSError("Scapy was not started from console")
    if WINDOWS:
        try:
            res_code = subprocess.call([sys.executable] + sys.argv)
        except KeyboardInterrupt:
            res_code = 1
        finally:
            os._exit(res_code)
    os.execv(sys.executable, [sys.executable] + sys.argv) 
Example #22
Source File: upload_gtest.py    From training_results_v0.5 with Apache License 2.0 5 votes vote down vote up
def main():
  # Finds the path to upload.py, assuming it is in the same directory
  # as this file.
  my_dir = os.path.dirname(os.path.abspath(__file__))
  upload_py_path = os.path.join(my_dir, 'upload.py')

  # Adds Google Test discussion group to the cc line if it's not there
  # already.
  upload_py_argv = [upload_py_path]
  found_cc_flag = False
  for arg in sys.argv[1:]:
    if arg.startswith(CC_FLAG):
      found_cc_flag = True
      cc_line = arg[len(CC_FLAG):]
      cc_list = [addr for addr in cc_line.split(',') if addr]
      if GTEST_GROUP not in cc_list:
        cc_list.append(GTEST_GROUP)
      upload_py_argv.append(CC_FLAG + ','.join(cc_list))
    else:
      upload_py_argv.append(arg)

  if not found_cc_flag:
    upload_py_argv.append(CC_FLAG + GTEST_GROUP)

  # Invokes upload.py with the modified command line flags.
  os.execv(upload_py_path, upload_py_argv) 
Example #23
Source File: larc_output.py    From larva-lang with GNU General Public License v3.0 5 votes vote down vote up
def _run_prog(args_for_run):
    if platform.system() in ("Darwin", "Linux"):
        pass
    else:
        raise Exception("Bug")
    if os.path.exists(_exe_file):
        os.execv(_exe_file, [_exe_file] + args_for_run)
    else:
        larc_common.exit("找不到可执行文件[%s]" % _exe_file) 
Example #24
Source File: simpleStream.py    From alpaca-trade-api-python with Apache License 2.0 5 votes vote down vote up
def reloadWatch(prog, cmd):
    async def watch_command():
        startingmodtime = os.path.getmtime(prog)

        while True:
            modtime = os.path.getmtime(prog)
            if modtime != startingmodtime:
                debug(f'Reloading {" ".join(cmd)} ...')

                os.execv(prog, cmd)

            await asyncio.sleep(5)

    return watch_command 
Example #25
Source File: run_tests.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main(regrtest_args):
    args = [sys.executable,
            '-W', 'default',      # Warnings set to 'default'
            '-bb',                # Warnings about bytes/bytearray
            '-E',                 # Ignore environment variables
            ]
    # Allow user-specified interpreter options to override our defaults.
    args.extend(test.support.args_from_interpreter_flags())

    # Workaround for issue #20361
    args.extend(['-W', 'error::BytesWarning'])

    args.extend(['-m', 'test',    # Run the test suite
                 '-r',            # Randomize test order
                 '-w',            # Re-run failed tests in verbose mode
                 ])
    if sys.platform == 'win32':
        args.append('-n')         # Silence alerts under Windows
    if threading and not any(is_multiprocess_flag(arg) for arg in regrtest_args):
        args.extend(['-j', '0'])  # Use all CPU cores
    if not any(is_resource_use_flag(arg) for arg in regrtest_args):
        args.extend(['-u', 'all,-largefile,-audio,-gui'])
    args.extend(regrtest_args)
    print(' '.join(args))
    if sys.platform == 'win32':
        from subprocess import call
        sys.exit(call(args))
    else:
        os.execv(sys.executable, args) 
Example #26
Source File: utils.py    From thinkpad-x1c5-hackintosh with MIT License 5 votes vote down vote up
def elevate(self, file):
        # Runs the passed file as admin
        if self.check_admin():
            return
        if os.name == "nt":
            ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, file, None, 1)
        else:
            try:
                p = subprocess.Popen(["which", "sudo"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                c = p.communicate()[0].decode("utf-8", "ignore").replace("\n", "")
                os.execv(c, [ sys.executable, 'python'] + sys.argv)
            except:
                exit(1) 
Example #27
Source File: actions.py    From r_e_c_u_r with GNU General Public License v3.0 5 votes vote down vote up
def restart_the_program(self):
        self.quit_the_program()
        os.execv('/usr/bin/python3', [sys.argv[0],'/home/pi/r_e_c_u_r/r_e_c_u_r.py']) 
Example #28
Source File: bot.py    From modmailbotkenng with MIT License 5 votes vote down vote up
def run_wizard():
        '''Wizard for first start'''
        print('------------------------------------------')
        token = input('Enter your token:\n> ')
        print('------------------------------------------')
        data = {
                "TOKEN" : token,
            }
        with open('config.json','w') as f:
            f.write(json.dumps(data, indent=4))
        print('------------------------------------------')
        print('Restarting...')
        print('------------------------------------------')
        os.execv(sys.executable, ['python'] + sys.argv) 
Example #29
Source File: upload_gmock.py    From training_results_v0.5 with Apache License 2.0 5 votes vote down vote up
def main():
  # Finds the path to upload.py, assuming it is in the same directory
  # as this file.
  my_dir = os.path.dirname(os.path.abspath(__file__))
  upload_py_path = os.path.join(my_dir, 'upload.py')

  # Adds Google Mock discussion group to the cc line if it's not there
  # already.
  upload_py_argv = [upload_py_path]
  found_cc_flag = False
  for arg in sys.argv[1:]:
    if arg.startswith(CC_FLAG):
      found_cc_flag = True
      cc_line = arg[len(CC_FLAG):]
      cc_list = [addr for addr in cc_line.split(',') if addr]
      if GMOCK_GROUP not in cc_list:
        cc_list.append(GMOCK_GROUP)
      upload_py_argv.append(CC_FLAG + ','.join(cc_list))
    else:
      upload_py_argv.append(arg)

  if not found_cc_flag:
    upload_py_argv.append(CC_FLAG + GMOCK_GROUP)

  # Invokes upload.py with the modified command line flags.
  os.execv(upload_py_path, upload_py_argv) 
Example #30
Source File: devhelpers.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def exec_editor(*names):
    """Runs your configured editor on a supplied list of files. Uses exec,
there is no return!"""
    ed = get_editor()
    if ed.find("/") >= 0:
        os.execv(ed, (ed,)+names)
    else:
        os.execvp(ed, (ed,)+names)