windows操作系统中的双引号转义

2024-05-23 15:29:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在程序名和参数中转义“和所有其他的野生字符,所以我试着用双引号引用它们。我可以在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']

谢谢!


Tags: orpytest程序cmdgohello参数
3条回答

尝试使用os.system('python "test.py" "a" "b" "c"')

您也可以使用子流程模块来实现这种目的

请看一下this thread

UPDATE:当我这样做,os.system('"test.py" "a" "b" "c"')时,我得到了类似的错误,但不是在os.system('test.py "a" "b" "c"')上,所以,我想假设第一个参数不应该是双引号

谷歌又来了

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""'确实有效!

实际上,它只是作为设计工作。 你不能那样使用os.system。请参阅: http://mail.python.org/pipermail/python-bugs-list/2000-July/000946.html

相关问题 更多 >