Python os.spawnvpe() Examples

The following are 22 code examples of os.spawnvpe(). 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: smb.py    From smbwrapper with GNU General Public License v3.0 6 votes vote down vote up
def winexe(cmd):
	check_tool('winexe')
	creds = '%s/%s%%%s' % (CONF['smb_domain'], CONF['smb_user'], CONF['smb_pass'])

	run = []
	run.append(TOOLS['winexe'])
	if CONF['system']:
		run.append('--system')
	run.append('--uninstall')
	run.append('--interactive=0')
	run.append('-U')
	run.append(creds)
	run.append('//'+ CONF['smb_ip'])
	run.append(cmd)

	if not cmd.lower().startswith('cmd'):
		process = subprocess.Popen(run, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)

		ret = process.stdout.read()
		ret = ret.replace('\x00', '')
		return ret.strip()

	# For an interactive command line, don't use popen
	os.spawnvpe(os.P_WAIT, run[0], run, os.environ)
	return '' 
Example #2
Source File: pydev_monkey.py    From PyDev.Debugger with Eclipse Public License 1.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)
    monkey_patch_os('posix_spawn', create_warn_multiproc)

    if not IS_JYTHON:
        if not IS_WINDOWS:
            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 #3
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 #4
Source File: pydev_monkey.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def create_spawnve(original_name):
    """
    os.spawnve(mode, path, args, env)
    os.spawnvpe(mode, file, args, env)
    """
    def new_spawnve(mode, path, args, env):
        import os
        return getattr(os, original_name)(mode, path, patch_args(args), env)
    return new_spawnve 
Example #5
Source File: test_os.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_spawnvpe_invalid_env(self):
        self._test_invalid_env(os.spawnvpe)


# The introduction of this TestCase caused at least two different errors on
# *nix buildbots. Temporarily skip this to let the buildbots move along. 
Example #6
Source File: posix.py    From sitoa with Apache License 2.0 5 votes vote down vote up
def exec_spawnvpe(l, env):
    stat = os.spawnvpe(os.P_WAIT, l[0], l, env)
    # os.spawnvpe() returns the actual exit code, not the encoding
    # returned by os.waitpid() or os.system().
    return stat 
Example #7
Source File: base.py    From docker_interface with Apache License 2.0 5 votes vote down vote up
def execute_command(self, parts, dry_run):
        """
        Execute a command.

        Parameters
        ----------
        parts : list
            Sequence of strings constituting a command.
        dry_run : bool
            Whether to just log the command instead of executing it.

        Returns
        -------
        status : int
            Status code of the executed command or 0 if `dry_run` is `True`.
        """
        if dry_run:
            self.logger.info("dry-run command '%s'", " ".join(map(str, parts)))
            return 0
        else:  # pragma: no cover
            self.logger.debug("executing command '%s'", " ".join(map(str, parts)))
            status_code = os.spawnvpe(os.P_WAIT, parts[0], parts, os.environ)
            if status_code:
                self.logger.warning("command '%s' returned status code %d",
                                    " ".join(map(str, parts)), status_code)
            return status_code 
Example #8
Source File: systemctl3.py    From vanilla-docker with MIT License 5 votes vote down vote up
def execve_from(self, conf, cmd, env):
        """ this code is commonly run in a child process // returns exit-code"""
        runs = conf.get("Service", "Type", "simple").lower()
        logg.debug("%s process for %s", runs, conf.filename())
        inp = open("/dev/zero")
        out = self.open_journal_log(conf)
        os.dup2(inp.fileno(), sys.stdin.fileno())
        os.dup2(out.fileno(), sys.stdout.fileno())
        os.dup2(out.fileno(), sys.stderr.fileno())
        runuser = self.expand_special(conf.get("Service", "User", ""), conf)
        rungroup = self.expand_special(conf.get("Service", "Group", ""), conf)
        envs = shutil_setuid(runuser, rungroup)
        badpath = self.chdir_workingdir(conf) # some dirs need setuid before
        if badpath:
            logg.error("(%s): bad workingdir: '%s'", shell_cmd(cmd), badpath)
            sys.exit(1)
        env = self.extend_exec_env(env)
        env.update(envs) # set $HOME to ~$USER
        try:
            if "spawn" in COVERAGE:
                os.spawnvpe(os.P_WAIT, cmd[0], cmd, env)
                sys.exit(0)
            else: # pragma: nocover
                os.execve(cmd[0], cmd, env)
        except Exception as e:
            logg.error("(%s): %s", shell_cmd(cmd), e)
            sys.exit(1) 
