繁体   English   中英

Python的subprocess.Popen()结果与命令行不同吗?

[英]Python's subprocess.Popen() results differ from command line?

在Windows 7 x32上的VS解决方案目录中使用Cygwin, find命令产生正确的结果:

$ find . -iname "*.sln"
./ProjName.sln

但是与Python的subprocess.Popen()相同的命令似乎仅在*上匹配:

>>> import subprocess
>>> print subprocess.Popen(['find', '.', '-iname', '"*.sln"'],
...     stdout=subprocess.PIPE, shell=True).communicate()[0]
.
./.git
./.git/COMMIT_EDITMSG
./.git/config
./.git/description
<snip>

我的Popen()调用有什么问题?

以下对我有用:

>>> import subprocess
>>> print subprocess.Popen(['find', '.', '-iname', '*.sln'],
...     stdout=subprocess.PIPE, shell=False).communicate()[0]

注意删除了*.sln周围的双引号,并将shell设置为False

这样可以确保传递*.sln来逐字find ,并且不会被shell扩展。

编辑:以下内容也适用:

>>> print subprocess.Popen(['find . -iname "*.sln"'],
...     stdout=subprocess.PIPE, shell=True).communicate()[0]

在POSIX系统上,当您使用Popen(['find', '.', '-iname', '"*.sln"'], shell=True) ,Python会这样做:

/bin/sh -c find . -iname "*.sln"

如果阅读sh的文档,您会发现只有-c之后的第一个参数被视为要作为shell脚本执行的命令字符串。 其余的参数实际上被视为shell脚本的参数。 在这种情况下,由于外壳程序脚本仅由命令名称“ find”组成,因此将忽略参数。 如果运行,您可以观察到此行为:

>>> subprocess.call(['echo arg0 = $0, arg1 = $1', 'foo', 'bar'], shell=True)
arg0 = foo, arg1 = bar
0

代码应为:

print subprocess.Popen(['find . -iname "*.sln"'], stdout=subprocess.PIPE, shell=True).communicate()[0]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM