在 Windows 上的 os.system 中转义双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1912818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
double quote escaping in os.system on windows
提问by jaimechen
I want to escape '"' and all other wild chars in program name and arguments, so I try to double quote them. and I can do this in cmd.exe
我想在程序名称和参数中转义 '"' 和所有其他通配符,所以我尝试双引号它们。我可以在 cmd.exe 中执行此操作
C:\bay\test\go>"test.py" "a" "b" "c"
hello
['C:\bay\test\go\test.py', 'a', 'b', 'c']
but what's wrong with the following code using os.sytem?
但是以下使用 os.sytem 的代码有什么问题?
cmd = '"test.py" "a" "b" "c"'
print cmd
os.system(cmd)
its output:
它的输出:
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.
Why is the whole string '"test.py" "a" "b" "c"' recognized as a single command? But the following example isn't:
为什么整个字符串 '"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']
Thanks!
谢谢!
采纳答案by YOU
Try with os.system('python "test.py" "a" "b" "c"')
试试 os.system('python "test.py" "a" "b" "c"')
You can also use subprocessmodule for that kind of purpose,
您也可以将子流程模块用于这种目的,
please take a look this thread
请看看这个线程
UPDATE:When I do, os.system('"test.py" "a" "b" "c"')
, I got similar errors, but not on os.system('test.py "a" "b" "c"')
, So, I like to assume that first parameter should not be double-quoted
更新:当我这样做时os.system('"test.py" "a" "b" "c"')
,我得到了类似的错误,但没有出现os.system('test.py "a" "b" "c"')
,所以,我想假设第一个参数不应该被双引号
回答by jaimechen
Furthing google comes this page
进一步谷歌来到这个页面
http://ss64.com/nt/syntax-esc.html
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""'
does work!
cmd = '""test.py" "a" "b" "c""'
确实有效!
回答by Hey
Actually, it just work as design. You can NOT use os.system like that. See this: http://mail.python.org/pipermail/python-bugs-list/2000-July/000946.html
实际上,它只是作为设计工作。你不能像那样使用 os.system。看到这个:http: //mail.python.org/pipermail/python-bugs-list/2000-July/000946.html
回答by user2435152
Enclose the arguments in brackets, it works.
将参数括在括号中,它有效。
CMD /k ("c:\batch files\test.cmd" "Parameter 1 with space" "Parameter2 with space")