Python os 模块,execvp() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.execvp()

项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def run_bg(cmd, debug=False, cwd=''):
    # make sure 'cmd' is a list of strings
    if type(cmd) in [str, unicode]:
        cmd = [c for c in cmd.split() if c != '']
    if debug:
        sys.stderr.write(' '.join(cmd)+'\n')
        sys.stderr.flush()

    try:
        ( child_pid, child_fd ) = pty.fork()
    except OSError as e:
        raise RunError(cmd, None, message='pty.fork() failed: %s' % str(e))
    if child_pid == 0:
        try:
            if cwd != '':
                os.chdir(cwd)
            os.execvp(cmd[0], cmd)
        except Exception, e:
            raise RunError(cmd, None, 'os.execvp() failed: %s' % str(e))
    else:
        return child_pid, child_fd
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def run_bg(cmd, debug=False, cwd=''):
    # make sure 'cmd' is a list of strings
    if type(cmd) in [str, unicode]:
        cmd = [c for c in cmd.split() if c != '']
    if debug:
        sys.stderr.write(' '.join(cmd)+'\n')
        sys.stderr.flush()

    try:
        ( child_pid, child_fd ) = pty.fork()
    except OSError as e:
        raise RunError(cmd, None, message='pty.fork() failed: %s' % str(e))
    if child_pid == 0:
        try:
            if cwd != '':
                os.chdir(cwd)
            os.execvp(cmd[0], cmd)
        except Exception, e:
            raise RunError(cmd, None, 'os.execvp() failed: %s' % str(e))
    else:
        return child_pid, child_fd
