Python os.execv() Examples

The following are code examples for showing how to use os.execv(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: nojs   Author: chrisdickinson   File: apk_operations.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 2
Project: nojs   Author: chrisdickinson   File: apk_operations.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 3
Project: cheribuild   Author: CTSRD-CHERI   File: __main__.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 4
Project: mitogen   Author: dw   File: master.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 5
Project: Taigabot   Author: FrozenPigs   File: seen.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 6
Project: jumpscale_portal   Author: jumpscale7   File: SocketProcess.py    (license) View Source Project 6 votes vote down vote up
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 
Example 7
Project: jumpscale_portal   Author: jumpscale7   File: PortalServer.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 8
Project: performance   Author: python   File: venv.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 9
Project: My-Web-Server-Framework-With-Python2.7   Author: syjsu   File: os.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 10
Project: taktyk   Author: kosior   File: script_commands.py    (license) View Source Project 6 votes vote down vote up
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 
Example 11
Project: autosub-bootstrapbill   Author: BenjV   File: wspbus.py    (license) View Source Project 6 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 12
Project: ccs-twistedextensions   Author: apple   File: service.py    (license) View Source Project 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 13
Project: cid-tool   Author: futoin   File: cid_deploy_test.py    (license) View Source Project 6 votes vote down vote up
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 
Example 14
Project: cid-tool   Author: futoin   File: cid_realapp_test.py    (license) View Source Project 6 votes vote down vote up
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 
Example 15
Project: cid-tool   Author: futoin   File: cid_realapp_test.py    (license) View Source Project 6 votes vote down vote up
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 
Example 16
Project: watcher   Author: nosmokingbandit   File: wspbus.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 17
Project: watcher   Author: nosmokingbandit   File: wspbus.py    (license) View Source Project 6 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 18
Project: ptterm   Author: jonathanslenders   File: posix.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 19
Project: requirements-tools   Author: Yelp   File: upgrade_requirements.py    (MIT License) View Source Project 5 votes vote down vote up
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) 
Example 20
Project: uzdevsbot   Author: Uzbek-Developers   File: reloader.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 21
Project: TerminalView   Author: Wramberg   File: linux_pty.py    (MIT License) View Source Project 5 votes vote down vote up
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) 
Example 22
Project: ScraXBRL   Author: tooksoi   File: main.py    (MIT License) View Source Project 5 votes vote down vote up
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__)]) 
Example 23
Project: endpoints-tools   Author: cloudendpoints   File: start_esp.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
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) 
Example 24
Project: hostapd-mana   Author: adde88   File: _twistd_unix.py    (license) View Source Project 5 votes vote down vote up
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:]) 
Example 25
Project: Taigabot   Author: FrozenPigs   File: core_admin_global.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 26
Project: Taigabot   Author: FrozenPigs   File: seen.py    (license) View Source Project 5 votes vote down vote up
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 
Example 27
Project: runtests   Author: bccp   File: tester.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 28
Project: Pext   Author: Pext   File: __main__.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 29
Project: Excalibot   Author: endreman0   File: maintenance.py    (license) View Source Project 5 votes vote down vote up
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:]) 
Example 30
Project: unsonic   Author: redshodan   File: serve.py    (license) View Source Project 5 votes vote down vote up
def run(self, args, config):
        pargs = args.pserve_args

        if not config.filename:
            print("No config file specified. Must specify a config file.")
            sys.exit(-1)

        # unsonic-server is needed to keep the cmdline args for pserve for its
        # reload option with hupper, otherwise pserve/hupper gets confused.
        paths = [os.path.abspath(
                     os.path.join(*list(os.path.split(unsonic.CMD)[:-1]) +
                                  ["unsonic-server"])),
                 os.path.abspath(os.path.join(os.path.dirname(__file__),
                                              "../../", "bin/unsonic-server")),
                 shutil.which("unsonic-server")]
        for path in paths:
            if os.access(path, os.X_OK):
                break
        else:
            path = None
        if not path:
            print("Failed to find the unsonic-server command.")
            sys.exit(-1)

        argv = [path]
        if len(pargs) and pargs[0] == "--":
            pargs = pargs[1:]
        argv.extend(pargs)
        argv.append(str(config.filename))
        print(" ".join(argv))
        os.execv(path, argv) 
Example 31
Project: zippy   Author: securesystemslab   File: test_os.py    (license) View Source Project 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 32
Project: ud_wxpy   Author: evestorm   File: evebot.py    (license) View Source Project 5 votes vote down vote up
def _restart():
    os.execv(sys.executable, [sys.executable] + sys.argv)


# process = psutil.Process() 
Example 33
Project: dogbot   Author: slice   File: admin.py    (license) View Source Project 5 votes vote down vote up
def restart_inplace():
    """Restarts the bot inplace."""
    logger.info('reboot: executable=%s argv=%s', sys.executable, sys.argv)
    os.execv(sys.executable, [sys.executable] + sys.argv) 
