subprocess.Popen(['cat','/path/to/file'], stdout=subprocess.PIPE, shell=True)
和
subprocess.Popen(['cat '+'/path/to/file'], stdout=subprocess.PIPE, shell=True)
之间的区别? 我在ipython中做这个。 对于第一个,ipython只是挂起。也许不会挂起,但速度要慢很多。 第二个就好。
只是不知道为什么。
subprocess.Popen(['cat','/path/to/file'], stdout=subprocess.PIPE, shell=True)
和
subprocess.Popen(['cat '+'/path/to/file'], stdout=subprocess.PIPE, shell=True)
之间的区别? 我在ipython中做这个。 对于第一个,ipython只是挂起。也许不会挂起,但速度要慢很多。 第二个就好。
只是不知道为什么。
第一个实际上只运行cat
(因为如果您使用shell = True
解析命令的方式),因此挂起,因为它正在等待输入。第二个是运行cat /path/to/file
。您可以通过执行看到:
>>> subprocess.Popen(['ls', '-l'])
<subprocess.Popen object at 0x10048bdd0>
>>> total 8
-rw------- 1 root wheel 652 Nov 29 09:07 000d94cfc78b4
srwxr-xr-x 1 nbastin wheel 0 Nov 29 09:06 ics179
srwxr-xr-x 1 nbastin wheel 0 Nov 29 09:06 icssuis501
drwx------ 3 nbastin wheel 102 Nov 29 09:06 launch-3ZniHd
drwx------ 3 nbastin wheel 102 Nov 29 09:06 launch-8QRgz2
drwx------ 3 nbastin wheel 102 Nov 29 09:06 launch-M5ppWp
drwx------ 3 nbastin wheel 102 Nov 29 09:06 launchd-137.ztQAmI
drwx------ 2 nbastin wheel 68 Nov 29 09:57 ssh-LreGlOZPAR
,而使用shell = True
做:
>>> subprocess.Popen(['ls', '-l'], shell = True)
<subprocess.Popen object at 0x10048bd90>
>>> 000d94cfc78b4 ics179 icssuis501 launch-3ZniHd launch-8QRgz2 launch-M5ppWp launchd-137.ztQAmI ssh-LreGlOZPAR
如果设置shell = True
,路过的列表为args
不会得到你想要的行为 - 你需要传递一个字符串。
我测试的样品,发现其第一工作返回在IPython的一个POPEN对象但第二做了同样的但印刷cat: /path/to/file: No such file or directory
我喜欢可能当与shell=True
避免使用subprocess.Popen
并用一个列表['x', '--version']
因为这避免了需要引用路径名与说'坟墓在他们或一些这样的渣土
在补丁pymp.py我改变:
p = subprocess.Popen(['mplayer -slave -quiet \'' + target + '\' -include \'' + MPLAYERCONFFILE + '\' 2>/dev/null'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
到:
devnull = open('/dev/null', 'w')
p = subprocess.Popen(['mplayer', '-slave', '-quiet', target, '-include', MPLAYERCONFFILE], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=devnull)
所以,你的意思是第一个,列表中的第二个字符串被忽略? – wliao 2010-11-30 07:14:30