Windows 上 os.system 中的双引号转义
我想转义程序名称和参数中的 '"' 和所有其他通配符,因此我尝试对它们加双引号。我可以在 cmd.exe 中执行此操作,
C:\bay\test\go>"test.py" "a" "b" "c"
hello
['C:\\bay\\test\\go\\test.py', 'a', 'b', 'c']
但使用 os.sytem 的以下代码有什么问题?
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']
谢谢!
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
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?
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:
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
进一步谷歌来到这个页面
http://ss64.com/nt/syntax-esc.html
cmd = '""test.py" "a" "b" "c""'
确实有效!Furthing google comes this page
http://ss64.com/nt/syntax-esc.html
cmd = '""test.py" "a" "b" "c""'
does work!实际上,它只是作为设计起作用。
你不能那样使用 os.system 。看这个:
http://mail.python.org/pipermail/ python-bugs-list/2000-July/000946.html
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('python "test.py" "a" "b" "c"')
您也可以使用 subprocess 模块来实现这种目的,
请看一下 这个线程
更新:当我这样做时,
os.system('"test.py" "a" "b" "c"')
,我得到了类似的错误,但不是在 os.system('test.py "a" "b" "c"') 上,所以,我喜欢假设第一个参数不应该用双引号引起来Try with
os.system('python "test.py" "a" "b" "c"')
You can also use subprocess module 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 onos.system('test.py "a" "b" "c"')
, So, I like to assume that first parameter should not be double-quoted将参数括在括号中,它可以工作。
Enclose the arguments in brackets, it works.