Skip to content

gh-131524: Update platform CLI to use argparse #131542

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
May 3, 2025
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 33 additions & 4 deletions Lib/platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -1464,9 +1464,38 @@ def invalidate_caches():

### Command line interface

if __name__ == '__main__':
# Default is to print the aliased verbose platform string
terse = ('terse' in sys.argv or '--terse' in sys.argv)
aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
def _parse_args(args: list[str] | None):
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("args", nargs="*", choices=["nonaliased", "terse"])
parser.add_argument(
"--terse",
action="store_true",
help=("return only the absolute minimum information needed to identify the "
"platform"),
)
parser.add_argument(
"--nonaliased",
dest="aliased",
action="store_false",
help=("disable system/ OS name aliasing. If aliasing is enabled, some "
"platforms will report system names which differ from their common "
"names, e.g. SunOS will be reported as Solaris"),
)

return parser.parse_args(args)


def _main(args: list[str] | None = None):
args = _parse_args(args)

terse = args.terse or ("terse" in args.args)
aliased = args.aliased and ('nonaliased' not in args.args)

print(platform(aliased, terse))


if __name__ == "__main__":
_main()
sys.exit(0)
78 changes: 78 additions & 0 deletions Lib/test/test_platform.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import os
import copy
import contextlib
import io
import itertools
import pickle
import platform
import shlex
import subprocess
import sys
import unittest
from unittest import mock
from textwrap import dedent

from test import support
from test.support import os_helper
Expand Down Expand Up @@ -741,5 +746,78 @@ def test_parse_os_release(self):
self.assertEqual(len(info["SPECIALS"]), 5)


class CommandLineTest(unittest.TestCase):
def setUp(self):
self.clear_caches()
self.addCleanup(self.clear_caches)

def clear_caches(self):
platform._platform_cache.clear()
platform._sys_version_cache.clear()
platform._uname_cache = None
platform._os_release_cache = None

@staticmethod
def text_normalize(string):
"""Dedent *string* and strip it from its surrounding whitespaces.
This method is used by the other utility functions so that any
string to write or to match against can be freely indented.
"""
return dedent(string).strip()

def invoke_platform(self, *flags):
output = io.StringIO()
with contextlib.redirect_stdout(output):
platform._main(args=flags)
return self.text_normalize(output.getvalue())

def test_unknown_flag(self):
with self.assertRaises(SystemExit):
# suppress argparse error message
with contextlib.redirect_stderr(io.StringIO()):
_ = self.invoke_platform('--unknown')

def test_invocation(self):
flags = (
"--terse", "--nonaliased", "terse", "nonaliased"
)

for r in range(len(flags) + 1):
for combination in itertools.combinations(flags, r):
self.invoke_platform(*combination)

def test_arg_parsing(self):
# Due to backwards compatibility, the `aliased` and `terse` parameters
# are computed based on a combination of positional arguments and flags.
#
# This test tests that the arguments are correctly passed to the underlying
# `platform.platform()` call. The parameters are two booleans for `aliased`
# and `terse`
options = (
("--nonaliased", (False, False)),
("nonaliased", (False, False)),
("--terse", (True, True)),
("terse", (True, True)),
("nonaliased terse", (False, True)),
("--nonaliased terse", (False, True)),
("--terse nonaliased", (False, True)),
)

for flags, args in options:
with self.subTest(f"{flags}, {args}"):
with mock.patch.object(platform, 'platform') as obj:
self.invoke_platform(*shlex.split(flags))
obj.assert_called_once_with(*args)

def test_help(self):
output = io.StringIO()

with self.assertRaises(SystemExit):
with contextlib.redirect_stdout(output):
platform._main(args=["--help"])

self.assertIn("usage:", output.getvalue())


if __name__ == '__main__':
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Add help message to :mod:`platform` command-line interface. Contributed by
Harry Lees.
Loading