Example #9
Source File: util.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def open_text_editor(data):
    if data is None:
        data = ""

    fd, path = tempfile.mkstemp()
    os.close(fd)

    with open(path, 'w') as output:
        output.write(data)

    # Get modified time before calling editor.
    orig_mtime = os.path.getmtime(path)

    editor = os.environ.get("EDITOR", "vim")
    os.spawnvpe(os.P_WAIT, editor, [editor, path], os.environ)

    with open(path, 'r') as source:
        data = source.read()

    # Check if the file has been modified, and if it has, send the update.
    new_mtime = os.path.getmtime(path)
    if new_mtime == orig_mtime:
        data = None

    os.remove(path)
    return data 
Example #10
Source File: pydev_monkey.py    From PyDev.Debugger with Eclipse Public License 1.0 5 votes vote down vote up
def create_spawnve(original_name):
    """
    os.spawnve(mode, path, args, env)
    os.spawnvpe(mode, file, args, env)
    """

    def new_spawnve(mode, path, args, env):
        if _get_apply_arg_patching():
            args = patch_args(args)
            send_process_created_message()

        return getattr(os, original_name)(mode, path, args, env)

    return new_spawnve 
Example #11
Source File: posix.py    From pivy with ISC License 5 votes vote down vote up
def exec_spawnvpe(l, env):
    stat = os.spawnvpe(os.P_WAIT, l[0], l, env)
    # os.spawnvpe() returns the actual exit code, not the encoding
    # returned by os.waitpid() or os.system().
    return stat 
Example #12
Source File: test_os.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_spawnvpe_invalid_env(self):
        self._test_invalid_env(os.spawnvpe) 
Example #13
Source File: device.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def edit(ctx):
    """
    Interactively edit the host configuration.
    """
    url = ctx.obj['base_url'] + "/config/hostconfig"
    req = router_request("GET", url, dump=False)
    config = req.json()

    fd, path = tempfile.mkstemp()
    os.close(fd)

    with open(path, 'w') as output:
        output.write(yaml.safe_dump(config, default_flow_style=False))

    # Get modified time before calling editor.
    orig_mtime = os.path.getmtime(path)

    editor = os.environ.get("EDITOR", "vim")
    os.spawnvpe(os.P_WAIT, editor, [editor, path], os.environ)

    with open(path, 'r') as source:
        data = source.read()
        config = yaml.safe_load(data)

    # Check if the file has been modified, and if it has, send the update.
    new_mtime = os.path.getmtime(path)
    if new_mtime != orig_mtime:
        data = {
            'config': config
        }
        res = router_request("PUT", url, json=data)
        result = res.json()
        ctx.invoke(watch, change_id=result['change_id'])

    os.remove(path) 
Example #14
Source File: device.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def shell(ctx):
    """
    Open a shell inside a chute.

    This requires you to have enabled SSH access to the device and installed
    bash inside your chute.
    """
    cmd = ["ssh", "-t", "paradrop@{}".format(ctx.obj['address']), "sudo", "docker",
            "exec", "-it", ctx.obj['chute'], "/bin/bash"]
    os.spawnvpe(os.P_WAIT, "ssh", cmd, os.environ) 
