且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么字符 '^'被 Python Popen 忽略 - 如何转义 '^'Popen Windows 中的字符?

更新时间:2022-04-13 23:43:17

为什么 Python 会剪切 '^' 字符以及如何避免它?

Why Python cuts '^' character and how to avoid it?

Python 不会剪切 ^ 字符.Popen() 将字符串 (resize_command) 传递给 CreateProcess() Windows API 调用.

Python does not cut ^ character. Popen() passes the string (resize_command) to CreateProcess() Windows API call as is.

易于测试:

#!/usr/bin/env python
import sys
import subprocess

subprocess.check_call([sys.executable, '-c', 'import sys; print(sys.argv)'] +
                      ['^', '<-- see, it is still here'])

后一个命令使用 subprocess.list2cmdline() 跟随 解析 C 命令行参数 规则将列表转换为命令字符串——它对 ^ 没有影响.

The latter command uses subprocess.list2cmdline() that follows Parsing C Command-Line Arguments rules to convert the list into the command string -- it has not effect on ^.

^CreateProcess 来说并不特殊().^ 是特殊的,如果你使用 shell=True(当 cmd.exe 运行时).

^ is not special for CreateProcess(). ^ is special if you use shell=True (when cmd.exe is run).

当且仅当生成的命令行将由 cmd 解释,在每个 shell 元字符(或每个字符)前加上 ^ 字符.它包括 ^ 本身.

if and only if the command line produced will be interpreted by cmd, prefix each shell metacharacter (or each character) with a ^ character. It includes ^ itself.