Python sys 模块,args() 实例源码

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

项目:deb-python-dcos    作者:openstack    | 项目源码 | 文件源码
def mock_called_some_args(mock, *args, **kwargs):
    """Convience method for some mock assertions.  Returns True if the
    arguments to one of the calls of `mock` contains `args` and
    `kwargs`.

    :param mock: the mock to check
    :type mock: mock.Mock
    :returns: True if the arguments to one of the calls for `mock`
    contains `args` and `kwargs`.
    :rtype: bool
    """

    for call in mock.call_args_list:
        call_args, call_kwargs = call

        if any(arg not in call_args for arg in args):
            continue

        if any(k not in call_kwargs or call_kwargs[k] != v
               for k, v in kwargs.items()):
            continue

        return True

    return False
项目:deb-python-dcos    作者:openstack    | 项目源码 | 文件源码
def exec_mock(main, args):
    """Call a main function with sys.args mocked, and capture
    stdout/stderr

    :param main: main function to call
    :type main: function
    :param args: sys.args to mock, excluding the initial 'dcos'
    :type args: [str]
    :returns: (returncode, stdout, stderr)
    :rtype: (int, bytes, bytes)
    """

    print('MOCK ARGS: {}'.format(' '.join(args)))

    with mock_args(args) as (stdout, stderr):
        returncode = main(args)

    stdout_val = six.b(stdout.getvalue())
    stderr_val = six.b(stderr.getvalue())

    print('STDOUT: {}'.format(stdout_val))
    print('STDERR: {}'.format(stderr_val))

    return (returncode, stdout_val, stderr_val)
项目:deb-python-dcos    作者:openstack    | 项目源码 | 文件源码
def assert_mock(main,
                args,
                returncode=0,
                stdout=b'',
                stderr=b''):
    """Mock and call a main function, and assert expected behavior.

    :param main: main function to call
    :type main: function
    :param args: sys.args to mock, excluding the initial 'dcos'
    :type args: [str]
    :type returncode: int
    :param stdout: Expected stdout
    :type stdout: str
    :param stderr: Expected stderr
    :type stderr: str
    :rtype: None
    """

    returncode_, stdout_, stderr_ = exec_mock(main, args)

    assert returncode_ == returncode
    assert stdout_ == stdout
    assert stderr_ == stderr
项目:deploy-marathon-bluegreen    作者:softonic    | 项目源码 | 文件源码
def mock_called_some_args(mock, *args, **kwargs):
    """Convience method for some mock assertions.  Returns True if the
    arguments to one of the calls of `mock` contains `args` and
    `kwargs`.

    :param mock: the mock to check
    :type mock: mock.Mock
    :returns: True if the arguments to one of the calls for `mock`
    contains `args` and `kwargs`.
    :rtype: bool
    """

    for call in mock.call_args_list:
        call_args, call_kwargs = call

        if any(arg not in call_args for arg in args):
            continue

        if any(k not in call_kwargs or call_kwargs[k] != v
               for k, v in kwargs.items()):
            continue

        return True

    return False
项目:deploy-marathon-bluegreen    作者:softonic    | 项目源码 | 文件源码
def exec_mock(main, args):
    """Call a main function with sys.args mocked, and capture
    stdout/stderr

    :param main: main function to call
    :type main: function
    :param args: sys.args to mock, excluding the initial 'dcos'
    :type args: [str]
    :returns: (returncode, stdout, stderr)
    :rtype: (int, bytes, bytes)
    """

    print('MOCK ARGS: {}'.format(' '.join(args)))

    with mock_args(args) as (stdout, stderr):
        returncode = main(args)

    stdout_val = six.b(stdout.getvalue())
    stderr_val = six.b(stderr.getvalue())

    print('STDOUT: {}'.format(stdout_val))
    print('STDERR: {}'.format(stderr_val))

    return (returncode, stdout_val, stderr_val)
项目:deploy-marathon-bluegreen    作者:softonic    | 项目源码 | 文件源码
def assert_mock(main,
                args,
                returncode=0,
                stdout=b'',
                stderr=b''):
    """Mock and call a main function, and assert expected behavior.

    :param main: main function to call
    :type main: function
    :param args: sys.args to mock, excluding the initial 'dcos'
    :type args: [str]
    :type returncode: int
    :param stdout: Expected stdout
    :type stdout: str
    :param stderr: Expected stderr
    :type stderr: str
    :rtype: None
    """

    returncode_, stdout_, stderr_ = exec_mock(main, args)

    assert returncode_ == returncode
    assert stdout_ == stdout
    assert stderr_ == stderr