项目:circleci-demo-python-flask    作者:CircleCI-Public    | 项目源码 | 文件源码
def test(coverage=False):
    """Run the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        import sys
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    import xmlrunner
    tests = unittest.TestLoader().discover('tests')
    # run tests with unittest-xml-reporting and output to $CIRCLE_TEST_REPORTS on CircleCI or test-reports locally
    xmlrunner.XMLTestRunner(output=os.environ.get('CIRCLE_TEST_REPORTS','test-reports')).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'tmp/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()
项目:rubber-docker    作者:Fewbytes    | 项目源码 | 文件源码
def contain(command, image_name, image_dir, container_id, container_dir):
    linux.unshare(linux.CLONE_NEWNS)  # create a new mount namespace

    linux.mount(None, '/', None, linux.MS_PRIVATE | linux.MS_REC, None)

    new_root = create_container_root(
        image_name, image_dir, container_id, container_dir)
    print('Created a new root fs for our container: {}'.format(new_root))

    _create_mounts(new_root)

    old_root = os.path.join(new_root, 'old_root')
    os.makedirs(old_root)
    linux.pivot_root(new_root, old_root)

    os.chdir('/')

    linux.umount2('/old_root', linux.MNT_DETACH)  # umount old root
    os.rmdir('/old_root') # rmdir the old_root dir
    os.execvp(command[0], command)
项目:rubber-docker    作者:Fewbytes    | 项目源码 | 文件源码
def contain(command, image_name, image_dir, container_id, container_dir):
    linux.unshare(linux.CLONE_NEWNS)  # create a new mount namespace
    # TODO: switch to a new UTS namespace, change hostname to container_id
    # HINT: use linux.sethostname()

    linux.mount(None, '/', None, linux.MS_PRIVATE | linux.MS_REC, None)

    new_root = create_container_root(
        image_name, image_dir, container_id, container_dir)
    print('Created a new root fs for our container: {}'.format(new_root))

    _create_mounts(new_root)

    old_root = os.path.join(new_root, 'old_root')
    os.makedirs(old_root)
    linux.pivot_root(new_root, old_root)

    os.chdir('/')

    linux.umount2('/old_root', linux.MNT_DETACH)  # umount old root
    os.rmdir('/old_root') # rmdir the old_root dir

    os.execvp(command[0], command)
项目:rubber-docker    作者:Fewbytes    | 项目源码 | 文件源码
def contain(command, image_name, image_dir, container_id, container_dir):
    linux.sethostname(container_id)  # change hostname to container_id

    linux.mount(None, '/', None, linux.MS_PRIVATE | linux.MS_REC, None)

    new_root = create_container_root(
        image_name, image_dir, container_id, container_dir)
    print('Created a new root fs for our container: {}'.format(new_root))

    _create_mounts(new_root)

    old_root = os.path.join(new_root, 'old_root')
    os.makedirs(old_root)
    linux.pivot_root(new_root, old_root)

    os.chdir('/')

    linux.umount2('/old_root', linux.MNT_DETACH)  # umount old root
    os.rmdir('/old_root') # rmdir the old_root dir

    os.execvp(command[0], command)
项目:rubber-docker    作者:Fewbytes    | 项目源码 | 文件源码
def contain(command, image_name, image_dir, container_id, container_dir):
    linux.unshare(linux.CLONE_NEWNS)  # create a new mount namespace
    linux.unshare(linux.CLONE_NEWUTS)  # switch to a new UTS namespace
    linux.sethostname(container_id)  # change hostname to container_id

    linux.mount(None, '/', None, linux.MS_PRIVATE | linux.MS_REC, None)

    new_root = create_container_root(
        image_name, image_dir, container_id, container_dir)
    print('Created a new root fs for our container: {}'.format(new_root))

    _create_mounts(new_root)

    old_root = os.path.join(new_root, 'old_root')
    os.makedirs(old_root)
    linux.pivot_root(new_root, old_root)

    os.chdir('/')

    linux.umount2('/old_root', linux.MNT_DETACH)  # umount old root
    os.rmdir('/old_root') # rmdir the old_root dir

    os.execvp(command[0], command)
项目:mitogen    作者:dw    | 项目源码 | 文件源码
def create_child(*args):
    parentfp, childfp = socket.socketpair()
    pid = os.fork()
    if not pid:
        mitogen.core.set_block(childfp.fileno())
        os.dup2(childfp.fileno(), 0)
        os.dup2(childfp.fileno(), 1)
        childfp.close()
        parentfp.close()
        os.execvp(args[0], args)

    childfp.close()
    # Decouple the socket from the lifetime of the Python socket object.
    fd = os.dup(parentfp.fileno())
    parentfp.close()

    LOG.debug('create_child() child %d fd %d, parent %d, cmd: %s',
              pid, fd, os.getpid(), Argv(args))
    return pid, fd
项目:mitogen    作者:dw    | 项目源码 | 文件源码
def tty_create_child(*args):
    master_fd, slave_fd = os.openpty()
    disable_echo(master_fd)
    disable_echo(slave_fd)

    pid = os.fork()
    if not pid:
        mitogen.core.set_block(slave_fd)
        os.dup2(slave_fd, 0)
        os.dup2(slave_fd, 1)
        os.dup2(slave_fd, 2)
        close_nonstandard_fds()
        os.setsid()
        os.close(os.open(os.ttyname(1), os.O_RDWR))
        os.execvp(args[0], args)

    os.close(slave_fd)
    LOG.debug('tty_create_child() child %d fd %d, parent %d, cmd: %s',
              pid, master_fd, os.getpid(), Argv(args))
    return pid, master_fd
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def test(coverage=False):
    """Run the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        import sys
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'tmp/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()
项目:witchcraft    作者:llllllllll    | 项目源码 | 文件源码
def play(conn, query):
    """Launch mpv with the results of the query.

    Parameters
    ----------
    conn : sa.engine.Connection
        The connection to the metadata database.
    query : string
        The witchcraft ql query to run against the database.

    Notes
    -----
    This function never returns.
    """
    select, extra_args = ql.compile(query)
    paths = [p[0] for p in conn.execute(select).fetchall()]

    if not paths:
        # nothing to play, mpv doesn't want an empty path list
        return

    os.execvp('mpv', ['mpv', '--no-video'] + extra_args + paths)
