当前位置: 首页>>代码示例>>Python>>正文


Python os.EX_OK属性代码示例

本文整理汇总了Python中os.EX_OK属性的典型用法代码示例。如果您正苦于以下问题:Python os.EX_OK属性的具体用法?Python os.EX_OK怎么用?Python os.EX_OK使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在os的用法示例。


在下文中一共展示了os.EX_OK属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: filter

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def filter(args):
    filter_args = dict(logGroupName=args.log_group)
    if args.log_stream:
        filter_args.update(logStreamNames=[args.log_stream])
    if args.pattern:
        filter_args.update(filterPattern=args.pattern)
    if args.start_time:
        filter_args.update(startTime=int(timestamp(args.start_time) * 1000))
    if args.end_time:
        filter_args.update(endTime=int(timestamp(args.end_time) * 1000))
    num_results = 0
    while True:
        for event in paginate(clients.logs.get_paginator("filter_log_events"), **filter_args):
            if "timestamp" not in event or "message" not in event:
                continue
            print_log_event(event)
            num_results += 1
        if args.follow:
            time.sleep(1)
        else:
            return SystemExit(os.EX_OK if num_results > 0 else os.EX_DATAERR) 
开发者ID:kislyuk,项目名称:aegea,代码行数:23,代码来源:logs.py

示例2: call

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def call(self, cmd, **kwargs):
        print('Running "{}"'.format(cmd), file=sys.stderr)
        expect = kwargs.pop("expect", [dict(return_codes=[os.EX_OK], stdout=None, stderr=None)])
        process = subprocess.Popen(cmd, stdin=kwargs.get("stdin", subprocess.PIPE), stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE, **kwargs)
        out, err = process.communicate()
        return_code = process.poll()
        out = out.decode(sys.stdin.encoding)
        err = err.decode(sys.stdin.encoding)

        def match(return_code, out, err, expected):
            exit_ok = return_code in expected["return_codes"]
            stdout_ok = re.search(expected.get("stdout") or "", out)
            stderr_ok = re.search(expected.get("stderr") or "", err)
            return exit_ok and stdout_ok and stderr_ok
        if not any(match(return_code, out, err, exp) for exp in expect):
            print(err)
            e = subprocess.CalledProcessError(return_code, cmd, output=out)
            e.stdout, e.stderr = out, err
            raise e
        return self.SubprocessResult(out, err, return_code) 
开发者ID:kislyuk,项目名称:aegea,代码行数:23,代码来源:test.py

示例3: test_dry_run_commands

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def test_dry_run_commands(self):
        unauthorized_ok = [dict(return_codes=[os.EX_OK]),
                           dict(return_codes=[1, os.EX_SOFTWARE], stderr="UnauthorizedOperation")]
        self.call("aegea launch unittest --dry-run --storage /x=512 /y=1024 --ubuntu-linux-ami",
                  shell=True, expect=unauthorized_ok)
        self.call("aegea launch unittest --dry-run --no-verify-ssh-key-pem-file --ubuntu-linux-ami",
                  shell=True, expect=unauthorized_ok)
        self.call("aegea launch unittest --dry-run --spot --no-verify-ssh-key-pem-file --amazon-linux-ami",
                  shell=True, expect=unauthorized_ok)
        self.call("aegea launch unittest --dry-run --duration-hours 1 --no-verify-ssh-key-pem-file --amazon-linux-ami",
                  shell=True, expect=unauthorized_ok)
        self.call(("aegea launch unittest --duration 0.5 --min-mem 6 --cores 2 --dry-run --no-verify --client-token t "
                   "--amazon-linux-ami"),
                  shell=True, expect=unauthorized_ok)
        self.call("aegea build-ami i --dry-run --no-verify-ssh-key-pem-file",
                  shell=True, expect=unauthorized_ok)

        self.call("aegea batch submit --command pwd --dry-run", shell=True)
        self.call("echo pwd > run.sh && aegea batch submit --execute run.sh --dry-run", shell=True)
        self.call("aegea batch submit --wdl '{}' --dry-run".format(__file__.replace(".py", ".wdl")), shell=True)

        self.call("aegea ecs run --command pwd --dry-run", shell=True) 
