Python os.execvpe() Examples

The following are 30 code examples of os.execvpe(). 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: test_process.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_executionError(self):
        """
        Raise an error during execvpe to check error management.
        """
        cmd = self.getCommand('false')

        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        def buggyexecvpe(command, args, environment):
            raise RuntimeError("Ouch")
        oldexecvpe = os.execvpe
        os.execvpe = buggyexecvpe
        try:
            reactor.spawnProcess(p, cmd, [b'false'], env=None,
                                 usePTY=self.usePTY)

            def check(ignored):
                errData = b"".join(p.errData + p.outData)
                self.assertIn(b"Upon execvpe", errData)
                self.assertIn(b"Ouch", errData)
            d.addCallback(check)
        finally:
            os.execvpe = oldexecvpe
        return d 
Example #2
Source File: vterm.py    From anyMesh-Python with MIT License 6 votes vote down vote up
def spawn(self):
        env = self.env
        env['TERM'] = 'linux'

        self.pid, self.master = pty.fork()

        if self.pid == 0:
            if callable(self.command):
                try:
                    try:
                        self.command()
                    except:
                        sys.stderr.write(traceback.format_exc())
                        sys.stderr.flush()
                finally:
                    os._exit(0)
            else:
                os.execvpe(self.command[0], self.command, env)

        if self.main_loop is None:
            fcntl.fcntl(self.master, fcntl.F_SETFL, os.O_NONBLOCK)

        atexit.register(self.terminate) 
Example #3
Source File: process.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _execChild(self, path, uid, gid, executable, args, environment):
        """
        The exec() which is done in the forked child.
        """
        if path:
            os.chdir(path)
        if uid is not None or gid is not None:
            if uid is None:
                uid = os.geteuid()
            if gid is None:
                gid = os.getegid()
            # set the UID before I actually exec the process
            os.setuid(0)
            os.setgid(0)
            switchUID(uid, gid)
        os.execvpe(executable, args, environment) 
Example #4
Source File: test_process.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_executionError(self):
        """
        Raise an error during execvpe to check error management.
        """
        cmd = self.getCommand('false')

        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        def buggyexecvpe(command, args, environment):
            raise RuntimeError("Ouch")
        oldexecvpe = os.execvpe
        os.execvpe = buggyexecvpe
        try:
            reactor.spawnProcess(p, cmd, ['false'], env=None,
                                 usePTY=self.usePTY)

            def check(ignored):
                errData = "".join(p.errData + p.outData)
                self.assertIn("Upon execvpe", errData)
                self.assertIn("Ouch", errData)
            d.addCallback(check)
        finally:
            os.execvpe = oldexecvpe
        return d 
Example #5
Source File: posix.py    From pivy with ISC License 6 votes vote down vote up
def exec_fork(l, env): 
    pid = os.fork()
    if not pid:
        # Child process.
        exitval = 127
        try:
            os.execvpe(l[0], l, env)
        except OSError as e:
            exitval = exitvalmap.get(e[0], e[0])
            sys.stderr.write("scons: %s: %s\n" % (l[0], e[1]))
        os._exit(exitval)
    else:
        # Parent process.
        pid, stat = os.waitpid(pid, 0)
        if stat & 0xff:
            return stat | 0x80
        return stat >> 8 
Example #6
Source File: test_process.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_executionError(self):
        """
        Raise an error during execvpe to check error management.
        """
        cmd = self.getCommand('false')

        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        def buggyexecvpe(command, args, environment):
            raise RuntimeError("Ouch")
        oldexecvpe = os.execvpe
        os.execvpe = buggyexecvpe
        try:
            reactor.spawnProcess(p, cmd, [b'false'], env=None,
                                 usePTY=self.usePTY)

            def check(ignored):
                errData = b"".join(p.errData + p.outData)
                self.assertIn(b"Upon execvpe", errData)
                self.assertIn(b"Ouch", errData)
            d.addCallback(check)
        finally:
            os.execvpe = oldexecvpe
        return d 
