在Windows上os.system中的双引号转义

3 投票
4 回答
7943 浏览
提问于 2025-04-15 17:05

我想在程序名称和参数中转义(也就是处理)双引号('"')和其他特殊字符,所以我尝试用双引号把它们包起来。在cmd.exe中我可以做到这一点。

C:\bay\test\go>"test.py" "a" "b"  "c"
hello
['C:\\bay\\test\\go\\test.py', 'a', 'b', 'c']

但是,下面这段使用os.system的代码有什么问题呢?

cmd = '"test.py" "a" "b" "c"'
print cmd
os.system(cmd)

它的输出是:

C:\bay\test\go>test2.py
"test.py" "a" "b" "c"
'test.py" "a" "b" "c' is not recognized as an internal or external command,
operable program or batch file.

为什么整个字符串 '"test.py" "a" "b" "c"' 被识别为一个单独的命令?而下面这个例子却不是:

cmd = 'test.py a b c'
print cmd
os.system(cmd)

C:\bay\test\go>test2.py
test.py a b c
hello
['C:\\bay\\test\\go\\test.py', 'a', 'b', 'c']

谢谢!

4 个回答

3

其实,它就是按照设计来工作的。你不能那样使用 os.system。看看这个链接:

http://mail.python.org/pipermail/python-bugs-list/2000-July/000946.html

5

进一步了解,谷歌上有这个页面

http://ss64.com/nt/syntax-esc.html

To launch a batch script which itself requires "quotes" 
CMD /k ""c:\batch files\test.cmd" "Parameter 1 with space" "Parameter2 with space"" 

cmd = '""test.py" "a" "b" "c""' 这个写法是可以用的!

1

可以试试用 os.system('python "test.py" "a" "b" "c"') 这个命令。

你也可以用 subprocess 模块来实现类似的功能。

可以看看 这个讨论

更新:当我使用 os.system('"test.py" "a" "b" "c"') 时,遇到了类似的错误,但用 os.system('test.py "a" "b" "c"') 就没有问题。所以,我觉得第一个参数不应该加双引号。

撰写回答