开发者ID:kislyuk,项目名称:aegea,代码行数:24,代码来源:test.py

示例4: manage_events

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def manage_events(self, notify):
        filename = os.path.basename(self.source_path)

        while True:
            try:
                events = notify.read()
            except KeyboardInterrupt:
                return os.EX_OK
            else:
                LOG.debug("Caught %d events", len(events))

            events = self.filter_events(filename, events)
            descriptions = self.describe_events(events)
            LOG.debug("Got %d events after filtration: %s",
                      len(descriptions), descriptions)

            if events:
                self.output()

            LOG.info("Config was managed. Going to the next loop.") 
开发者ID:9seconds,项目名称:concierge,代码行数:22,代码来源:daemon.py

示例5: _instancecheck_impl

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def _instancecheck_impl(self, value, info: Info) -> InfoMsg:
        if not isinstance(value, str) or value == "":
            return info.errormsg(self, value)
        value = os.path.expanduser(value)
        if self.allow_std and value == "-" and (self.constraint is None or self.constraint(value)):
            return info.wrap(True)
        is_valid = True
        if os.path.exists(value):
            if os.path.isfile(value) and os.access(os.path.abspath(value), os.W_OK)\
                    and (self.constraint is None or self.constraint(value)):
                return info.wrap(True)
            return info.errormsg(self, value)
        if not self.allow_non_existent:
            return info.errormsg(self, "File doesn't exist")
        abs_name = os.path.abspath(value)
        dir_name = os.path.dirname(abs_name)
        if os.path.exists(dir_name) and os.access(dir_name, os.EX_OK) and os.access(dir_name, os.W_OK) \
            and (self.constraint is None or self.constraint(value)):
            return info.wrap(True)
        return info.errormsg(self, value) 
开发者ID:parttimenerd,项目名称:temci,代码行数:22,代码来源:typecheck.py

示例6: test_main_list

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def test_main_list(monkeypatch, capsys, mocked_sysexit, mocked_configure):
    server_id = pytest.faux.gen_uuid()
    host = pytest.faux.gen_alphanumeric()
    username = pytest.faux.gen_alphanumeric()
    initiator_id = pytest.faux.gen_uuid()

    tsk = task.ServerDiscoveryTask(server_id, host, username, initiator_id)
    tsk = tsk.create()

    monkeypatch.setenv(process.ENV_ENTRY_POINT, "server_discovery")
    monkeypatch.setenv(process.ENV_TASK_ID, str(tsk._id))
    monkeypatch.setattr("sys.argv", ["progname", "--list"])

    assert inventory.main() == os.EX_OK

    mocked_sysexit.assert_not_called()

    out, _ = capsys.readouterr()
    arg = json.loads(out)
    assert arg["new"]["hosts"] == [host]
    assert arg["_meta"]["hostvars"][host]["ansible_user"] == username 
开发者ID:Mirantis,项目名称:ceph-lcm,代码行数:23,代码来源:test_inventory.py

示例7: test_main_host_ok

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def test_main_host_ok(monkeypatch, capsys, mocked_sysexit, mocked_configure):
    server_id = pytest.faux.gen_uuid()
    host = pytest.faux.gen_alphanumeric()
    username = pytest.faux.gen_alphanumeric()
    initiator_id = pytest.faux.gen_uuid()

    tsk = task.ServerDiscoveryTask(server_id, host, username, initiator_id)
    tsk = tsk.create()

    monkeypatch.setenv(process.ENV_ENTRY_POINT, "server_discovery")
    monkeypatch.setenv(process.ENV_TASK_ID, str(tsk._id))
    monkeypatch.setattr("sys.argv", ["progname", "--host", host])

    assert inventory.main() == os.EX_OK

    mocked_sysexit.assert_not_called()

    out, _ = capsys.readouterr()
    arg = json.loads(out)
    assert arg["ansible_user"] == username 