Example #15
Source File: util.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def open_yaml_editor(data, description):
    if data is None:
        data = {}

    fd, path = tempfile.mkstemp()
    os.close(fd)

    with open(path, 'w') as output:
        if len(data) > 0:
            output.write(yaml.safe_dump(data, default_flow_style=False))
        output.write("\n")
        output.write("# You are editing the configuration for the {}.\n".format(description))
        output.write("# Blank lines and lines starting with '#' will be ignored.\n")
        output.write("# Save and exit to apply changes; exit without saving to discard.\n")

    # Get modified time before calling editor.
    orig_mtime = os.path.getmtime(path)

    editor = os.environ.get("EDITOR", "vim")
    os.spawnvpe(os.P_WAIT, editor, [editor, path], os.environ)

    with open(path, 'r') as source:
        data = source.read()
        new_data = yaml.safe_load(data)

    # If result is null, convert to an empty dict before sending to router.
    if new_data is None:
        new_data = {}

    # Check if the file has been modified.
    new_mtime = os.path.getmtime(path)
    changed = (new_mtime != orig_mtime)

    os.remove(path)
    return new_data, changed 
Example #16
Source File: pydev_monkey.py    From PyDev.Debugger with Eclipse Public License 1.0 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)
    monkey_patch_os('posix_spawn', create_posix_spawn)

    if not IS_JYTHON:
        if not IS_WINDOWS:
            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 #17
Source File: posix.py    From pivy with ISC License 4 votes vote down vote up
def generate(env):
    # If os.spawnvpe() exists, we use it to spawn commands.  Otherwise
    # if the env utility exists, we use os.system() to spawn commands,
    # finally we fall back on os.fork()/os.exec().  
    #
    # os.spawnvpe() is prefered because it is the most efficient.  But
    # for Python versions without it, os.system() is prefered because it
    # is claimed that it works better with threads (i.e. -j) and is more
    # efficient than forking Python.
    #
    # NB: Other people on the scons-users mailing list have claimed that
    # os.fork()/os.exec() works better than os.system().  There may just
    # not be a default that works best for all users.

    if 'spawnvpe' in os.__dict__:
        spawn = spawnvpe_spawn
    elif env.Detect('env'):
        spawn = env_spawn
    else:
        spawn = fork_spawn

    if env.Detect('env'):
        pspawn = piped_env_spawn
    else:
        pspawn = piped_fork_spawn

    if 'ENV' not in env:
        env['ENV']        = {}
    env['ENV']['PATH']    = '/usr/local/bin:/opt/bin:/bin:/usr/bin'
    env['OBJPREFIX']      = ''
    env['OBJSUFFIX']      = '.o'
    env['SHOBJPREFIX']    = '$OBJPREFIX'
    env['SHOBJSUFFIX']    = '$OBJSUFFIX'
    env['PROGPREFIX']     = ''
    env['PROGSUFFIX']     = ''
    env['LIBPREFIX']      = 'lib'
    env['LIBSUFFIX']      = '.a'
    env['SHLIBPREFIX']    = '$LIBPREFIX'
    env['SHLIBSUFFIX']    = '.so'
    env['LIBPREFIXES']    = [ '$LIBPREFIX' ]
    env['LIBSUFFIXES']    = [ '$LIBSUFFIX', '$SHLIBSUFFIX' ]
    env['PSPAWN']         = pspawn
    env['SPAWN']          = spawn
    env['SHELL']          = 'sh'
    env['ESCAPE']         = escape
    env['TEMPFILE']       = TempFileMunge
    env['TEMPFILEPREFIX'] = '@'
    #Based on LINUX: ARG_MAX=ARG_MAX=131072 - 3000 for environment expansion
    #Note: specific platforms might rise or lower this value
    env['MAXLINELENGTH']  = 128072

    # This platform supports RPATH specifications.
    env['__RPATH'] = '$_RPATH'

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4: 
Example #18
Source File: thumbnails.py    From gprime with GNU General Public License v2.0 4 votes vote down vote up
def run_thumbnailer(mime_type, src_file, dest_file, size=SIZE_NORMAL):
    """
    This function attempts to generate a thumbnail image for a non-image.
    This includes things such as video and PDF files. This will currently
    only succeed if the GNOME environment is installed, since at this point,
    only the GNOME environment has the ability to generate thumbnails.

    :param mime_type: mime type of the source file
    :type mime_type: unicode
    :param src_file: filename of the source file
    :type src_file: unicode
    :param dest_file: destination file for the thumbnail image
    :type dest_file: unicode
    :param size: option parameters specifying the desired size of the
      thumbnail
    :type size: int
    :returns: True if the thumbnail was successfully generated
    :rtype: bool
    """
    # only try this if GCONF is present, the thumbnailer has not been
    # disabled, and if the src_file actually exists
    if GCONF and USE_THUMBNAILER and os.path.isfile(src_file):

        # find the command and enable for the associated mime types by
        # querying the gconf database
        base = '/desktop/gnome/thumbnailers/%s' % mime_type.replace('/', '@')
        cmd = __get_gconf_string(base + '/command')
        enable = __get_gconf_bool(base + '/enable')

        # if we found the command and it has been enabled, then spawn
        # of the command to build the thumbnail
        if cmd and enable:
            if size == SIZE_LARGE:
                thumbscale = THUMBSCALE_LARGE
            else:
                thumbscale = THUMBSCALE
            sublist = {
                '%s' : "%d" % int(thumbscale),
                '%u' : src_file,
                '%o' : dest_file,
                }
            cmdlist = [ sublist.get(x, x) for x in cmd.split() ]
            return os.spawnvpe(os.P_WAIT, cmdlist[0], cmdlist, os.environ) == 0
    return False