Example #7
Source File: nvr.py    From neovim-remote with MIT License 6 votes vote down vote up
def execute_new_nvim_process(self, silent, nvr, options, arguments):
        if not silent:
            print(textwrap.dedent('''\
                [*] Starting new nvim process using $NVR_CMD or 'nvim'.

                    Use --nostart to avoid starting a new process.
            '''))

        args = os.environ.get('NVR_CMD')
        args = args.split(' ') if args else ['nvim']

        multiprocessing.Process(target=self.try_attach, args=(args, nvr, options, arguments)).start()

        os.environ['NVIM_LISTEN_ADDRESS'] = self.address
        try:
            os.execvpe(args[0], args, os.environ)
        except FileNotFoundError:
            print("[!] Can't start new nvim process: '{}' is not in $PATH.".format(args[0]))
            sys.exit(1) 
Example #8
Source File: arbiter.py    From Flask-P2P with MIT License 6 votes vote down vote up
def reexec(self):
        """\
        Relaunch the master and workers.
        """
        if self.pidfile is not None:
            self.pidfile.rename("%s.oldbin" % self.pidfile.fname)

        self.reexec_pid = os.fork()
        if self.reexec_pid != 0:
            self.master_name = "Old Master"
            return

        environ = self.cfg.env_orig.copy()
        fds = [l.fileno() for l in self.LISTENERS]
        environ['GUNICORN_FD'] = ",".join([str(fd) for fd in fds])

        os.chdir(self.START_CTX['cwd'])
        self.cfg.pre_exec(self)

        # exec the process using the original environnement
        os.execvpe(self.START_CTX[0], self.START_CTX['args'], environ) 
Example #9
Source File: process.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _execChild(self, path, uid, gid, executable, args, environment):
        """
        The exec() which is done in the forked child.
        """
        if path:
            os.chdir(path)
        if uid is not None or gid is not None:
            if uid is None:
                uid = os.geteuid()
            if gid is None:
                gid = os.getegid()
            # set the UID before I actually exec the process
            os.setuid(0)
            os.setgid(0)
            switchUID(uid, gid)
        os.execvpe(executable, args, environment) 
Example #10
Source File: server.py    From promnesia with MIT License 6 votes vote down vote up
def _run(*, port: str, db: Optional[Path]=None, timezone: str, quiet: bool):
    logger = get_logger()
    env = {
        **os.environ,
        # not sure if there is a simpler way to communicate with hug..
        # # TODO here
        _ENV_CONFIG: json.dumps({
            'timezone': timezone,
            **({} if db is None else {'db': str(db)})
        }),
    }
    args = [
        'python3',
        '-m', 'hug', # TODO eh, not sure about this. what if user had it already installed?? it's a mess..
        *(['--silent'] if quiet else []),
        '-p', port,
        '-f', __file__,
    ]
    logger.info('Running server: %s', args)
    os.execvpe('python3', args, env) 
Example #11
Source File: process.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _execChild(self, path, settingUID, uid, gid,
                   executable, args, environment):
        """
        The exec() which is done in the forked child.
        """
        if path:
            os.chdir(path)
        # set the UID before I actually exec the process
        if settingUID:
            switchUID(uid, gid)
        os.execvpe(executable, args, environment) 
Example #12
Source File: test_process.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_mockWithExecError(self):
        """
        Spawn a process but simulate an error during execution in the client
        path: C{os.execvpe} raises an error. It should close all the standard
        fds, try to print the error encountered, and exit cleanly.
        """
        cmd = '/mock/ouch'

        d = defer.Deferred()
        p = TrivialProcessProtocol(d)
        self.mockos.raiseExec = True
        try:
            reactor.spawnProcess(p, cmd, ['ouch'], env=None,
                                 usePTY=False)
        except SystemError:
            self.assert_(self.mockos.exited)
            self.assertEquals(
                self.mockos.actions, [("fork", False), "exec", "exit"])
            # Check that fd have been closed
            self.assertIn(0, self.mockos.closed)
            self.assertIn(1, self.mockos.closed)
            self.assertIn(2, self.mockos.closed)
            # Check content of traceback
            self.assertIn("RuntimeError: Bar", self.mockos.fdio.getvalue())
        else:
            self.fail("Should not be here") 
Example #13
Source File: test_process.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def execvpe(self, command, args, env):
        """
        Fake C{os.execvpe}. Save the action, and raise an error if
        C{self.raiseExec} is set.
        """
        self.actions.append('exec')
        if self.raiseExec:
            raise RuntimeError("Bar") 