项目:deb-python-dcos    作者:openstack    | 项目源码 | 文件源码
def mock_args(args):
    """ Context manager that mocks sys.args and captures stdout/stderr

    :param args: sys.args values to mock
    :type args: [str]
    :rtype: None
    """
    with mock.patch('sys.argv', ['dcos'] + args):
        stdout, stderr = sys.stdout, sys.stderr
        sys.stdout, sys.stderr = six.StringIO(), six.StringIO()
        try:
            yield sys.stdout, sys.stderr
        finally:
            sys.stdout, sys.stderr = stdout, stderr
项目:niceman    作者:ReproNim    | 项目源码 | 文件源码
def _license_info():
    return """\
Copyright (c) 2016- NICEMAN developers (parts 2013-2016 DataLad developers)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""


# TODO:  OPT look into making setup_parser smarter to become faster
# Now it seems to take up to 200ms to do all the parser setup
# even though it might not be necessary to know about all the commands etc.
# I wondered if it could somehow decide on what commands to worry about etc
# by going through sys.args first
项目:deploy-marathon-bluegreen    作者:softonic    | 项目源码 | 文件源码
def mock_args(args):
    """ Context manager that mocks sys.args and captures stdout/stderr

    :param args: sys.args values to mock
    :type args: [str]
    :rtype: None
    """
    with mock.patch('sys.argv', ['dcos'] + args):
        stdout, stderr = sys.stdout, sys.stderr
        sys.stdout, sys.stderr = six.StringIO(), six.StringIO()
        try:
            yield sys.stdout, sys.stderr
        finally:
            sys.stdout, sys.stderr = stdout, stderr
项目:niceman    作者:ReproNim    | 项目源码 | 文件源码
def main(args=None):
    lgr.log(5, "Starting main(%r)", args)
    # PYTHON_ARGCOMPLETE_OK
    parser = setup_parser()
    try:
        import argcomplete
        argcomplete.autocomplete(parser)
    except ImportError:
        pass

    # parse cmd args
    cmdlineargs = parser.parse_args(args)
    if not cmdlineargs.change_path is None:
        for path in cmdlineargs.change_path:
            chpwd(path)

    if not hasattr(cmdlineargs, 'func'):
        lgr.info("No command given, returning")
        return

    ret = None
    if cmdlineargs.common_debug or cmdlineargs.common_idebug:
        # so we could see/stop clearly at the point of failure
        setup_exceptionhook(ipython=cmdlineargs.common_idebug)
        ret = cmdlineargs.func(cmdlineargs)
    else:
        # otherwise - guard and only log the summary. Postmortem is not
        # as convenient if being caught in this ultimate except
        try:
            ret = cmdlineargs.func(cmdlineargs)
        except InsufficientArgumentsError as exc:
            # if the func reports inappropriate usage, give help output
            lgr.error('%s (%s)' % (exc_str(exc), exc.__class__.__name__))
            cmdlineargs.subparser.print_usage()
            sys.exit(1)
        except MissingConfigFileError as exc:
            # TODO: ConfigManager is not finding files in the default locations.
            message = """
    ERROR: Unable to locate the niceman.cfg file.

    You may either specify one using the --config parameter or place one in the
    one of following locations:

    1. '/etc/niceman/niceman.cfg'
    2. 'niceman/config' in all directories defined by $XDG_CONFIG_DIRS
        (by default: /etc/xdg/)
    3. 'niceman.cfg' in $XDG_CONFIG_HOME (by default: ~/.config/)
    4. 'niceman.cfg' in the current directory
"""
            # print(message)
            lgr.error('%s (%s)' % (exc_str(exc), exc.__class__.__name__))
            sys.exit(1)
        except Exception as exc:
            # print('%s (%s)' % (exc_str(exc), exc.__class__.__name__))
            lgr.error('%s (%s)' % (exc_str(exc), exc.__class__.__name__))
            sys.exit(1)
    if hasattr(cmdlineargs, 'result_renderer'):
        cmdlineargs.result_renderer(ret)