#-------------------------------------------------------------------------
#
# get_thumbnail_image
#
#------------------------------------------------------------------------- 
Example #19
Source File: smb.py    From smbwrapper with GNU General Public License v3.0 4 votes vote down vote up
def smb_rdp():
	"""
	<ip> [ user ] [ passwd/nthash ] [ enable | disable ]
	Open a Remote Desktop session using xfreerdp (Pass-the-Hash = restricted admin)
	"""

	if CONF["threaded_mode"]:
		text("[!] Function not available when running for several hosts.", 1)

	if 'enable' in sys.argv:
		set_creds(4)
		text("[*] %s Updating Registry..." % (CONF["smb_ip"]))
		winexe('reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f')
		smb_fwrule('add', 3389)
		sys.exit(0)

	if 'disable' in sys.argv:
		set_creds(4)
		text("[*] %s Updating Registry..." % (CONF["smb_ip"]))
		winexe('reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 1 /f')
		smb_fwrule('del', 3389);
		sys.exit(0)

	set_creds(3)
	check_tool('xfreerdp')

	res = screen_resolution()
	max_res = '%dx%d' % (int(res[0]), int(res[1]) - 50)

	run = []
	run.append(TOOLS['xfreerdp'])
	run.append('/size:%s' % max_res)
	run.append('/t:%s' % CONF['smb_ip'])
	run.append('/v:%s' % CONF['smb_ip'])

	if '\\' in CONF['smb_user']:
		tab = CONF['smb_user'].split('\\', 2)
		run.append('/d:%s' % tab[0])
		run.append('/u:%s' % tab[1])

	else:
		run.append('/u:%s' % CONF['smb_user'])

	if CONF['smb_pass'] == '':
		text("[!] Note: Pass-the-Hash with RDP only works for local admin accounts and under the restricted admin mode.")
		run.append('/pth:%s' % CONF['smb_hash'])
		run.append('/restricted-admin')

	else:
		run.append('/p:%s' % CONF['smb_pass'])

	# Tweak the following to suit your needs
	run.append("+clipboard")
	run.append("+home-drive")
	run.append("-decorations")
	run.append("/cert-ignore") # baaad.

	os.spawnvpe(os.P_WAIT, run[0], run, os.environ) 