项目:Plog    作者:thundernet8    | 项目源码 | 文件源码
def test(coverage=False):
    """
    ??
    :param coverage ????????
    :return:
    """
    if coverage and not os.environ.get('PG_COVERAGE'):
        import sys
        os.environ['PG_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'tests/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()
项目:PilosusBot    作者:pilosus    | 项目源码 | 文件源码
def test(coverage=False):
    """Run the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        import sys
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'tmp/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()
项目:fritzchecksum    作者:mementum    | 项目源码 | 文件源码
def RunAsAdminUnixLike():
    # FIXME ... what happens if "frozen"
    script = os.path.abspath(sys.argv[0])

    params = [sys.executable]
    if sys.executable != script:
        params.append(script)
        # CHECK Seems logic to always extend
        params.extend(sys.argv[1:])

    # FIXME ... execute the command directly
    try:
        os.execvp('sudo', params)
    except Exception, e:
        return False, str(e)

    # If execvp was ok ... this will never be reached
    return True, None
项目:layercake    作者:bcsaller    | 项目源码 | 文件源码
def main():
    loop = asyncio.get_event_loop()
    loop.set_debug(False)
    options = setup()
    configure_logging(options.log_level)
    config = configure_from_file(options.conf)
    config.update(configure_from_env())
    r = reactive.Reactive(config, loop=loop)
    r.find_rules()
    r.find_schemas()
    try:
        config_task = loop.create_task(r())
        loop.run_until_complete(config_task)
        if config_task.result() is True:
            # Fork/Exec cmd
            log.info("Container Configured")
            log.info("Exec {}".format(options.cmd))
            os.execvp(options.cmd[0], options.cmd)
        else:
            log.critical("Unable to configure container, see log or run with -l DEBUG")
    finally:
        loop.close()
项目:SweetHeart    作者:haojunyu    | 项目源码 | 文件源码
def test(coverage=False):
  # run the test unit
  if coverage and not os.environ.get('FLASK_COVERAGE'):
    import sys
    os.environ['FLASK_COVERAGE'] = '1'
    os.execvp(sys.executable, [sys.executable] + sys.argv)
  import unittest
  tests = unittest.TestLoader().discover('tests')
  unittest.TextTestRunner(verbosity=2).run(tests)
  if COV:
    COV.stop()
    COV.save()
    print('Coverage Summary:')
    COV.report()
    basedir = os.path.abspath(os.path.dirname(__file__))
    covdir = os.path.join(basedir, 'tmp/coverage')
    COV.html_report(directory=covdir)
    print('HTML version: file://%s/index.html' % covdir)
    COV.erase()
项目:device-cloud-python    作者:Wind-River    | 项目源码 | 文件源码
def execl(*args):
    """
    Replaces the current process with a new instance of the specified
    executable. This function will only return if there is an issue starting the
    new instance, in which case it will return false. Otherwise, it will not
    return.
    """
    retval = EXECUTION_FAILURE

    if POSIX:
        os.execvp(args[0], args)
    elif WIN32:
        os.execvp(sys.executable, args)
    else:
        retval = NOT_SUPPORTED

    return retval
项目:Kali-Pi    作者:Re4son    | 项目源码 | 文件源码
def screen_on(retPage, backlightControl):

    if os.environ["KPPIN"] != "1":
        launch_bg=os.environ["MENUDIR"] + "launch-bg.sh"
        process = subprocess.call(launch_bg, shell=True)

    pygame.quit()
    if backlightControl == "3.5r":
        process = subprocess.call("echo '1' > /sys/class/backlight/soc\:backlight/brightness", shell=True)
    elif backlightControl == "4dpi-24":
        process = subprocess.call("echo '80' > /sys/class/backlight/24-hat-pwm/brightness", shell=True)
    else:
        backlight = GPIO.PWM(18, 1023)
        backlight.start(100)
        GPIO.cleanup()
    if os.environ["KPPIN"] == "1":
        page=os.environ["MENUDIR"] + "menu-pin.py"
        args = [page, retPage]
    else:
        page=os.environ["MENUDIR"] + retPage
        args = [page]

    os.execvp("python", ["python"] + args)

# Turn screen off
项目:uwsgiconf    作者:idlesign    | 项目源码 | 文件源码
def spawn(self, filepath, configuration_alias, replace=False):
        """Spawns uWSGI using the given configuration module.

        :param str|unicode filepath:

        :param str|unicode configuration_alias:

        :param bool replace: Whether a new process should replace current one.

        """
        # Pass --conf as an argument to have a chance to use
        # touch reloading form .py configuration file change.
        args = ['uwsgi', '--ini', 'exec://%s %s --conf %s' % (self.binary_python, filepath, configuration_alias)]

        if replace:
            return os.execvp('uwsgi', args)

        return os.spawnvp(os.P_NOWAIT, 'uwsgi', args)
项目:flask-api-boilerplate    作者:mikaelm1    | 项目源码 | 文件源码
def cli(cov):
    """
    Runs all the tests.
    :param cov: bool Set to True to get coverage report
    """
    if cov and not os.environ.get('FLASK_COVERAGE'):
        import sys
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    tests = unittest.TestLoader().discover('app.tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname('__file__'))
        covdir = os.path.join(basedir, 'tmp/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()
项目:aegea    作者:kislyuk    | 项目源码 | 文件源码
def ssh(args):
    prefix, at, name = args.name.rpartition("@")
    instance = resources.ec2.Instance(resolve_instance_id(name))
    if not instance.public_dns_name:
        msg = "Unable to resolve public DNS name for {} (state: {})"
        raise AegeaException(msg.format(instance, getattr(instance, "state", {}).get("Name")))

    tags = {tag["Key"]: tag["Value"] for tag in instance.tags or []}
    ssh_host_key = tags.get("SSHHostPublicKeyPart1", "") + tags.get("SSHHostPublicKeyPart2", "")
    if ssh_host_key:
        # FIXME: this results in duplicates.
        # Use paramiko to detect if the key is already listed and not insert it then (or only insert if different)
        add_ssh_host_key_to_known_hosts(instance.public_dns_name + " " + ssh_host_key + "\n")
    ssh_args = ["ssh", prefix + at + instance.public_dns_name]
    if not (prefix or at):
        try:
            ssh_args += ["-l", resources.iam.CurrentUser().user.name]
        except:
            logger.info("Unable to determine IAM username, using local username")
    os.execvp("ssh", ssh_args + args.ssh_args)
项目:url-shortener-api    作者:mabbie    | 项目源码 | 文件源码
def test(coverage=False):
    """Runs the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        import sys
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'tmp/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()
项目:treadmill    作者:Morgan-Stanley    | 项目源码 | 文件源码
def _wait_for_ssh(queue, ssh, command, timeout=1, attempts=40):
    """Wait until a successful connection to the ssh endpoint can be made."""
    try:
        host, port = queue.get(timeout=timeout * attempts)
    except g_queue.Empty:
        cli.bad_exit("No SSH endpoint found.")

    for _ in six.moves.range(attempts):
        _LOGGER.debug('Checking SSH endpoint %s:%s', host, port)
        if checkout.connect(host, port):
            run_ssh(host, port, ssh, list(command))
            break  # if run_ssh doesn't end with os.execvp()...

        try:
            host, port = queue.get(timeout=timeout)
            queue.task_done()
        except g_queue.Empty:
            pass

    # Either all the connection attempts failed or we're after run_ssh
    # (not resulting in os.execvp) so let's "clear the queue" so the thread
    # can join
    queue.task_done()
项目:treadmill    作者:Morgan-Stanley    | 项目源码 | 文件源码
def sane_execvp(filename, args, close_fds=True, restore_signals=True):
    """Execute a new program with sanitized environment.
    """
    def _restore_signals():
        """Reset the default behavior to all signals.
        """
        for i in _SIGNALS:
            signal.signal(i, signal.SIG_DFL)

    def _close_fds():
        """Close all file descriptors except 0, 1, 2.
        """
        os.closerange(3, subprocess.MAXFD)

    if close_fds:
        _close_fds()
    if restore_signals:
        _restore_signals()
    os.execvp(filename, args)
项目:cci-demo-flask    作者:circleci    | 项目源码 | 文件源码
def test(coverage=False):
    """Run the unit tests."""
    import sys
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    import xmlrunner
    tests = unittest.TestLoader().discover('tests')
    results = xmlrunner.XMLTestRunner(output='test-reports').run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'test-reports/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()
    if (len(results.failures) > 0 or len(results.errors) > 0):
        sys.exit(1)
项目:jack    作者:jack-cli-cd-ripper    | 项目源码 | 文件源码
def start_new_process(args, nice_value=0):
    "start a new process in a pty and renice it"
    data = {}
    data['start_time'] = time.time()
    pid, master_fd = pty.fork()
    if pid == CHILD:
        default_signals()
        if nice_value:
            os.nice(nice_value)
        os.execvp(args[0], [a.encode(cf['_charset'], "replace") for a in args])
    else:
        data['pid'] = pid
        if os.uname()[0] == "Linux":
            fcntl.fcntl(master_fd, F_SETFL, O_NONBLOCK)
        data['fd'] = master_fd
        data['file'] = os.fdopen(master_fd)
        data['cmd'] = args
        data['buf'] = ""
        data['otf'] = 0
        data['percent'] = 0
        data['elapsed'] = 0
        return data
项目:project    作者:Junctionzc    | 项目源码 | 文件源码
def test(coverage = False):
    """Run the unit tests"""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        import sys
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity = 2).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'tmp/coverage')
        COV.html_report(directory = covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()
项目:alicloud-duplicity    作者:aliyun    | 项目源码 | 文件源码
def _as_child(self, process, gnupg_commands, args):
        """Stuff run after forking in child"""
        # child
        for std in _stds:
            p = process._pipes[std]
            os.dup2(p.child, getattr(sys, "__%s__" % std).fileno())

        for k, p in process._pipes.items():
            if p.direct and k not in _stds:
                # we want the fh to stay open after execing
                fcntl.fcntl(p.child, fcntl.F_SETFD, 0)

        fd_args = []

        for k, p in process._pipes.items():
            # set command-line options for non-standard fds
            if k not in _stds:
                fd_args.extend([_fd_options[k], "%d" % p.child])

            if not p.direct:
                os.close(p.parent)

        command = [self.call] + fd_args + self.options.get_args() + gnupg_commands + args

        os.execvp(command[0], command)
项目:Graduation_design    作者:mr-betterman    | 项目源码 | 文件源码
def test(coverage=False):
    """Run the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        import sys
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'tmp/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()
项目:ava-capture    作者:electronicarts    | 项目源码 | 文件源码
def loop_forever(self):
        try:
            while 1:
                try:
                    self.status_changed = False
                    self.phone_home()

                except Exception as e:
                    self.logger.error('Failed to contact server. %s' % e)

                if self.need_restart and not self.container.running_jobs and not self.container.finished_jobs:
                    print 'Restarting...'
                    # End current process and launch a new one with the same command line parameters
                    #os.execvp('python.exe', ['python.exe'] + sys.argv)
                    exit(3)

                if not self.status_changed:
                    self.cpu_percent = psutil.cpu_percent(interval=self.PHONEHOME_DELAY)

        except KeyboardInterrupt:
            pass
        finally:
            print 'Exiting...'
            self.notify_exit()
项目:gyp    作者:electron    | 项目源码 | 文件源码
def __init__(self, cmd, bufsize=-1):
                    p2cread, p2cwrite = os.pipe()
                    c2pread, c2pwrite = os.pipe()
                    self.pid = os.fork()
                    if self.pid == 0:
                        # Child
                        os.dup2(p2cread, 0)
                        os.dup2(c2pwrite, 1)
                        os.dup2(c2pwrite, 2)
                        for i in range(3, popen2.MAXFD):
                            try:
                                os.close(i)
                            except: pass
                        try:
                            os.execvp(cmd[0], cmd)
                        finally:
                            os._exit(1)
                        # Shouldn't come here, I guess
                        os._exit(1)
                    os.close(p2cread)
                    self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
                    os.close(c2pwrite)
                    self.fromchild = os.fdopen(c2pread, 'r', bufsize)
                    popen2._active.append(self)
项目:flask-blog    作者:zhuwei05    | 项目源码 | 文件源码
def test(coverage=False):
    """Run the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        import sys
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'tmp/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()

# source code profile
项目:blog    作者:hukaixuan    | 项目源码 | 文件源码
def test(coverage=False):
    """Run the unit tests"""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        import sys
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'tmp/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()
项目:rest_api    作者:opentargets    | 项目源码 | 文件源码
def test(coverage=False):
    """Run the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'tmp/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()
项目:livetv_mining    作者:taogeT    | 项目源码 | 文件源码
def test(coverage=False):
    """Run the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    testresult = TextTestRunner(verbosity=2).run(TestLoader().discover('tests'))
    if cov:
        cov.stop()
        cov.save()
        print('Coverage Summary:')
        cov.report()
        covdir = app.config.get('COVERAGE_DIRECTORY', '')
        if covdir:
            covdir = os.path.join(covdir, datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S'))
            if not os.path.exists(covdir):
                os.makedirs(covdir)
            cov.html_report(directory=covdir)
            print('Coverage HTML version: file://{}/index.html'.format(covdir))
        cov.erase()
    if len(testresult.failures) + len(testresult.errors) > 0:
        sys.exit(1)
项目:python-zulip-api    作者:zulip    | 项目源码 | 文件源码
def maybe_restart_mirroring_script():
    # type: () -> None
    if os.stat(os.path.join(options.stamp_path, "stamps", "restart_stamp")).st_mtime > start_time or \
            ((options.user == "tabbott" or options.user == "tabbott/extra") and
             os.stat(os.path.join(options.stamp_path, "stamps", "tabbott_stamp")).st_mtime > start_time):
        logger.warning("")
        logger.warning("zephyr mirroring script has been updated; restarting...")
        maybe_kill_child()
        try:
            zephyr._z.cancelSubs()
        except IOError:
            # We don't care whether we failed to cancel subs properly, but we should log it
            logger.exception("")
        while True:
            try:
                os.execvp(os.path.abspath(__file__), sys.argv)
            except Exception:
                logger.exception("Error restarting mirroring script; trying again... Traceback:")
                time.sleep(1)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def _run_child(self, cmd):
        if isinstance(cmd, basestring):
            cmd = ['/bin/sh', '-c', cmd]
        os.closerange(3, MAXFD)
        try:
            os.execvp(cmd[0], cmd)
        finally:
            os._exit(1)
项目:mongodb-monitoring    作者:jruaux    | 项目源码 | 文件源码
def _execute(path, argv, environ):
            if environ is None:
                os.execvp(path, argv)
            else:
                os.execvpe(path, argv, environ)
            return

    # endregion
项目:Splunk_CBER_App    作者:MHaggis    | 项目源码 | 文件源码
def _execute(path, argv, environ):
            if environ is None:
                os.execvp(path, argv)
            else:
                os.execvpe(path, argv, environ)
            return

    # endregion
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _run_child(self, cmd):
        if isinstance(cmd, basestring):
            cmd = ['/bin/sh', '-c', cmd]
        os.closerange(3, MAXFD)
        try:
            os.execvp(cmd[0], cmd)
        finally:
            os._exit(1)
项目:meteos    作者:openstack    | 项目源码 | 文件源码
def main():
    """Parse options and call the appropriate class/method."""
    CONF.register_cli_opt(category_opt)
    script_name = sys.argv[0]
    if len(sys.argv) < 2:
        print(_("\nOpenStack meteos version: %(version)s\n") %
              {'version': version.version_string()})
        print(script_name + " category action [<args>]")
        print(_("Available categories:"))
        for category in CATEGORIES:
            print("\t%s" % category)
        sys.exit(2)

    try:
        log.register_options(CONF)
        CONF(sys.argv[1:], project='meteos',
             version=version.version_string())
        log.setup(CONF, "meteos")
    except cfg.ConfigFilesNotFoundError:
        cfgfile = CONF.config_file[-1] if CONF.config_file else None
        if cfgfile and not os.access(cfgfile, os.R_OK):
            st = os.stat(cfgfile)
            print(_("Could not read %s. Re-running with sudo") % cfgfile)
            try:
                os.execvp('sudo', ['sudo', '-u', '#%s' % st.st_uid] + sys.argv)
            except Exception:
                print(_('sudo failed, continuing as if nothing happened'))

        print(_('Please re-run meteos-manage as root.'))
        sys.exit(2)

    fn = CONF.category.action_fn

    fn_args = fetch_func_args(fn)
    fn(*fn_args)
项目:rubber-docker    作者:Fewbytes    | 项目源码 | 文件源码
def contain(command, image_name, image_dir, container_id, container_dir):
    # TODO: would you like to do something before chrooting?
    # print('Created a new root fs for our container: {}'.format(new_root))

    # TODO: chroot into new_root
    # TODO: something after chrooting?

    os.execvp(command[0], command)
项目:rubber-docker    作者:Fewbytes    | 项目源码 | 文件源码
def contain(command, image_name, image_dir, container_id, container_dir):
    linux.unshare(linux.CLONE_NEWNS)  # create a new mount namespace

    # TODO: we added MS_REC here. wanna guess why?
    linux.mount(None, '/', None, linux.MS_PRIVATE | linux.MS_REC, None)

    new_root = create_container_root(
        image_name, image_dir, container_id, container_dir)
    print('Created a new root fs for our container: {}'.format(new_root))

    # Create mounts (/proc, /sys, /dev) under new_root
    linux.mount('proc', os.path.join(new_root, 'proc'), 'proc', 0, '')
    linux.mount('sysfs', os.path.join(new_root, 'sys'), 'sysfs', 0, '')
    linux.mount('tmpfs', os.path.join(new_root, 'dev'), 'tmpfs',
                linux.MS_NOSUID | linux.MS_STRICTATIME, 'mode=755')

    # Add some basic devices
    devpts_path = os.path.join(new_root, 'dev', 'pts')
    if not os.path.exists(devpts_path):
        os.makedirs(devpts_path)
        linux.mount('devpts', devpts_path, 'devpts', 0, '')

    makedev(os.path.join(new_root, 'dev'))

    os.chroot(new_root)  # TODO: replace with pivot_root

    os.chdir('/')

    # TODO: umount2 old root (HINT: see MNT_DETACH in man 2 umount)

    os.execvp(command[0], command)
项目:rubber-docker    作者:Fewbytes    | 项目源码 | 文件源码
def contain(command, image_name, image_dir, container_id, container_dir):
    new_root = create_container_root(
        image_name, image_dir, container_id, container_dir)
    print('Created a new root fs for our container: {}'.format(new_root))

    # TODO: time to say goodbye to the old mount namespace,
    #       see "man 2 unshare" to get some help
    #   HINT 1: there is no os.unshare(), time to use the linux module we made
    #           just for you!
    #   HINT 2: the linux module includes both functions and constants!
    #           e.g. linux.CLONE_NEWNS

    # TODO: remember shared subtrees?
    # (https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt)
    # Make / a private mount to avoid littering our host mount table.

    # Create mounts (/proc, /sys, /dev) under new_root
    linux.mount('proc', os.path.join(new_root, 'proc'), 'proc', 0, '')
    linux.mount('sysfs', os.path.join(new_root, 'sys'), 'sysfs', 0, '')
    linux.mount('tmpfs', os.path.join(new_root, 'dev'), 'tmpfs',
                linux.MS_NOSUID | linux.MS_STRICTATIME, 'mode=755')
    # Add some basic devices
    devpts_path = os.path.join(new_root, 'dev', 'pts')
    if not os.path.exists(devpts_path):
        os.makedirs(devpts_path)
        linux.mount('devpts', devpts_path, 'devpts', 0, '')
    for i, dev in enumerate(['stdin', 'stdout', 'stderr']):
        os.symlink('/proc/self/fd/%d' % i, os.path.join(new_root, 'dev', dev))

    # TODO: add more devices (e.g. null, zero, random, urandom) using os.mknod.

    os.chroot(new_root)

    os.chdir('/')

    os.execvp(command[0], command)
项目:rubber-docker    作者:Fewbytes    | 项目源码 | 文件源码
def contain(command, image_name, image_dir, container_id, container_dir,
            cpu_shares, memory, memory_swap):
    _setup_cpu_cgroup(container_id, cpu_shares)

    # TODO: similarly to the CPU cgorup, add Memory cgroup support here
    #       setup memory -> memory.limit_in_bytes,
    #       memory_swap -> memory.memsw.limit_in_bytes if they are not None

    linux.sethostname(container_id)  # Change hostname to container_id

    linux.mount(None, '/', None, linux.MS_PRIVATE | linux.MS_REC, None)

    new_root = create_container_root(
        image_name, image_dir, container_id, container_dir)
    print('Created a new root fs for our container: {}'.format(new_root))

    _create_mounts(new_root)

    old_root = os.path.join(new_root, 'old_root')
    os.makedirs(old_root)
    linux.pivot_root(new_root, old_root)

    os.chdir('/')

    linux.umount2('/old_root', linux.MNT_DETACH)  # umount old root
    os.rmdir('/old_root') # rmdir the old_root dir

    os.execvp(command[0], command)
项目:rubber-docker    作者:Fewbytes    | 项目源码 | 文件源码
def contain(command, image_name, image_dir, container_id, container_dir,
            cpu_shares):
    # TODO: insert the container to a new cpu cgroup named:
    #       'rubber_docker/container_id'

    # TODO: if (cpu_shares != 0)  => set the 'cpu.shares' in our cpu cgroup

    linux.sethostname(container_id)  # change hostname to container_id

    linux.mount(None, '/', None, linux.MS_PRIVATE | linux.MS_REC, None)

    new_root = create_container_root(
        image_name, image_dir, container_id, container_dir)
    print('Created a new root fs for our container: {}'.format(new_root))

    _create_mounts(new_root)

    old_root = os.path.join(new_root, 'old_root')
    os.makedirs(old_root)
    linux.pivot_root(new_root, old_root)

    os.chdir('/')

    linux.umount2('/old_root', linux.MNT_DETACH)  # umount old root
    os.rmdir('/old_root') # rmdir the old_root dir

    os.execvp(command[0], command)
项目:dockwrkr    作者:turbulent    | 项目源码 | 文件源码
def run(container, containerArgs, config, basePath=None, networks=None):
    params = readCreateParameters(
        container, config, basePath=basePath, networks=networks, asList=True)
    if params.isFail():
        return params
    try:
        cmd = [DOCKER_CLIENT, "run", "--rm", "--interactive", "--tty"] + params.getOK() + containerArgs
        logger.debug("EXECVP - %s" % subprocess.list2cmdline(cmd))
        os.execvp(DOCKER_CLIENT, cmd)
    except Exception as ex:
        return Fail(ex)
项目:raiden    作者:raiden-network    | 项目源码 | 文件源码
def main(eth_nodes, seed, raiden_executable, raiden_args):
    if ETH_RPC_ENDPOINT_ARG in raiden_args:
        raise RuntimeError("Argument conflict: {}".format(ETH_RPC_ENDPOINT_ARG))
    eth_nodes = eth_nodes.split(",")
    offset = sum(ord(c) for c in seed) % len(eth_nodes)
    target_eth_node = eth_nodes[offset]
    raiden_args = [raiden_executable] + list(raiden_args) + [ETH_RPC_ENDPOINT_ARG, target_eth_node]
    print(" ".join(raiden_args))
    # Ensure print is flushed - exec could swallow it
    sys.stdout.flush()
    os.execvp(raiden_args[0], raiden_args)
项目:runtests    作者:bccp    | 项目源码 | 文件源码
def _launch_mpisub(self, args, site_dir):

        # extract the mpirun run argument
        parser = ArgumentParser(add_help=False)
        # these values are ignored. This is a hack to filter out unused argv.
        parser.add_argument("--single", default=False, action='store_true')
        parser.add_argument("--mpirun", default=None)
        _args, additional = parser.parse_known_args()

        # now call with mpirun
        mpirun = args.mpirun.split()
        cmdargs = [sys.executable, sys.argv[0], '--mpisub']

        if site_dir is not None:
            # mpi subs will use system version of package
            cmdargs.extend(['--mpisub-site-dir=' + site_dir])

        # workaround the strict openmpi oversubscribe policy
        # the parameter is found from
        # https://github.com/open-mpi/ompi/blob/ba47f738871ff06b8e8f34b8e18282b9fe479586/orte/mca/rmaps/base/rmaps_base_frame.c#L169
        # see the faq:
        #   https://www.open-mpi.org/faq/?category=running#oversubscribing
        os.environ['OMPI_MCA_rmaps_base_oversubscribe'] = '1'

        os.execvp(mpirun[0], mpirun + cmdargs + additional)

        # if we are here os.execvp has failed; bail
        sys.exit(1)
项目:python-ibmdb-django    作者:ibmdb    | 项目源码 | 文件源码
def runshell( self ):
        if ( djangoVersion[0:2] <= ( 1, 0 ) ):
            from django.conf import settings
            database_name = settings.DATABASE_NAME
            database_user = settings.DATABASE_USER
            database_password = settings.DATABASE_PASSWORD
        elif ( djangoVersion[0:2] <= ( 1, 1 ) ):
            settings_dict = self.connection.settings_dict
            database_name = settings_dict['DATABASE_NAME']
            database_user = settings_dict['DATABASE_USER']
            database_password = settings_dict['DATABASE_PASSWORD']
        else:
            settings_dict = self.connection.settings_dict
            database_name = settings_dict['NAME']
            database_user = settings_dict['USER']
            database_password = settings_dict['PASSWORD']

        cmdArgs = ["db2"]

        if ( os.name == 'nt' ):
            cmdArgs += ["db2 connect to %s" % database_name]
        else:
            cmdArgs += ["connect to %s" % database_name]
        if sys.version_info.major >= 3:
            basestring = str
        else:
            basestring = basestring

        if ( isinstance( database_user, basestring ) and 
            ( database_user != '' ) ):
            cmdArgs += ["user %s" % database_user]

            if ( isinstance( database_password, basestring ) and 
                ( database_password != '' ) ):
                cmdArgs += ["using %s" % database_password]

        # db2cmd is the shell which is required to run db2 commands on windows.
        if ( os.name == 'nt' ):
            os.execvp( 'db2cmd', cmdArgs )
        else:
            os.execvp( 'db2', cmdArgs )