![](/img/trans.png)
[英]Python - what is difference in os.popen and subprocess.Popen?
[英]Python subprocess Popen parameter difference
之間有什么區別
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.