Example #14
Source File: external_search_command.py    From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def _execute(path, argv, environ):
            if environ is None:
                os.execvp(path, argv)
            else:
                os.execvpe(path, argv, environ)
            return

    # endregion 
Example #15
Source File: base.py    From docky with GNU Affero General Public License v3.0 5 votes vote down vote up
def _exec(self, cmd, args=[]):
        """Run a command in the same process and log it
        this will replace the current process by the cmd"""
        logger.debug(cmd + ' '.join(args))
        os.execvpe(cmd, [cmd] + args, local.env) 
Example #16
Source File: pydev_monkey.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def create_execve(original_name):
    """
    os.execve(path, args, env)
    os.execvpe(file, args, env)
    """
    def new_execve(path, args, env):
        import os
        return getattr(os, original_name)(path, patch_args(args), env)
    return new_execve 
Example #17
Source File: pydev_monkey.py    From filmkodi with Apache License 2.0 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 #18
Source File: util.py    From cli with MIT License 5 votes vote down vote up
def exec_or_return(argv: List[str], extra_env: Mapping = {}) -> int:
    """
    exec(3) into the desired program, or return 1 on failure.  Never returns if
    successful.

    The return value makes this suitable for chaining through to sys.exit().

    On Windows (or other non-POSIX OSs), where os.execvp() is not properly
    supported¹, this forks another process, waits for it to finish, and then
    exits with the same return code.  A proper POSIX exec(3) is still more
    desirable when available as it properly handles file descriptors and
    signals.

    If an *extra_env* mapping is passed, the provided keys and values are
    overlayed onto the current environment.

    ¹ https://bugs.python.org/issue9148
    """
    env = os.environ.copy()

    if extra_env:
        env.update(extra_env)

    # Use a POSIX exec(3) for file descriptor and signal handling…
    if os.name == "posix":
        try:
            os.execvpe(argv[0], argv, env)
        except OSError as error:
            warn("Error executing into %s: %s" % (argv, error))
            return 1

    # …or naively emulate one when not available.
    else:
        try:
            process = subprocess.run(argv, env = env)
        except OSError as error:
            warn("Error running %s: %s" % (argv, error))
            return 1
        else:
            exit(process.returncode) 
Example #19
Source File: test_os.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def test_execvpe_with_bad_arglist(self):
        self.assertRaises(ValueError, os.execvpe, 'notepad', [], None) 
Example #20
Source File: external_search_command.py    From vscode-extension-splunk with MIT License 5 votes vote down vote up
def _execute(path, argv, environ):
            if environ is None:
                os.execvp(path, argv)
            else:
                os.execvpe(path, argv, environ)
            return

    # endregion 
Example #21
Source File: external_search_command.py    From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def _execute(path, argv, environ):
            if environ is None:
                os.execvp(path, argv)
            else:
                os.execvpe(path, argv, environ)
            return

    # endregion 
Example #22
Source File: __main__.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def legacy(options=None, unknown=None):
    from burpui.utils import lookup_file

    if unknown is None:
        unknown = []
    if not options:
        options, unknown = parse_args(mode=False, name='burpui-legacy')
    env = os.environ

    if options.config:
        conf = lookup_file(options.config, guess=False)
    else:
        if 'BUI_CONFIG' in env:
            conf = env['BUI_CONFIG']
        else:
            conf = lookup_file()
    check_config(conf)

    env['BUI_MODE'] = 'legacy'
    env['BUI_CONFIG'] = conf
    if os.path.isdir('burpui'):
        env['FLASK_APP'] = 'burpui/cli.py'
    else:
        env['FLASK_APP'] = 'burpui.cli'
    env['BUI_VERBOSE'] = str(options.log)
    if options.logfile:
        env['BUI_LOGFILE'] = options.logfile
    if options.debug:
        env['BUI_DEBUG'] = '1'
        env['FLASK_DEBUG'] = '1'

    args = [
        'flask',
        'legacy'
    ]
    args += unknown
    args += [x for x in options.remaining if x != '--']

    os.execvpe(args[0], args, env) 
