You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3 argv偶现换行拆分异常,该行为是否属于Bug?

Is this argv splitting behavior in Python 3 a 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:
    $ 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']
    
    At first glance it looks like the string was split into multiple elements, but checking len(sys.argv) will show it's still 2 in both versions. Python 3's pprint just 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:
    $ 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']
    
    Here, the shell escapes \n into \\n before passing it to Python. Again, Python 3's pprint splits the display at a space for readability, but the string is still a single element in sys.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:11:22