开发者ID:Mirantis,项目名称:ceph-lcm,代码行数:22,代码来源:test_inventory.py

示例8: run

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def run(self):
        if self.finished:
            return

        self.process = subprocess.Popen(
            [str(self.path)],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=True
        )

        LOG.info("Run %s. Pid %d", self.path, self.process.pid)
        self.process.wait()
        logmethod = LOG.info if self.process.returncode == os.EX_OK \
            else LOG.warning
        logmethod("%s has been finished. Exit code %s",
                  self.path, self.process.returncode)

        self.stdout = self.process.stdout.read().decode("utf-8")
        self.stderr = self.process.stderr.read().decode("utf-8")

        if self.process.returncode != os.EX_OK:
            raise RuntimeError(
                "Program {0} has been finished with exit code {1}",
                self.path, self.process.returncode) 
开发者ID:Mirantis,项目名称:ceph-lcm,代码行数:27,代码来源:migration.py

示例9: get_package_version

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def get_package_version(prefix, connection, package_name):
    command = "dpkg-query --showformat='${Version}' --show %s" % shlex.quote(
        package_name)
    result = await connection.run(command)

    if result.exit_status != os.EX_OK:
        click.echo(
            "{0}package (failed {1}): {2} - {3}".format(
                prefix, result.exit_status, package_name, result.stderr.strip()
            )
        )
    else:
        click.echo(
            "{0}package (ok): {1}=={2}".format(
                prefix, package_name, result.stdout.strip()
            )
        ) 
开发者ID:Mirantis,项目名称:ceph-lcm,代码行数:19,代码来源:ceph_version.py

示例10: grep

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def grep(args):
    if args.context:
        args.before_context = args.after_context = args.context
    if not args.end_time:
        args.end_time = Timestamp("-0s")
    query = clients.logs.start_query(logGroupName=args.log_group,
                                     startTime=int(timestamp(args.start_time) * 1000),
                                     endTime=int(timestamp(args.end_time) * 1000),
                                     queryString=args.query)
    seen_results = {}
    print_with_context = partial(print_log_event_with_context, before=args.before_context, after=args.after_context)
    try:
        with ThreadPoolExecutor() as executor:
            while True:
                res = clients.logs.get_query_results(queryId=query["queryId"])
                log_record_pointers = []
                for record in res["results"]:
                    event = {r["field"]: r["value"] for r in record}
                    event_hash = hashlib.sha256(json.dumps(event, sort_keys=True).encode()).hexdigest()[:32]
                    if event_hash in seen_results:
                        continue
                    if "@ptr" in event and (args.before_context or args.after_context):
                        log_record_pointers.append(event["@ptr"])
                    else:
                        print_log_event(event)
                    seen_results[event_hash] = event
                if log_record_pointers:
                    executor.map(print_with_context, log_record_pointers)
                if res["status"] == "Complete":
                    break
                elif res["status"] in {"Failed", "Cancelled"}:
                    raise AegeaException("Query status: {}".format(res["status"]))
                time.sleep(1)
    finally:
        try:
            clients.logs.stop_query(queryId=query["queryId"])
        except clients.logs.exceptions.InvalidParameterException:
            pass
    logger.debug("Query %s: %s", query["queryId"], res["statistics"])
    return SystemExit(os.EX_OK if seen_results else os.EX_DATAERR) 
开发者ID:kislyuk,项目名称:aegea,代码行数:42,代码来源:logs.py

示例11: check_output

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def check_output(self, command, input_data=None, stderr=sys.stderr):
        logger.debug('Running "%s"', command)
        ssh_stdin, ssh_stdout, ssh_stderr = self.exec_command(command)
        if input_data is not None:
            ssh_stdin.write(input_data)
        exit_code = ssh_stdout.channel.recv_exit_status()
        stderr.write(ssh_stderr.read().decode("utf-8"))
        if exit_code != os.EX_OK:
            raise Exception('Error while running "{}": {}'.format(command, errno.errorcode.get(exit_code)))
        return ssh_stdout.read().decode("utf-8") 