Example #23
Source File: posix.py    From sitoa with Apache License 2.0 5 votes vote down vote up
def exec_piped_fork(l, env, stdout, stderr):
    # spawn using fork / exec and providing a pipe for the command's
    # stdout / stderr stream
    if stdout != stderr:
        (rFdOut, wFdOut) = os.pipe()
        (rFdErr, wFdErr) = os.pipe()
    else:
        (rFdOut, wFdOut) = os.pipe()
        rFdErr = rFdOut
        wFdErr = wFdOut
    # do the fork
    pid = os.fork()
    if not pid:
        # Child process
        os.close( rFdOut )
        if rFdOut != rFdErr:
            os.close( rFdErr )
        os.dup2( wFdOut, 1 ) # is there some symbolic way to do that ?
        os.dup2( wFdErr, 2 )
        os.close( wFdOut )
        if stdout != stderr:
            os.close( wFdErr )
        exitval = 127
        try:
            os.execvpe(l[0], l, env)
        except OSError, e:
            exitval = exitvalmap.get(e[0], e[0])
            stderr.write("scons: %s: %s\n" % (l[0], e[1]))
        os._exit(exitval) 
Example #24
Source File: test_process.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def execvpe(self, command, args, env):
        """
        Fake C{os.execvpe}. Save the action, and raise an error if
        C{self.raiseExec} is set.
        """
        self.actions.append('exec')
        if self.raiseExec:
            raise RuntimeError("Bar") 
Example #25
Source File: test_os.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_execvpe_with_bad_program(self):
        self.assertRaises(OSError, os.execvpe, 'no such app-',
                          ['no such app-'], None) 
Example #26
Source File: posix.py    From sitoa with Apache License 2.0 5 votes vote down vote up
def exec_fork(l, env): 
    pid = os.fork()
    if not pid:
        # Child process.
        exitval = 127
        try:
            os.execvpe(l[0], l, env)
        except OSError, e:
            exitval = exitvalmap.get(e[0], e[0])
            sys.stderr.write("scons: %s: %s\n" % (l[0], e[1]))
        os._exit(exitval) 
Example #27
Source File: test_os.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_execvpe_with_bad_arglist(self):
        self.assertRaises(ValueError, os.execvpe, 'notepad', [], None) 
Example #28
Source File: test_os.py    From gcblue with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_execvpe_with_bad_arglist(self):
        self.assertRaises(ValueError, os.execvpe, 'notepad', [], None) 
Example #29
Source File: __main__.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def server(options=None, unknown=None):
    from burpui.utils import lookup_file

    if unknown is None:
        unknown = []
    if not options:
        options, unknown = parse_args(mode=False)
    env = os.environ

    if options.config:
        conf = lookup_file(options.config, guess=False)
    else:
        if 'BUI_CONFIG' in env:
            conf = env['BUI_CONFIG']
        else:
            conf = lookup_file()
    check_config(conf)

    if os.path.isdir('burpui'):
        env['FLASK_APP'] = 'burpui/cli.py'
    else:
        env['FLASK_APP'] = 'burpui.cli'
    env['BUI_CONFIG'] = conf
    env['BUI_VERBOSE'] = str(options.log)
    if options.logfile:
        env['BUI_LOGFILE'] = options.logfile
    if options.debug:
        env['BUI_DEBUG'] = '1'
        env['FLASK_DEBUG'] = '1'
    env['BUI_MODE'] = 'server'

    args = [
        'flask',
        'run'
    ]
    args += unknown
    args += [x for x in options.remaining if x != '--']

    os.execvpe(args[0], args, env) 
Example #30
Source File: launcher.py    From spinalcordtoolbox with MIT License 5 votes vote down vote up
def main():
	"""
	Compatibility entry point to run scripts
	"""

	# Force scripts to not use graphical output
	env = dict()
	env.update(os.environ)

	if "DISPLAY" not in os.environ:
		# No DISPLAY, set suitable default matplotlib backend as pyplot is used
		env["MPLBACKEND"] = "Agg"

	if "ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS" not in os.environ:
		env["ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS"] = str(multiprocessing.cpu_count())

	command = os.path.basename(sys.argv[0])
	sct_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
	script = os.path.join(sct_dir, "scripts", "{}.py".format(command))
	assert os.path.exists(script)
	cmd = [sys.executable, script] + sys.argv[1:]

	mpi_flags = os.environ.get("SCT_MPI_MODE", None)
	if mpi_flags is not None:
		if mpi_flags == "yes": # compat
			mpi_flags = "-n 1"
		cmd = ["mpiexec"] + mpi_flags.split() + cmd

	os.execvpe(cmd[0], cmd[0:], env)