[英]Path environment variables in Python and Mac OS X when using subprocess.call
[英]Python subprocess call can't find full path on Mac OS X
在我的Python腳本中,這一行:
call("/Applications/BitRock\\ InstallBuilder\\ for\\ Qt\\ 8.5.2/bin/Builder.app/Contents/MacOS/installbuilder.sh")
每次都會失敗,並顯示錯誤OSError: [Errno 2] No such file or directory
但是,如果我寫出該字符串的結果:
sys.stdout.write("/Applications/BitRock\\ InstallBuilder\\ for\\ Qt\\ 8.5.2/bin/Builder.app/Contents/MacOS/installbuilder.sh")
我得到:
/Applications/BitRock\ InstallBuilder\ for\ Qt\ 8.5.2/bin/Builder.app/Contents/MacOS/installbuilder.sh
如果我直接將其放入終端,則效果很好。
我想念什么?
默認情況下, subprocess.call
使用任何shell( shell=False
)。 因此,無需逃脫空間。 shell需要空格轉義(因為shell需要知道二進制文件的名稱和參數)。 因此,以下所有用法都是正確的(和相似的):
在不產生產生子進程的外殼的情況下(有利):
from subprocess import call call('/Applications/BitRock InstallBuilder for Qt 8.5.2/bin/Builder.app/Contents/MacOS/installbuilder.sh')
或再次不使用shell(顯式shell=False
和參數列表的用法)
from subprocess import call call(['/Applications/BitRock InstallBuilder for Qt 8.5.2/bin/Builder.app/Contents/MacOS/installbuilder.sh'], shell=False)
但是,當首先告訴subprocess
進程所有swawn shell之后又產生子進程本身時,必須轉義空格,因為這是一個shell命令:
from subprocess import call call('/Applications/BitRock\\\\ InstallBuilder\\\\ for\\\\ Qt 8.5.2/bin/Builder.app/Contents/MacOS/installbuilder.sh', shell=True)
一種替代方法是使用外殼和引號:
from subprocess import call call('"/Applications/BitRock InstallBuilder for Qt 8.5.2/bin/Builder.app/Contents/MacOS/installbuilder.sh"', shell=True)
我建議盡可能不要使用shell(主要出於安全原因),請記住,如果不使用shell,則必須將參數作為list
傳遞給命令。
任一種(無殼,有利):
call(['/bin/echo', 'foo', 'bar'])
或帶殼
call('/bin/echo foo bar', shell=True)
(兩個調用的輸出都相同( foo bar\\n
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.