开发者ID:kislyuk,项目名称:aegea,代码行数:12,代码来源:ssh.py

示例12: page_output

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def page_output(content, pager=None, file=None):
    if file is None:
        file = sys.stdout
    if not content.endswith("\n"):
        content += "\n"

    pager_process = None
    try:
        if file != sys.stdout or not file.isatty() or not content.startswith(border("┌")):
            raise AegeaException()
        content_lines = content.splitlines()
        content_rows = len(content_lines)

        tty_cols, tty_rows = get_terminal_size()

        naive_content_cols = max(len(i) for i in content_lines)
        if tty_rows > content_rows and tty_cols > naive_content_cols:
            raise AegeaException()

        content_cols = max(len(strip_ansi_codes(i)) for i in content_lines)
        if tty_rows > content_rows and tty_cols > content_cols:
            raise AegeaException()

        pager_process = subprocess.Popen(pager or os.environ.get("PAGER", "less -RS"), shell=True,
                                         stdin=subprocess.PIPE, stdout=file)
        pager_process.stdin.write(content.encode("utf-8"))
        pager_process.stdin.close()
        pager_process.wait()
        if pager_process.returncode != os.EX_OK:
            raise AegeaException()
    except Exception as e:
        if not (isinstance(e, IOError) and e.errno == errno.EPIPE):
            file.write(content.encode("utf-8") if USING_PYTHON2 else content)
    finally:
        try:
            pager_process.terminate()
        except BaseException:
            pass 
开发者ID:kislyuk,项目名称:aegea,代码行数:40,代码来源:printing.py

示例13: test_secrets

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def test_secrets(self):
        unauthorized_ok = [dict(return_codes=[os.EX_OK]),
                           dict(return_codes=[1, os.EX_SOFTWARE], stderr="(AccessDenied|NoSuchKey)")]
        secret_name = "test_secret_{}".format(int(time.time()))
        self.call("{s}=test aegea secrets put {s} --iam-role aegea.launch".format(s=secret_name),
                  shell=True, expect=unauthorized_ok)
        self.call("aegea secrets put {s} --generate-ssh-key --iam-role aegea.launch".format(s=secret_name),
                  shell=True, expect=unauthorized_ok)
        self.call("aegea secrets ls", shell=True, expect=unauthorized_ok)
        self.call("aegea secrets ls --json", shell=True, expect=unauthorized_ok)
        self.call("aegea secrets get {s} --iam-role aegea.launch".format(s=secret_name), shell=True,
                  expect=unauthorized_ok)
        self.call("aegea secrets delete {s} --iam-role aegea.launch".format(s=secret_name), shell=True,
                  expect=unauthorized_ok) 
开发者ID:kislyuk,项目名称:aegea,代码行数:16,代码来源:test.py

示例14: _popen_psql

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def _popen_psql(sql):
	if os.getuid():
		raise RuntimeError('_popen_psql can only be used as root due to su requirement')
	results = startup.run_process(['su', 'postgres', '-c', "psql -At -c \"{0}\"".format(sql)])
	if results.status != os.EX_OK:
		raise errors.KingPhisherDatabaseError("failed to execute postgresql query '{0}' via su and psql".format(sql))
	return results.stdout.strip().split('\n') 
开发者ID:rsmusllp,项目名称:king-phisher,代码行数:9,代码来源:manager.py

示例15: _exit_gracefully

# 需要导入模块: import os [as 别名]
# 或者: from os import EX_OK [as 别名]
def _exit_gracefully(self, signum, frame):  # pylint: disable=unused-argument
        """
        Helper method to clean up DAG file processors to avoid leaving orphan processes.
        """
        self.log.info("Exiting gracefully upon receiving signal %s", signum)
        self.terminate()
        self.end()
        self.log.debug("Finished terminating DAG processors.")
        sys.exit(os.EX_OK) 
开发者ID:apache,项目名称:airflow,代码行数:11,代码来源:dag_processing.py


注:本文中的os.EX_OK属性示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。