Example 34
Project: vivisect-py3   Author: bat-serjo   File: freebsd.py    (license) View Source Project 5 votes vote down vote up
def platformExec(self, cmdline):
        # Basically just like the one in the Ptrace mixin...
        self.execing = True
        cmdlist = e_cli.splitargs(cmdline)
        os.stat(cmdlist[0])
        pid = os.fork()
        if pid == 0:
            v_posix.ptrace(PT_TRACE_ME, 0, 0, 0)
            os.execv(cmdlist[0], cmdlist)
            sys.exit(-1)
        return pid 
Example 35
Project: vivisect-py3   Author: bat-serjo   File: posix.py    (license) View Source Project 5 votes vote down vote up
def platformExec(self, cmdline):
        self.execing = True
        cmdlist = e_cli.splitargs(cmdline)
        os.stat(cmdlist[0])
        pid = os.fork()
        if pid == 0:
            ptrace(PT_TRACE_ME, 0, 0, 0)
            os.execv(cmdlist[0], cmdlist)
            sys.exit(-1)
        return pid 
Example 36
Project: Doc-Analysis-Public-Data   Author: AdnanMuhib   File: GUI.py    (license) View Source Project 5 votes vote down vote up
def refreshWindow(self):
        self.btnProcessAgain.setVisible(False)
        self.btnProcessImage.setVisible(True)
        self.btnImageBrowse.setEnabled(True)
        os.execv(sys.executable, ['python'] + sys.argv) 
Example 37
Project: EmaProject   Author: halkliff   File: EmaBot.py    (license) View Source Project 5 votes vote down vote up
def main_loop():
    while True:
        try:
            bot.polling(none_stop=True)
        except Exception as e:
            print("Exception occurred:", e)
            break
            time.sleep(2)
            os.execv(sys.executable, ['python'] + sys.argv)
            pass
        else:
            break
    while 1:
        time.sleep(3) 
Example 38
Project: sslstrip-hsts-openwrt   Author: adde88   File: _twistd_unix.py    (license) View Source Project 5 votes vote down vote up
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:]) 
Example 39
Project: django-gateone   Author: jimmy201602   File: ssh_connect.py    (license) View Source Project 5 votes vote down vote up
def took_too_long():
    """
    Called when :meth:`main` takes too long to run its course (idle timeout
    before any connection was made).
    """
    timeout_script = os.path.join(APPLICATION_PATH, 'timeout.sh')
    sys.stdout.flush()
    # Calling execv() so we can quit the main process to reduce memory usage
    os.execv('/bin/sh', ['-c', timeout_script])
    os._exit(0) 
Example 40
Project: specto   Author: mrknow   File: pydev_monkey.py    (license) View Source Project 5 votes vote down vote up
def create_execv(original_name):
    def new_execv(path, args):
        """
        os.execv(path, args)
        os.execvp(file, args)
        """
        import os
        send_process_created_message()
        return getattr(os, original_name)(path, patch_args(args))
    return new_execv 
Example 41
Project: specto   Author: mrknow   File: pydev_monkey.py    (license) View Source Project 5 votes vote down vote up
def patch_new_process_functions_with_warning():
    monkey_patch_os('execl', create_warn_multiproc)
    monkey_patch_os('execle', create_warn_multiproc)
    monkey_patch_os('execlp', create_warn_multiproc)
    monkey_patch_os('execlpe', create_warn_multiproc)
    monkey_patch_os('execv', create_warn_multiproc)
    monkey_patch_os('execve', create_warn_multiproc)
    monkey_patch_os('execvp', create_warn_multiproc)
    monkey_patch_os('execvpe', create_warn_multiproc)
    monkey_patch_os('spawnl', create_warn_multiproc)
    monkey_patch_os('spawnle', create_warn_multiproc)
    monkey_patch_os('spawnlp', create_warn_multiproc)
    monkey_patch_os('spawnlpe', create_warn_multiproc)
    monkey_patch_os('spawnv', create_warn_multiproc)
    monkey_patch_os('spawnve', create_warn_multiproc)
    monkey_patch_os('spawnvp', create_warn_multiproc)
    monkey_patch_os('spawnvpe', create_warn_multiproc)

    if sys.platform != 'win32':
        monkey_patch_os('fork', create_warn_multiproc)
        try:
            import _posixsubprocess
            monkey_patch_module(_posixsubprocess, 'fork_exec', create_warn_fork_exec)
        except ImportError:
            pass
    else:
        # Windows
        try:
            import _subprocess
        except ImportError:
            import _winapi as _subprocess
        monkey_patch_module(_subprocess, 'CreateProcess', create_CreateProcessWarnMultiproc) 