Example #20
Source File: posix.py    From sitoa with Apache License 2.0 4 votes vote down vote up
def generate(env):
    # If os.spawnvpe() exists, we use it to spawn commands.  Otherwise
    # if the env utility exists, we use os.system() to spawn commands,
    # finally we fall back on os.fork()/os.exec().  
    #
    # os.spawnvpe() is prefered because it is the most efficient.  But
    # for Python versions without it, os.system() is prefered because it
    # is claimed that it works better with threads (i.e. -j) and is more
    # efficient than forking Python.
    #
    # NB: Other people on the scons-users mailing list have claimed that
    # os.fork()/os.exec() works better than os.system().  There may just
    # not be a default that works best for all users.

    if 'spawnvpe' in os.__dict__:
        spawn = spawnvpe_spawn
    elif env.Detect('env'):
        spawn = env_spawn
    else:
        spawn = fork_spawn

    if env.Detect('env'):
        pspawn = piped_env_spawn
    else:
        pspawn = piped_fork_spawn

    if 'ENV' not in env:
        env['ENV']        = {}
    env['ENV']['PATH']    = '/usr/local/bin:/opt/bin:/bin:/usr/bin'
    env['OBJPREFIX']      = ''
    env['OBJSUFFIX']      = '.o'
    env['SHOBJPREFIX']    = '$OBJPREFIX'
    env['SHOBJSUFFIX']    = '$OBJSUFFIX'
    env['PROGPREFIX']     = ''
    env['PROGSUFFIX']     = ''
    env['LIBPREFIX']      = 'lib'
    env['LIBSUFFIX']      = '.a'
    env['SHLIBPREFIX']    = '$LIBPREFIX'
    env['SHLIBSUFFIX']    = '.so'
    env['LIBPREFIXES']    = [ '$LIBPREFIX' ]
    env['LIBSUFFIXES']    = [ '$LIBSUFFIX', '$SHLIBSUFFIX' ]
    env['PSPAWN']         = pspawn
    env['SPAWN']          = spawn
    env['SHELL']          = 'sh'
    env['ESCAPE']         = escape
    env['TEMPFILE']       = TempFileMunge
    env['TEMPFILEPREFIX'] = '@'
    #Based on LINUX: ARG_MAX=ARG_MAX=131072 - 3000 for environment expansion
    #Note: specific platforms might rise or lower this value
    env['MAXLINELENGTH']  = 128072

    # This platform supports RPATH specifications.
    env['__RPATH'] = '$_RPATH'

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4: 
Example #21
Source File: device.py    From Paradrop with Apache License 2.0 4 votes vote down vote up
def edit_environment(ctx):
    """
    Interactively edit the chute environment vairables.
    """
    req = router_request("GET", ctx.obj['chute_url'], dump=False)
    info = req.json()
    old_environ = info.get('environment', None)
    if old_environ is None:
        old_environ = {}

    fd, path = tempfile.mkstemp()
    os.close(fd)

    with open(path, 'w') as output:
        if len(old_environ) > 0:
            output.write(yaml.safe_dump(old_environ, default_flow_style=False))
        output.write("\n")
        output.write("# You are editing the environment variables for the chute {}.\n"
                .format(ctx.obj['chute']))
        output.write("# Blank lines and lines starting with '#' will be ignored.\n")
        output.write("# Put each variable on a line with a colon separator, e.g. 'VARIABLE: VALUE'\n")
        output.write("# Save and exit to apply changes; exit without saving to discard.\n")

    # Get modified time before calling editor.
    orig_mtime = os.path.getmtime(path)

    editor = os.environ.get("EDITOR", "vim")
    os.spawnvpe(os.P_WAIT, editor, [editor, path], os.environ)

    with open(path, 'r') as source:
        data = source.read()
        new_environ = yaml.safe_load(data)

    # If result is null, convert to an empty dict before sending to router.
    if new_environ is None:
        new_environ = {}

    # Check if the file has been modified, and if it has, send the update.
    new_mtime = os.path.getmtime(path)
    if new_mtime != orig_mtime:
        data = {
            'environment': new_environ
        }
        url = ctx.obj['chute_url'] + "/restart"
        res = router_request("POST", url, json=data)
        data = res.json()
        ctx.invoke(watch, change_id=data['change_id'])

    os.remove(path) 
Example #22
Source File: pydev_monkey.py    From filmkodi with Apache License 2.0 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)