Python 3 argv偶现换行拆分异常,该行为是否属于Bug?
Short answer: This isn't a bug — it's just a change in how Python 3's pprint formats strings with newlines for readability. The actual sys.argv list isn't being split; the string remains a single element in the list.
Let's break down the details with your examples:
The Test Scripts
First, here are the two scripts used to reproduce the behavior:
print_argv.py
import sys from pprint import pprint pprint(sys.argv) # Add this line to verify element count: # print(f"Number of argv elements: {len(sys.argv)}")
test.py
import sys import subprocess subprocess.check_call([ 'python%s' % sys.argv[1], './print_argv.py', 'similarity index 90%\nrename from file1.txt\nrename to file1-mv.txt\nindex 2bef330..f8fd673 100644\n', ])
Behavior Comparison
1. Running via subprocess
- Python 2 Output:
$ python3 test.py 2 ['./print_argv.py', 'similarity index 90%\nrename from file1.txt\nrename to file1-mv.txt\nindex 2bef330..f8fd673 100644\n'] - Python 3 Output:
At first glance it looks like the string was split into multiple elements, but checking$ python3 test.py 3 ['./print_argv.py', 'similarity index 90%\n' 'rename from file1.txt\n' 'rename to file1-mv.txt\n' 'index 2bef330..f8fd673 100644\n']len(sys.argv)will show it's still2in both versions. Python 3'spprintjust wraps the string across multiple lines at newline characters to make it easier to read.
2. Running Directly via Shell
- Python 2 Output:
$ python2 print_argv.py 'similarity index 90%\nrename from file1.txt\nrename to file1-mv.txt\nindex 2bef330..f8fd673 100644\n' ['print_argv.py', 'similarity index 90%\\nrename from file1.txt\\nrename to file1-mv.txt\\nindex 2bef330..f8fd673 100644\\n'] - Python 3 Output:
Here, the shell escapes$ python3 print_argv.py 'similarity index 90%\nrename from file1.txt\nrename to file1-mv.txt\nindex 2bef330..f8fd673 100644\n' ['print_argv.py', 'similarity index 90%\\nrename from file1.txt\\nrename to ' 'file1-mv.txt\\nindex 2bef330..f8fd673 100644\\n']\ninto\\nbefore passing it to Python. Again, Python 3'spprintsplits the display at a space for readability, but the string is still a single element insys.argv.
Why This Happens
Python 3 updated the pprint module to format multi-line or long strings in a more human-friendly way. The splitting is purely cosmetic in the output — the underlying sys.argv list structure and string content haven't changed. If you use a regular print(sys.argv) instead of pprint, you'll see the string as a single, unbroken entry in both Python 2 and 3.
内容的提问来源于stack exchange,提问作者Pastafarianist