Example 42
Project: web_ctp   Author: molebot   File: test_os.py    (license) View Source Project 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 43
Project: time2go   Author: twitchyliquid64   File: autoreload.py    (license) View Source Project 5 votes vote down vote up
def _reload():
    global _reload_attempted
    _reload_attempted = True
    for fn in _reload_hooks:
        fn()
    if hasattr(signal, "setitimer"):
        # Clear the alarm signal set by
        # ioloop.set_blocking_log_threshold so it doesn't fire
        # after the exec.
        signal.setitimer(signal.ITIMER_REAL, 0, 0)
    if sys.platform == 'win32':
        # os.execv is broken on Windows and can't properly parse command line
        # arguments and executable name if they contain whitespaces. subprocess
        # fixes that behavior.
        subprocess.Popen([sys.executable] + sys.argv)
        sys.exit(0)
    else:
        try:
            os.execv(sys.executable, [sys.executable] + sys.argv)
        except OSError:
            # Mac OS X versions prior to 10.6 do not support execv in
            # a process that contains multiple threads.  Instead of
            # re-executing in the current process, start a new one
            # and cause the current process to exit.  This isn't
            # ideal since the new process is detached from the parent
            # terminal and thus cannot easily be killed with ctrl-C,
            # but it's better than not being able to autoreload at
            # all.
            # Unfortunately the errno returned in this case does not
            # appear to be consistent, so we can't easily check for
            # this error specifically.
            os.spawnv(os.P_NOWAIT, sys.executable,
                      [sys.executable] + sys.argv)
            sys.exit(0) 
Example 44
Project: bnc-bot   Author: snoonetIRC   File: __main__.py    (license) View Source Project 5 votes vote down vote up
def main():
    with open('.bncbot.pid', 'w') as pid_file:
        pid_file.write(str(os.getpid()))
    conn = Conn(bot.HANDLERS)

    original_sigint = signal.getsignal(signal.SIGINT)

    def handle_sig(sig, frame):
        if sig == signal.SIGINT:
            if conn:
                asyncio.run_coroutine_threadsafe(conn.shutdown(), conn.loop)
            signal.signal(signal.SIGINT, original_sigint)
        elif sig == signal.SIGHUP:
            if conn:
                asyncio.run_coroutine_threadsafe(conn.shutdown(True), conn.loop)

    signal.signal(signal.SIGINT, handle_sig)
    signal.signal(signal.SIGHUP, handle_sig)
    restart = conn.run()
    if restart:
        conn = None
        time.sleep(1)
        os.chdir(original_wd)
        args = sys.argv
        for f in [sys.stdout, sys.stderr]:
            f.flush()
        os.execv(sys.executable, [sys.executable] + args) 
Example 45
Project: bitmex-market-maker   Author: amanelis   File: market_maker.py    (license) View Source Project 5 votes vote down vote up
def restart(self):
        logger.info("Restarting the market maker...")
        os.execv(sys.executable, [sys.executable] + sys.argv)

#
# Helpers
# 
Example 46
Project: gazee   Author: hubbcaps   File: gazee.py    (license) View Source Project 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 47
Project: FuzzFlow   Author: talos-vulndev   File: helper.py    (license) View Source Project 5 votes vote down vote up
def update(self):
        print "[*] Trying to update the client..."
        try:
            with open("client.zip", "rb") as f:
                cli = f.read()
                hsh = hashlib.md5(cli).hexdigest()
        except IOError:
            hsh = "INVALID"

        path = Rest.get_update(hsh)
        if path is not None:
            shutil.rmtree('engine')
            shutil.rmtree('client')
            os.remove('client.py')
            os.remove('requirements.txt')

            f = zipfile.ZipFile(path, "r")
            f.extractall('tmp')
            f.close()

            root = 'tmp' + os.sep + 'client' + os.sep
            shutil.move(root + 'client', '.')
            shutil.move(root + 'engine', '.')
            shutil.move(root + 'client.py', '.')
            shutil.move(root + 'requirements.txt', '.')
            shutil.rmtree('tmp')

            args = sys.argv[:]
            print "[*] Update installed successfully, restarting...\n"

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

            os.execv(sys.executable, args)
            sys.exit(1)

        else:
            print "[!] Client is already the latest version." 
Example 48
Project: Doc-Analysis-commercial-data   Author: AdnanMuhib   File: GUI.py    (license) View Source Project 5 votes vote down vote up
def refreshWindow(self):
        self.btnProcessAgain.setVisible(False)
        self.btnProcessImage.setVisible(True)
        self.btnProcessImage.setEnabled(True)
        os.execv(sys.executable, ['python'] + sys.argv) 
Example 49
Project: cpp-boilerplate   Author: xwvvvvwx   File: upload_gtest.py    (license) View Source Project 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 50
Project: cpp-boilerplate   Author: xwvvvvwx   File: upload_gmock.py    (license) View Source Project 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)