繁体   English   中英

Python子进程调用在Mac OS X上找不到完整路径

[英]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需要知道二进制文件的名称和参数)。 因此,以下所有用法都是正确的(和相似的):

  1. 在不产生产生子进程的外壳的情况下(有利):

     from subprocess import call call('/Applications/BitRock InstallBuilder for Qt 8.5.2/bin/Builder.app/Contents/MacOS/installbuilder.sh') 
  2. 或再次不使用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) 
  3. 但是,当首先告诉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) 
  4. 一种替代方法是使用外壳和引号:

     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.

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