utils_net: strip ANSI escape codes before parsing JSON output#4354
utils_net: strip ANSI escape codes before parsing JSON output#4354dzhengfy wants to merge 1 commit intoavocado-framework:masterfrom
Conversation
When running ip commands with -json, some environments may include ANSI escape sequences (e.g., bracketed paste mode codes like ^[[?2004l) in the output, which causes json.loads to fail. This patch ensures that any ANSI escape sequences are stripped from the output before attempting to parse it as JSON. Signed-off-by: Dan Zheng <dzheng@redhat.com>
There was a problem hiding this comment.
Code Review
This pull request introduces ANSI escape sequence stripping for command outputs in get_linux_iface_info and get_default_gateway_json to prevent JSON parsing errors. The reviewer suggests refactoring the duplicated regex into a module-level compiled constant to improve performance and maintainability.
|
|
||
| try: | ||
| ip_output_str = run_func(ip_cmd).strip() | ||
| ip_output_str = re.sub(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])', '', ip_output_str) |
There was a problem hiding this comment.
The ANSI escape sequence regex is duplicated here and in get_default_gateway_json (line 4121). To improve maintainability and performance, consider defining this regex as a compiled constant at the module level (e.g., ANSI_ESCAPE_RE = re.compile(...)). This avoids redundant string compilation on every function call and ensures consistency across the module.
|
|
||
| try: | ||
| ip_output_str = run_func(cmd).strip() | ||
| ip_output_str = re.sub(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])', '', ip_output_str) |
|
Before the fix: After the fix: no Error |
This PR fixes a JSON parsing issue in
virttest/utils_net.pywhere ANSI escape sequences (like bracketed paste mode codes^[[?2004l) inip -jsonoutput would causejson.loadsto fail.The fix involves stripping all ANSI escape sequences from the command output string before attempting to parse it as JSON.
Signed-off-by: Dan Zheng dzheng@redhat.com